简体   繁体   English

以ZendFramework2形式设置验证器

[英]Set validators in form ZendFramework2

I'm trying to write my first form in ZF2 and my code is 我正在尝试用ZF2编写我的第一个表格,我的代码是

                namespace Frontend\Forms;
            use Zend\Form\Form;
            use Zend\Validator;

            class Pagecontent extends Form
            {
                public function __construct($name = null)
                {
                    // we want to ignore the name passed
                    parent::__construct('logo');
                    $this->setAttribute('method', 'post');      
                    $this->add(array(
                        'name' => 'content_yes_no',
                        'type'=>'text',
                        'required' => true,
                        'validators' => array(
                                'name' => 'Alnum',
                                'options'=>array(
                                    'allowWhiteSpace'=>true,
                                ),
                        ),
                    ));
                }
            }

I want to know can I set validators like this? 我想知道我可以设置验证器吗? Please advice 请指教

You've got to surround validators by another array: 您必须用另一个数组包围验证器:

'validators' => array(
        array(
                        'name' => 'Alnum',
                        'options' => array(
                                'allowWhiteSpace'=>true,
                        ),
        ),
),

You can use Input Filter component: 您可以使用输入过滤器组件:

<?php
namespace Frontend\Forms;

use Zend\Form\Form;
use Zend\Validator;
use Zend\InputFilter\Factory as InputFactory;
use Zend\InputFilter\InputFilter;

class Pagecontent extends Form
{

    public function __construct($name = null)
    {
        ...
        $inputFilter = new InputFilter();
        $factory     = new InputFactory();
        $inputFilter->add($factory->createInput(array(
            'name'     => 'content_yes_no',
            'required' => true,
            'filters'  => array(),
            'validators' => array(
                array(
                    'name' => 'Alnum',
                    'options' => array(
                        'allowWhiteSpace' => true,
                    ),
                ),
            ),
        )));

        $this->setInputFilter($inputFilter);
    }
}

// your controller //您的控制器

$form = new \Frontend\Forms\Pagecontent();
$form->setData($request->getPost());

if ($form->isValid()) {
    // your code
}

To setup filters and validators you need an inputFilter. 要设置过滤器和验证器,您需要一个inputFilter。 Typically you will find the inputFilter defined in the form class or associated model class. 通常,您会在表单类或关联的模型类中找到定义的inputFilter。 Here is a template for a form. 这是表格的模板。

<?php
/* All bracket enclosed items are to be replaced with information from your 
 * implementation. 
 */
namespace {Module}\Form;

class {Entity}Form
{
    public function __construct()
    {
        // Name the form
        parent::__construct('{entity}_form');

        // Typically there is an id field on the form
        $this->add(array(
            'name' => 'id',
            'type' => 'Hidden',
        ));

        // Add a csrf field to help with security
        $this->add(array(
            'type' => 'Zend\Form\Element\Csrf',
            'name' => 'csrf'
        ));

        // Add more form fields here
        $this->add(array(
            'name' => 'example',
            'type' => 'Text',
            'options' => array(
                'label' => 'Example',
            ),
        ));

        //Of course we need a submit button
        $this->add(array(
            'name' => 'submit',
            'type' => 'Submit',
            'attributes' => array(
                'value' => 'Submit',
                'id' => 'submitbutton',
            ),
        ));
    }
}

The form defines all of the elements that will be displayed in the form. 表单定义了将在表单中显示的所有元素。 Now, you can either create the inputFilter in the form's class or in a model that is associated with the form's class. 现在,您可以在表单的类中或与表单的类关联的模型中创建inputFilter。 Either way it would look like: 不管哪种方式,它都看起来像:

<?php
/* All bracket enclosed items are to be replaced with information from your 
 * implementation. 
 */
namespace {Module}\Model;

/*
 * Include these if you require input filtering. 
 */
use Zend\InputFilter\Factory as InputFactory;   
use Zend\InputFilter\InputFilter;                
use Zend\InputFilter\InputFilterAwareInterface;  
use Zend\InputFilter\InputFilterInterface;   

class {Model} implements InputFilterAwareInterface 
{
    /*
     * Add in model members as necessary
    */
    public $id;
    public $example;

    /*
     * Declare an inputFilter
     */
    private $inputFilter;

    /*
     * You don't need a set function but the InputFilterAwareInterface makes
     * you declare one
     */
    public function setInputFilter(InputFilterInterface $inputFilter)
    {
        throw new \Exception("Not used");
    }

    /*
     * Put all of your form's fields' filters and validators in here
     */
    public function getInputFilter()
    {
        if (!$this->inputFilter) 
        {
            $inputFilter = new InputFilter();
            $factory     = new InputFactory();

            $inputFilter->add($factory->createInput(array(
                'name'     => 'id',
                'required' => true,
                'filters'  => array(
                    array('name' => 'Int'),
                ),
            )));

            // This example input cannot have html tags in it, is trimmed, and 
            // must be 1-32 characters long
            $inputFilter->add($factory->createInput(array(
                'name'     => 'example',
                'required' => false,
                'filters'  => array(
                    array('name' => 'StripTags'),
                    array('name' => 'StringTrim'),
                ),
                'validators' => array(
                    array(
                        'name'    => 'StringLength',
                        'options' => array(
                            'encoding' => 'UTF-8',
                            'min'      => 1,
                            'max'      => 32,
                        ),
                    ),
                ),
            )));

            $this->inputFilter = $inputFilter;
        }

        return $this->inputFilter;
    }
}

Then when you are programming your controller's action you can bring it all together like this: 然后,当您对控制器的动作进行编程时,可以将其全部组合在一起,如下所示:

if($request->isPost())
{
    $model = new Model;
    $form->setInputFilter($model->getInputFilter());
    $form->setData($request->getPost());

    if ($form->isValid()) 
    {
        // Do some database stuff
    }
}

Notice that we get the inputFilter from the model and use the form's setInputFilter() method to attach it. 注意,我们从模型中获取inputFilter,并使用表单的setInputFilter()方法将其附加。

To summarize, You must create a form class to place all of your form elements in, then create an inputFilter to hold all of your filters and validators. 总而言之,您必须创建一个表单类来放置所有表单元素,然后创建一个inputFilter来容纳所有过滤器和验证器。 Then you can grab the inputFilter in the controller and apply it to the form. 然后,您可以在控制器中获取inputFilter并将其应用到表单。 Of course this is just a couple ways to skin a cat though. 当然,这只是给猫皮剥皮的几种方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM