What is the most effective way to use DoctrineModule\Validator\NoObjectExists
validator in a Zend Form that is used for editing also? Because when I use the same Form for saving edited values, this validates the Object existence and flags form is invalid.
Few weeks ago I resolved the same problem using a helper method in my custom filter. I am not sure if this is the correct approach but it works.
Zend\InputFilter\InputFilter
.init()
method of filter.So,
<?php
/**
* Baz filter
*/
class BazFilter extends Zend\InputFilter\InputFilter
{
/**
* This method will be triggered automatically when you retrive baz filter via inputfiltermanager.
*/
public function init()
{
// Define your input names, types, validators and filters as arrays
$this->add(array(
'name' => 'code',
'required' => true,
'validators' => array(),
'filters' => array()
));
$this->add( array(...) );
$this->add( array(...) );
// ...
}
/**
* Appends doctrine's noobjectexists validator to validator chain only when required.
*
* @access public
* @param \Doctrine\ORM\EntityRepository $repository
* @return \Zend\InputFilter\InputFilter
*/
public function appendExistenceValidator(\Doctrine\ORM\EntityRepository $repository)
{
$validatorSignature = array(
'name' => 'code',
'validators' => array(
array(
'name' => 'DoctrineModule\Validator\NoObjectExists',
'options' => array(
'object_repository' => $repository,
'fields' => 'code',
'messages' => array( NoObjectExists::ERROR_OBJECT_FOUND => "This object with code already exists in database." )
)
)
)
);
$validator = $this->getFactory()->createInput( $validatorSignature );
$this->add($validator);
return $this;
}
}
Finally, append this inputfilter to your form when editing:
// $form = your form instance
// $filter = Bazfilter instance
$form->setData($postData)->setInputFilter( $filter );
if( $form->isValid() === false ) {
// ...
}
When creating:
// $filter = bazfilter instance
$repository = $entityManager->getRepository('Your\Entity\Name');
$filter->appendExistenceValidator( $repository ); // <-- Notice this line
$form->setData($postData)->setInputFilter( $filter );
if( $form->isValid() === false ) {
// ...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With