为什么这种形式一直无效

时间:2015-06-09 22:17:14

标签: php forms validation zend-framework orm

我有这个只有一个字段的表单,方法isValid()会一直处理它,好像每次提交它时它都是无效的,我一直在提交它应该是的文本

//form
class CategoryForm extends Form
{
 public function __construct()
 {
    parent::__construct('category');

    $this->setAttribute('method', 'post');

    $this->add(array(
        'name' => 'name',
        'type'  => 'text',
        'options' => array('label' => 'Name',),
        'required' => true,
            'filters'  => array(
                array('name' => 'StripTags'),
                array('name' => 'StringTrim'),
            ),
    ));

    $this->add(array(
        'name' => 'submit',
        'attributes' => array(
            'type'  => 'submit',
            'value' => 'Save',
            'id' => 'submitbutton',
        ),
    ));
 }
}

这将是错误的部分,我嘲笑,因为它有点工作,没有错误信息。

//validation clause at controller
 $category = new Category;
 $form = new CategoryForm();
 $form->bind($category);
 $request = $this->getRequest();

    if ($request->isPost()) {
        $form->setInputFilter($category->getInputFilter());
        $form->setData($request->getPost());

        if ($form->isValid()) {
            $em = $this->getEntityManager();
            $em->persist($category);
            $em->flush();

            $this->flashMessenger()->addSuccessMessage('category Saved');

            return $this->redirect()->toRoute('category');
        }
    }

如果我将代码更改为此,则会保留数据

public function addAction()
{
    $form = new CategoryForm();
    $form->get('submit')->setValue('Add');

    $request = $this->getRequest();
    if ($request->isPost()) {
        $category = new category();
        $form->setInputFilter($category->getInputFilter());
        $form->setData($request->getPost());
        $form->isValid();

        $category->exchangeArray($form->getData());
        $em = $this->getEntityManager();
        $em->persist($category);
        $em->flush();
        $this->flashMessenger()->addSuccessMessage('Category Saved');
        return $this->redirect()->toRoute('category');
    }
     return new ViewModel(array(
        'category' => $category,
        'form' => $form
    ));
}

1 个答案:

答案 0 :(得分:1)

您是否在验证之前将提交的值传递给表单?

我通常做这样的事情:

if ($this->_request->isPost() && $form->isValid($this->getRequest()->getPost())) { 
...
Your save code here...

如果您这样做,请检查表单中是否出现了验证错误......

var_dump($form->getMessages());