我已在控制器中添加了代码以检查记录是否已存在。
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);
}
注1:我必须在这里添加第二个字段以排除eDelete =“1”,所以如果有eDelete =“1”的记录,那么我也可以在我的数据库中添加相同的角色名称。 或者给我一个解决方案,如果使用eDelete = 1的记录而不是显示zend错误,我可以将它从eDelete = 1更新为0.
答案 0 :(得分:0)
根据Zend Code of Class Zend_Validate_Db_Abstract
,它是Zend_Validate_Db_NoRecordExists
的父类,你可以为'exclude'属性提供字符串/数组,
/* 'exclude' => An optional where clause or field/value pair to exclude from the query
所以你可以试试
'exclude' => 'iRoldId = ' . $request->getPost('iRoleID') . ' AND eDelete = "1"'
和Zend会给出结果true
。
答案 1 :(得分:0)
根据ZF2 documentation,您可以执行以下操作:
在getInputFilter()
模型功能中:
$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,
),
),
),
)));