Validation 如何在cakephp3.0验证中的编辑模式下从唯一验证中排除特定字段

Validation 如何在cakephp3.0验证中的编辑模式下从唯一验证中排除特定字段,validation,cakephp-3.0,Validation,Cakephp 3.0,我想验证一个名为survey\u id的字段,它是用户输入的唯一性。添加新记录时,它工作正常并给出正确的响应,但当我试图编辑此记录时,它给出了一个错误[unique]=>提供的值已存在。因此,我想要的是从唯一性检查中排除当前记录的survey\u id,如果用户为survey\u id输入其他值,则应检查唯一性搜索 目前,我正在使用CakePHP 3.0验证和on create验证。以下是我正在使用的验证规则: validator ->requirePresence('su

我想验证一个名为
survey\u id
的字段,它是用户输入的唯一性。添加新记录时,它工作正常并给出正确的响应,但当我试图编辑此记录时,它给出了一个错误
[unique]=>提供的值已存在
。因此,我想要的是从唯一性检查中排除当前记录的
survey\u id
,如果用户为
survey\u id
输入其他值,则应检查唯一性搜索

目前,我正在使用CakePHP 3.0验证和on create验证。以下是我正在使用的验证规则:

validator
        ->requirePresence('survey_id', __('msg_required'))
        ->notEmpty('survey_id', __('msg_required'))
        ->maxlength('survey_id', 32, __('msg_maxlength'))    
        ->add('survey_id', 'unique', ['rule' =>   ['validateUnique',['id']], 'provider' => 'table', 'message' => 'Provided value already exist', 'on'=>'create']);

return $validator;
这个代码有什么问题吗

提前谢谢。
`

它将使用此验证规则

$validator
        ->requirePresence('survey_id', __('msg_required'))
        ->notEmpty('survey_id', __('msg_required'))
        ->maxlength('survey_id', 32, __('msg_maxlength'))
        ->alphaNumeric('survey_id', __('msg_surveyid_format'))
        ->add('survey_id', 'custom', [
            'rule' => function ($value, $context) {
              if (!empty($context['data']['projectId'])) { $values = array($context['data']['projectId']); } else { $values = array(); }
              $data = $this->getSurveyId($value, $values);
              return (!empty($data)) ? false : true;
            },
              'message' => __('msg_surveyid_exsist')]);

        return $validator;
      }

public function getSurveyId($surveyId = null, $exclude = null) {

        $where = array('p.survey_id' => $surveyId);
        if (!empty($exclude) && is_array($exclude)) {
          $where[] = array('p.id NOT IN' => $exclude);
        }
        return $this->db->newQuery()
                        ->select('*')
                        ->from(['p' => 'projects'])
                        ->where($where)
                        ->execute()
                        ->fetch('assoc');
      }

我的用例是用户编辑其他详细信息但不更改调查id?这个验证失败了,因为它不是唯一的!调查id存在于数据库中,它属于试图更改其配置文件其他方面的用户。我们如何处理这件事?或者,如果用户更改并提供其他调查id,则应检查唯一性检查,不包括当前调查。您需要创建自定义验证方法来完成此操作。请参考此请同时检查表/模型中的buildRules()。Hi justrohu我试图创建自定义验证,但如何才能传递表的当前id以将其从当前上下文中排除$validator->add('survey_id','custom',['rule'=>函数($value,$id)use($id){$data=$this->getSurveyId($value,array($id));返回(!empty($data))?false:true;},'message'=>'标题无效']);因此,如何在此上下文中获取$id对于编辑来说,表的当前id存在于$context/request数据中。比创建匿名函数和公共方法更好的是只创建一个方法。在我看来,这将更具可读性:
->添加('survey_id','custom',[$this','validateSurveyId'))
并将所有逻辑放在那里。