ZF2 input filter doctrine NoObjectExists editing object does not check

So, I got the ZF2 application, got the form and input filter in InputFilter, I have:

$this->add( array( 'name' => 'email', 'required' => true, 'validators' => array( array( 'name' => 'EmailAddress' ), array( 'name' => 'DoctrineModule\Validator\NoObjectExists', 'options' => array( 'object_repository' => $sm->get('doctrine.entitymanager.orm_default')->getRepository('YrmUser\Entity\User'), 'fields' => 'email' ), ), ), ) ); 

works fine, however, when I edit an existing object and save it, the NoObjectExists validator says that the corresponding object is found, so it does not check. Is there a solution to this problem? Or should I just remove the validator on the edit form and catch the exception when inserting a duplicate?

UPDATE: How to use DoctrineModule \ Validator \ NoObjectExists in edit forms - Zend Framework 2 and Doctrine 2

- the same problem, but the answer is simply to remove the validator when editing, this non-course is not a solution. Since you still have to catch the exception thrown when inserting the duplicate. I could do it without problems, but what I ask is a solution to make it work WITH NoObjectExists (otherwise use this validator if I have to catch an exception for duplicates anyway)

UPDATE, other appropriate code has been added (my form and entity have more fields than this, but I deleted them so that they are readable here)

FORM:

 namespace YrmUser\Form; use Zend\Form\Form; use DoctrineModule\Stdlib\Hydrator\DoctrineObject as DoctrineHydrator; use DoctrineORMModule\Stdlib\Hydrator\DoctrineEntity; use YrmUser\Entity\User; class UserForm extends Form { protected $objectManager; /** * __construct description * * @param String $name form name * * @return void */ public function __construct($name = null) { parent::__construct('new-user'); } public function init() { $this->setHydrator( new DoctrineHydrator($this->objectManager, 'YrmUser\Entity\User') )->setObject(new User()); $this->setAttribute('method', 'post'); $this->add( array( 'name' => 'email', 'attributes' => array( 'type' => 'email', 'placeholder' =>'Email', ), 'options' => array( 'label' => 'Email', ), ) ); } } 

FILTER:

 class UserFilter extends InputFilter { /** * [__construct description] * * @param ServiceLocator $sm servicelocator */ public function __construct($sm) { $this->add( array( 'name' => 'email', 'required' => true, 'validators' => array( array( 'name' => 'EmailAddress' ), array( 'name' => 'DoctrineModule\Validator\NoObjectExists', 'options' => array( 'object_repository' => $sm->get('doctrine.entitymanager.orm_default')->getRepository('YrmUser\Entity\User'), 'fields' => 'email' ), ), ), ) ); } } 

CONTROLLER ACTION:

 public function editAction() { $id = (int) $this->params('id', null); if (null === $id) { return $this->redirect()->toRoute('manage-users'); } $em = $this->getServiceLocator()->get('Doctrine\ORM\EntityManager'); $formManager = $this->getServiceLocator()->get('FormElementManager'); $form = $formManager->get('UserForm'); $user = $em->find('YrmUser\Entity\User', $id); $form->setInputFilter(new UserFilter($this->getServiceLocator())); $form->bind($user); $request = $this->getRequest(); if ($request->isPost()) { $form->setData($request->getPost()); if ($form->isValid()) { $em->persist($user); $em->flush(); return $this->redirect()->toRoute('manage-users'); } } return array( 'form' => $form, 'id' => $id ); } 

FACE:

 class User { /** * @var int * @ORM\Id * @ORM\Column(type="integer") * @ORM\GeneratedValue(strategy="AUTO") */ protected $id; /** * @var string * @ORM\Column(type="string", unique=true, length=255) */ protected $email; /** * Get id. * * @return int */ public function getId() { return $this->id; } /** * Set id. * * @param int $id user id * * @return void */ public function setId($id) { $this->id = (int) $id; } /** * Get email. * * @return string */ public function getEmail() { return $this->email; } /** * Set email. * * @param string $email user email adress * * @return void */ public function setEmail($email) { $this->email = $email; } } 

thanks in advance,

Yrm

+2
source share
1 answer

