Unique record validation in ZF2 forms

Controller code:

$employeeInfoValidator = new EmployeeInfoValidator();
 
$dbAdapter = $this->getServiceLocator()->get('Zend\Db\Adapter\Adapter');
$employeeInfoValidator->data = array(
	'UserId' => $userId,
	'CoveredPersonDependentId' => $dependentId
);
 
$employeeInfoValidator->setDbAdapter($dbAdapter);
$form->setInputFilter($employeeInfoValidator->getInputFilter());

Validator class:

dbAdapter = $dbAdapter;
    }

    public function setInputFilter(InputFilterInterface $inputFilter)
    {
        throw new \Exception("Not used");
    }

    public function getInputFilter($type = null)
    {
        if (!$this->inputFilter) {
            $inputFilter = new InputFilter;
            $factory = new InputFactory;

            $clause = null;
            if (!empty($this->data['DependentId']) && !empty($this->data['UserId'])) {
                $clause = 'DependentId != ' . (string)intval($this->data['DependentId']) . ' AND UserId = ' . (string)intval($this->data['UserId']);
            } elseif (!empty($this->data['UserId'])) {
                $clause = 'UserId = ' . (string)intval($this->data['UserId']);
            }

            $inputFilter->add($factory->createInput(array(
                'name' => 'DependentType',
                'required' => true,
                'validators' => array(
                    array(
                        'name' => '\Zend\Validator\Db\NoRecordExists',
                        'options' => array(
                            'table' => 'Dependent',
                            'field' => 'DependentType',
                            'adapter' => $this->dbAdapter,
                            'exclude' => $clause,
                            'messages' => array(
                                \Zend\Validator\Db\NoRecordExists::ERROR_RECORD_FOUND => 'A spouse is already defined',
                            ),
                        ),
                    ),
                ),
            )));

            $this->inputFilter = $inputFilter;
        }

        return $this->inputFilter;
    }
}

Share This:

Leave a comment

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