这一篇比较简单,主要将如何用zendframework生成一个可以提交的表单。下面来讲步骤。
【使用命令行生成form】
在你可以在application文件夹下看到新建了个forms文件夹,里面有一个form,名字为Guestbook,下一步就是修改该form。
【修改该form,用于后来生成静态页面】
<?php
class Application_Form_Guestbook extends Zend_Form
{
public function init()
{
$this->setMethod('post');
//添加邮箱元素
$this->addElement('text','email',array(
'label' => '邮箱地址:',
'required' => true,
'filters' => array('StringTrim'),
'validators'=>array('EmailAddress',)
));
// 添加评论元素
$this->addElement('textarea', 'comment', array(
'label' => '添加评论:',
'required' => true,
'validators' => array(
array('validator' => 'StringLength', 'options' => array(0, 20))
)
));
//添加验证码元素
$this->addElement('captcha', 'captcha', array(
'label' => '输入4位验证码:',
'required' => true,
'captcha' => array(
'captcha' => 'Figlet',
'wordLen' => 4,
'timeout' => 300
)
));
//添加提交按钮
$this->addElement('submit','submit',array(
'ignore' => true,
'label' => '添加',
));
}
}
代码比较简单,这里就不讲了
【使用命令行为Guestbook这个controller添加一个sign方法(也成为action)】
从上图的提示,我们可以看到,我们在Guestbook这个controller里添加了一个名为sign的action,并且在view/scripts/guestbook中自动添加了相应的signb.phtml视图页面
【完善Guestbook这个controller里的signAction】
public function signAction()
{
$request = $this->getRequest();
$form = new Application_Form_Guestbook();
if ($this->getRequest()->isPost()) {
if ($form->isValid($request->getPost())) {
$comment = new Application_Model_Guestbook($form->getValues());
$mapper = new Application_Model_GuestbookMapper();
$mapper->save($comment);
return $this->_helper->redirector('index');
}
}
$this->view->form = $form;
}
这个比较简单,主要就是最有一条语句,将form赋值给了视图的view变量。
【在视图页显示表单】
添加guestbook页面</br>
<?php
$this->form->setAction($this->url());
echo $this->form;
至此,我们quickstart课程全部结束。但是我们学习zendframework的脚步会继续下去。
所以,我会继续我的后续博文,希望大家能够互勉,一起进步!