cakephp: model validation based on another field
我正在尝试在一个字段上设置模型验证,仅当另一个字段等于特定值时才需要检查。
我的第一个字段是query,这是一个包含许多值的下拉列表,如果选择此值,则是\\'Other \\',那么我需要第二个字段\\'query_other \\'不能为空。
我的物品模型中有此设置:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | public $validate = array( 'query' => array( 'notempty' => array( 'rule' => array('notempty'), 'message' => 'THE QUERY IS REQUIRED', //'allowEmpty' => false, //'required' => false, //'last' => false, // Stop validation after this rule //'on' => 'create', // Limit validation to 'create' or 'update' operations ), ), 'query_other' => array( 'notempty' => array( 'rule' => array('if_query_other', 'query'), 'message' => 'REASON IS REQUIRED', //'allowEmpty' => false, //'required' => false, //'last' => false, // Stop validation after this rule //'on' => 'create', // Limit validation to 'create' or 'update' operations ), ), ); |
然后我有了上面自定义的自定义函数。
1 2 3 4 5 6 7 8 9 10 11 | function if_query_other(&$data, $check, $query_field) { if($this->data[$this->name][$query_field] == 'Other' && $check == NULL) { return false; } else { return true; } } |
它不起作用,我当前遇到此错误:Item :: if_query_other()的参数1应该是引用,给定值
CakePHP版本2.3.6
谢谢
错误消息非常清楚,参数1是通过值传递的,而不是方法签名所要求的引用。引用自定义验证方法没有要传递的内容,因此只需删除
传递给自定义验证方法的第一个参数将始终是要验证的字段的数据(以
长话短说,您只需要定义两个参数,第一个将包含要验证的字段的数据,第二个是在
下面是一个示例,它检查在
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | ... App::uses('Hash', 'Utility'); App::uses('Validation', 'Utility'); class Item extends AppModel { ... public function if_query_other($check, $query_field) { if(Hash::get($this->data[$this->alias], $query_field) === 'Other') { return Validation::notEmpty(current($check)); } return true; } } |