Zf2 entity create a custom filters

118 views Asked by At
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;
}

I want to add a new function in entity called "Special Char" in all input fields, so how does one create a custom filter in a doctrine entity.

I want to add validation to avoid special char in entity because I need to use this in n no of places.

How do I implement this?

1

There are 1 answers

0
danopz On

From 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;
    }
}

Then you should be able to do:

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