我要去香蕉。我创建了一个包含两个字段的简单表单。一个是文本字段,另一个是文本字段。表格看起来不错,但我不会验证 - 无论我尝试什么。
这是我的表单类:
class MyForm extends Form
{
public function __construct()
{
parent::__construct();
$this->add(array(
'name' => 'subject',
'required' => true,
'allowEmpty' => false,
'options' => array(
'label' => 'Betreff*',
),
'type' => 'Zend\Form\Element\Text',
'validators' => array(
// validators for field "name"
new \Zend\Validator\NotEmpty(),
),
'filters' => array(
// filters for field "name"
array('name' => 'Zend\Filter\StringTrim'),
),
));
$this->add(array(
'name' => 'text',
'required' => true,
'allowEmpty' => false,
'options' => array(
'label' => 'Nachricht*',
),
'type' => 'Zend\Form\Element\Textarea',
));
$this->add(new Element\Csrf('security'));
}
}
valdiators
和filters
只是我尝试过的很多事情之一......
在我的控制器中,表单始终有效:
$form = new MyForm();
$request = $this->getRequest();
if ($request->isPost()) {
$form = new MyForm();
$form->setData($request->getPost());
echo $form->isValid();
if($form->isValid()) { ... }
我总是通过if
。
我想知道:当我设置required=true
时,为什么我还需要验证器?为什么他们在没有做任何事情的时候会实现这样的属性?
但仍然:我如何验证我的表格?我只想要一个像trim
和NotEmpty
验证器这样的clenup过滤器。
谢谢!
答案 0 :(得分:2)
添加required =>字段上的true仅用于美容目的。
你在谈论哪个“如果”?我只看到你回应isValid?
(抱歉在这里提问,我不能评论巡回问题,低代表......)
修改强>
按照承诺,一个“解决方案”。在你说你自己找到解决方案后我开始写这篇文章,所以我只是写下我如何创建表单并将表单和验证器放在一起。为了清晰起见,我喜欢将验证器放在我的表单旁边,尽管技术上将验证器置于它们所用的实体中将为您提供更多的灵活性,比如说和API。
足够说,这是我在表单中使用的(非常基本的)Fieldset的示例:
(我留下了评论,因为所有内容都应该是不言自明的)
class RaceUserFieldset extends Fieldset implements InputFilterProviderInterface {
public function __construct() {
parent::__construct('hosts');
$this ->setHydrator(new \Zend\Stdlib\Hydrator\ClassMethods(false))
->setObject(new RaceUser());
$this->add(array(
'name' => 'userid',
'type' => 'hidden',
));
$this->add(array(
'name' => 'username',
'type' => 'Text',
));
}
public function getInputFilterSpecification() {
return array(
'username' => array(
'required' => true,
),
);
}
}
这就好了,实体,保湿器,领域(没有过滤器,但这很容易)和验证器。
以表格形式使用它(简称):
class RaceUserForm extends Form
{
public function __construct()
{
parent::__construct('raceuser');
$this->setAttribute('method', 'post');
$this->add(array(
'type' => 'YCRFront\Form\EditRaceFieldset',
'options' => array(
'use_as_base_fieldset' => true
)
));
$this->add(array(
'name' => 'submit',
'attributes' => array(
'type' => 'submit',
'value' => 'Send'
)
));
}
}