Composite key type duplicate key check with ZF2 Doctrine

Their are instances when we need to add some composite keys in our DBs. Then we also need a check on application side too. This is also same as duplicate check on multiple fields.

In ZF2, we know about Zend\Validator\Db\RecordExists & Zend\Validator\Db\NoRecordExists combo for duplicate check on database side (Zend DB). Their are also respective relative in doctrine called DoctrineModule\Validator\ObjectExists & DoctrineModule\Validator\NoObjectExists. They do the same job as Zend DB counter part with one caveat.

They do not support multiple fields when work with InputFilters. You can pass array but that gave error "zf2 Provided values count is 1, while expected number of fields to be matched is 2". The solution are using your custom validator.

I tried here to write a Validator Plugin which extends DoctrineModule\Validator\NoObjectExists and have support for multiple fields. See implementation code .

   'name' => 'studentId',
   'required' => true,
   'filters' => array(
   array('name' => 'StripTags'),
   array('name' => 'StringTrim'),
 'validators' => array(
     'name' => 'Student\Validate\NoObjectExists',
     'options' => array(
     'object_repository' => $this->getObjectManager()->getRepository('Student\Entity\Student'),
     'fields' => array('studentId', 'class'),

Validator Plugin Code are as :

namespace Student\Validate;

use DoctrineModule\Validator\NoObjectExists as DoctrineModuleNoObjectExists;

class NoObjectExists extends DoctrineModuleNoObjectExists
  protected $messageTemplates = array(
   self::ERROR_OBJECT_FOUND => "An object matching combination of fields was found",

  public function isValid($value, $context = null)
    $valueArray = array();
    foreach($this->fields as $name => $val)
       $valueArray[] = $context[$val];
    $value = $this->cleanSearchValue($valueArray);

    $match = $this->objectRepository->findOneBy($value);

    if (is_object($match)) {
       $this->error(self::ERROR_OBJECT_FOUND, $value);
       return false;

    return true;

Further link can be found at : Github link

One Reply to “Composite key type duplicate key check with ZF2 Doctrine”

Leave a Reply

Your email address will not be published. Required fields are marked *