1

我要在这里吃香蕉。我创建了一个包含两个字段的简单表单。一个是文本字段,另一个是文本区域。表格看起来很棒,但我不会验证 - 无论我尝试什么。

这是我的表单类:

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'));
}
}

valdiatorsfilters只是我尝试过的许多事情之一......

在我的控制器中,表单始终有效:

    $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?为什么他们不做任何事情时要实现这样的属性?

但仍然:如何验证我的表格?我只想要一个像trimNotEmpty验证器这样的清洁过滤器。

谢谢!

4

1 回答 1

2

在字段上添加 required => true 只是为了美观。

你说的是哪个“如果”?我只看到你回显 isValid?

(抱歉在这里提问,我还不能评论旅游问题,低代表......)

编辑:

正如所承诺的,一个“解决方案”。在您说您自己找到了解决方案之后,我开始写这篇文章,所以我将写下我如何创建表单并将我的表单和验证器放在一起。为了清晰起见,我喜欢将验证器放在我的表单旁边,尽管从技术上来说,将验证器放置在它们所服务的实体中会给你在 API 等方面提供更大的灵活性。

说得够多了,这是我在表单中使用的(非常基本的)字段集的示例:

(我留下了评论,因为一切都应该是不言自明的)

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'
            )
        ));
    }
}
于 2013-11-15T18:09:04.693 回答