0

I want to create them as objects and then assign options, smth like:

$name = new Zend\Form\Element\Text('name');
$name->setLabel('Your name:');
$name->setRequired(true); // does not work?
$this->add($name);

How it is possible set options like "required" one there, how to set validators? Framework throws exception "No method exists" for setRequired() one.

P.S. I really don't want to use array-style, it's quite annoying when you have tons of code in one array. I mean the following:

$this->addElement('text', 'email', array(
        'label'      => 'Your email address:',
        'required'   => true,
        'filters'    => array('StringTrim'),
        'validators' => array(
            'EmailAddress',
        )
    ));
4

2 回答 2

2

您误解了一件事,默认情况下验证器不是元素的一部分。

如果你想要一个元素本身包含一些验证器。您需要使元素实现 InputProviderInterface 例如

use Zend\Form\Element;
use Zend\InputFilter\InputProviderInterface;
class MyElement extends Element implements InputProviderInterface
{
    public function getInputSpecification()
    {
        $spec = array(
            'name' => $this->getName(),
            'required' => true,
            'validators' => array(
                'EmailAddress',
            )
        );

        return $spec;
    }
}

当表单验证开始时,表单的 InputFilter 将从表单元素中收集所有验证器并合并到最后一个。

但是,您也可以通过处理表单 InputFilter 动态添加/删除表单验证器:

$form = new \Zend\Form\Form();
$form->add($yourElement);
$filter = $form->getInputFilter();
$filter->remove('email');
$filter->add(array(
    'name' => 'email',
    'required' => true,
    'validators' => array (
        'EmailAddress'
    ),
));
$form->setInputFilter($filter);
$form->setData(array(
    'email' => 'abc',
));
$form->prepare();
echo $form->isValid();
print_r($form->getMessages());
于 2012-12-25T08:26:34.877 回答
0

Zend 表单选项 setRequired true 仅适用于选项验证器。您必须像这样为此元素定义验证规则。

$this->review->addValidators(

array('NotEmpty',true, array( 'messages' => array( 'isEmpty' => "Please enter product Review.") ) )

);
于 2013-02-13T09:09:49.683 回答