I have added the code in my controller to check if the record is already exists.
public function addAction()
{
$form = new Form();
$request = $this->getRequest();
if ($request->isPost()) {
$role = new Role($this->dbAdapter);
$form->setInputFilter($role->getInputFilter());
$form->setData($request->getPost());
// start here for add validator for already exists same data as entered.
$db = $this->getServiceLocator()->get('Zend\Db\Adapter\Adapter');
$validator = new \Zend\Validator\Db\NoRecordExists(
array(
'table' => 'tbl_roles',
'field' => 'vRoleName',
'exclude' => array(
'field' => 'iRoleID',
'value' => $request->getPost('iRoleID') // note 1
),
'adapter' => $db,
'messages' => array(
\Zend\Validator\Db\NoRecordExists::ERROR_RECORD_FOUND => 'This Role is already exist.',
),
)
);
$form->getInputFilter()->get('vRoleName')->getValidatorChain()->addValidator($validator);
// end here for add validator for already exists same data as entered.
if ($form->isValid()) {
$role->exchangeArray($form->getData());
$this->aclRoleTable->saveRole($role);
$this->flashMessenger()->addMessage('Role Added Successfully.');
return $this->redirect()->toRoute('role');
}
}
return array('form' => $form);
}
Note 1: I have to add here second field to exclude like eDelete = "1", so if record with eDelete = "1" is there then also i can add same role name in my database. Or give me the solution that if record with eDelete=1 is there than not show zend error and i can update it from eDelete = 1 to 0.
Here's what you can do according to ZF2 documentation:
In your getInputFilter()
Model function:
$select = new \Zend\Db\Sql\Select();
$select->from('clientes')
->where(array(
'iRoldId' => $request->getPost('iRoleID'),
'eDelete' => '1',
));
$inputFilter->add($factory->createInput(array(
'name' => 'yourfieldname',
'validators' => array(
array(
'name' => 'Db\NoRecordExists',
'options' => array(
'table' => 'yourtablename',
'field' => 'yourfieldname',
'adapter' => 'youradapter',
//Here comes the magic
'select' => $select,
),
),
),
)));