具有多个排除选项问题的Zend db \ NoRecordExists

时间:2014-01-17 05:44:46

标签: php forms zend-framework zend-db zend-validate

我已在控制器中添加了代码以检查记录是否已存在。

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.

2 个答案:

答案 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,
            ), 
        ), 
    ),
)));