Entity exist validation in Zend Framework 2 with Doctrine 2 using inputfilter in entity

安稳与你 提交于 2019-12-03 08:20:49

The problem with putting the NoEntityExists validator in your User class is that it creates a tight coupling between the entity class and the data storage layer. It makes it impossible to use the entity class without Doctrine, or to switch to a new storage layer without rewriting the entity class. This tight coupling is what Doctrine is specifically designed to avoid.

Validators that need to check the database can be kept in a custom EntityRepository class:

class UserRepository extends \Doctrine\ORM\EntityRepository
{
    public function getInputFilter()
    {
        $inputFilter = new \Zend\InputFilter\InputFilter();
        $factory = new \Zend\InputFilter\Factory();

        $inputFilter->add($factory->createInput(array(
            'name' => 'username',
            'validators' => array(
                'name' => '\DoctrineModule\Validator\NoObjectExists',
                'options' => array(
                    'object_repository' => this,
                    'fields' => array('username'),
                ),
            ),
        )));

        return $inputFilter;
    }
}

Make sure to add the necessary annotation to your User entity:

/**
 * @Entity(repositoryClass="MyProject\UserRepository")
 */
class User
{
    //...
}

Then merge the input filters together before passing to your form:

$request = $this->getRequest();
$entityManager = $this->getServiceLocator()->get('Doctrine\ORM\EntityManager');
$repository = $entityManager->getRepository('User');
$user = new User();

$filter = $repository->getInputFilter();
$filter->add($user->getInputFilter());
$form = new Loginform();
$form->setInputFilter($filter);
$form->setData($request->getPost());

if ($form->isValid()) {
    // success
} else {
    // fail
}

Have you tried adding the full namespace to the Validator?

array(
    'name' =>'\Auth\Validator\Doctrine\NoEntityExists', 
    'options' => array(
        'messages' => array(
           \Zend\Validator\NotEmpty::IS_EMPTY => 'User name can not be empty.' 
        ),
    ),

),

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!