Recently, I had the same problem in my project, I spend a lot of time finding a solution, and I finally found this LosBase on Github module.

It uses two custom validators that extend the DoctrineModule\Validator\NoObjectExists : NoEntityExists for Add action and NoOtherEntityExists for Edit action.

So, I used this assessment to solve my problem. This is the solution I have made so far:

Validator NoOtherEntityExists:

 use Zend\Validator\Exception\InvalidArgumentException; use DoctrineModule\Validator\NoObjectExists; class NoOtherEntityExists extends NoObjectExists { private $id; //id of the entity to edit private $id_getter; //getter of the id private $additionalFields = null; //other fields public function __construct(array $options) { parent::__construct($options); if (isset($options['additionalFields'])) { $this->additionalFields = $options['additionalFields']; } $this->id = $options['id']; $this->id_getter = $options['id_getter']; } public function isValid($value, $context = null) { if (null != $this->additionalFields && is_array($context)) { $value = (array) $value; foreach ($this->additionalFields as $field) { $value[] = $context[$field]; } } $value = $this->cleanSearchValue($value); $match = $this->objectRepository->findOneBy($value); if (is_object($match) && $match->{$this->id_getter}() != $this->id) { if (is_array($value)) { $str = ''; foreach ($value as $campo) { if ($str != '') { $str .= ', '; } $str .= $campo; } $value = $str; } $this->error(self::ERROR_OBJECT_FOUND, $value); return false; } return true; } } 

Validator NoEntityExists:

 use Zend\Validator\Exception\InvalidArgumentException; use DoctrineModule\Validator\NoObjectExists; class NoEntityExists extends NoObjectExists { private $additionalFields = null; public function __construct(array $options) { parent::__construct($options); if (isset($options['additionalFields'])) { $this->additionalFields = $options['additionalFields']; } } public function isValid($value, $context = null) { if (null != $this->additionalFields && is_array($context)) { $value = (array) $value; foreach ($this->additionalFields as $field) { $value[] = $context[$field]; } } $value = $this->cleanSearchValue($value); $match = $this->objectRepository->findOneBy($value); if (is_object($match)) { if (is_array($value)) { $str = ''; foreach ($value as $campo) { if ($str != '') { $str .= ', '; } $str .= $campo; } $value = $str; } $this->error(self::ERROR_OBJECT_FOUND, $value); return false; } return true; } } 

Using these validators with inputFilter:

In my custom input filters I added two methods: one to add the NoEntityExists validator, and the other to add the NoOtherEntityExists validator:

 /** * Appends doctrine NoObjectExists Validator for Add FORM . * * @param \Doctrine\ORM\EntityRepository $repository * @return \Zend\InputFilter\InputFilter */ public function appendAddValidator(EntityRepository $repository) { $this->add($this->getFactory()->createInput( array( 'name' => 'libellesite', //unique field name 'validators' => array( array( 'name' => 'Netman\Form\NoEntityExists',//use namespace 'options' => array( 'object_repository' => $repository, 'fields' => 'libellesite', 'messages' => array( 'objectFound' => 'custom message here' ), ), ), ) ))); return $this; } /** * Appends doctrine NoObjectExists Validator for EDIT FORM. * * @param \Doctrine\ORM\EntityRepository $repository * @return \Zend\InputFilter\InputFilter */ public function appendEditValidator(EntityRepository $repository, $id) { $this->add($this->getFactory()->createInput( array( 'name' => 'libellesite', 'validators' => array( array( 'name' => 'Netman\Form\NoOtherEntityExists', 'options' => array( 'object_repository' => $repository, 'fields' => 'libellesite', 'id'=>$id, // 'id_getter'=>'getCodesite',//getter for ID 'messages' => array( 'objectFound' => 'custom message here' ), ), ), ) ))); return $this; } 

Controller:

In addAction :

 $repository = $em->getRepository('Entity\Name'); $form->setInputFilter($filter->appendAddValidator($repository)); 

In editAction :

 $id = $this->params('id', null); $repository = $em->getRepository('Entity\Name'); $form->setInputFilter($filter->appendEditValidator($repository,$id)); 

Hope this helps someone!

+4
source

Source: https://habr.com/ru/post/1234921/


All Articles