Zf2实体创建自定义过滤器

时间:2015-06-10 08:08:25

标签: filter zend-framework2 entity

public function getInputFilter($em){
if (!$this->inputFilter) {
    $inputFilter = new InputFilter();

    $inputFilter->add(array(
        'name'     => 'fullName',
        'required' => true,
        'filters'  => array(
            array('name' => 'StripTags'),
            array('name' => 'StringTrim'), 
            array('name' => 'SpecialChar')
        ),
        'validators' => array(
            array(
                'name'    => 'StringLength',
                'options' => array(
                    'encoding' => 'UTF-8',
                    'min'      => 5,
                    'max'      => 100,
                ),
            ),
        ),
    ));

    $inputFilter->add(array(
        'name'     => 'password',
        'required' => true,
        'filters'  => array(
            array('name' => 'StripTags'),
            array('name' => 'StringTrim'),
        ),
        'validators' => array(
            array(
                'name'    => 'StringLength',
                'options' => array(
                    'encoding' => 'UTF-8',
                    'min'      => 1,
                    'max'      => 100,
                ),
            ),
        ),
    ));

    $inputFilter->add(array(
        'name'     => 'email',
        'required' => true,
        'filters'  => array(
            array('name' => 'StripTags'),
            array('name' => 'StringTrim'),
        ),
        'validators' => array(
            array(
                'name'    => 'EmailAddress',
            ),
            array(
                'name'  => 'User\Validator\NoEntityExists',
                'options'=>array(
                    'entityManager' =>$em,
                    'class' => 'User\Entity\User',
                    'property' => 'email',
                    'exclude' => array(
                        array('property' => 'id', 'value' => $this->getId())
                    )
                )
            )
        ),
    ));

    $this->inputFilter = $inputFilter;
}

return $this->inputFilter;
}

我想在实体中添加一个名为" Special Char"在所有输入字段中,如何在教条实体中创建自定义过滤器。

我想添加验证以避免实体中的特殊字符,因为我需要在n个地方使用它。

我该如何实现?

1 个答案:

答案 0 :(得分:1)

来自Zend documentation

namespace Application\Filter;

use Zend\Filter\FilterInterface;

class MyFilter implements FilterInterface
{
    public function filter($value)
    {
        // perform some transformation upon $value to arrive on $valueFiltered

        return $valueFiltered;
    }
}

然后你应该能够做到:

$inputFilter->add(array(
    'name'     => 'fullName',
    'required' => true,
    'filters'  => array(
        array('name' => 'Application\Filter\MyFilter')
        …