(本文的上文请参看:http://q.115.com/t-153332-57128.html)
这很明显是用原始方式形成渲染的部件。HTML的部件已经超出了Konstrukt的范围之外,但你可以使用第三方的库,如Zend_Form的,生成的HTML。如果你使用一个真正的模板引擎,它也提供了一种方式。
要访问表单,我们需要添加视图页面的链接,编辑templates/contacts-entity.tpl.php:
<h2><?phpe($contact->short_name());?></h2>
<dl>
<dt>FirstName</dt>
<dd><?phpe($contact->first_name());?></dd>
<dt>LastName</dt>
<dd><?phpe($contact->last_name());?></dd>
<dt>Email</dt>
<dd><?phpe($contact->email());?></dd>
</dl>
<p>
<ahref="<?php e(url('', array('edit')));?>">edit</a>
</p>
你可以通过点击url:contacts/jabba?edit.访问表单,一般而言,Konstruct需要将其翻译为renderHtmlEdit并调度它的方法。
现在我们需要一个展示的form,我们仍然需要处理它将产生的POST请求,Time可以为我们的组件添加更多的方法。
<?php
classcomponents_contacts_Entityextendsk_Component{
functionpostForm(){
if($this->process()){
returnnewk_SeeOther($this->url());
}
return$this->render();
}
functionprocess(){
global$contacts;
$this->contact =newContact(
array(
'short_name'=>$this->contact->short_name(),
'first_name'=>$this->body("first_name"),
'last_name'=>$this->body("last_name"),
'email'=>$this->body("email")
));
if(!$this->contact->first_name()){
@$this->contact->errors[]="Missing first_name";
}
if(!$this->contact->last_name()){
@$this->contact->errors[]="Missing last_name";
}
if(!$this->contact->email()){
@$this->contact->errors[]="Missing email";
}
if(!isset($this->contact->errors)){
try{
$contacts->save($this->contact);
}catch(Exception$ex){
@$this->contact->errors[]=$ex->getMessage();
returnfalse;
}
returntrue;
}
returnfalse;
}
...
本教程并不是针对模型层,实施的process()保持简单。你可以在省略的领域测试失败案例。否则entity就会保存到数据库。
这postForm()方法虽然简洁,在操作过程中,还是有几句话比较实用。如果过程顺利,我们生成一个重定向。在这个例子中,它是一个url重定向的组件。假如成功,它将为用户返回一个默认的展示。如果有失败,form就会重新显示。注意,在最后面,我们必须明确的调度render()。如果没有,我们就得到一个空白页。
这种模式一般被认为“redirect after post”或者"post-redirect-get"(PRG)。这意味着一旦表单形成了,那么POST行为不会被存储到客户端浏览器历史记录。假如不这样做,使用浏览器的“back”键将会重新提交表单。你可能已经在一个网站上经历了这种麻烦的行为不只一次了。
注意,只有表单成功的被处理了,重定向才产生。