cakephp:基于另一个字段的模型验证

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是通过值传递的,而不是方法签名所要求的引用。引用自定义验证方法没有要传递的内容,因此只需删除&或分别从签名中完全删除第一个参数。

传递给自定义验证方法的第一个参数将始终是要验证的字段的数据(以key => value格式),然后是在rule数组中定义的可能参数,例如您的字段名。因此,除非您在rule数组中定义了null,即'rule' => array('if_query_other', null),否则$check永远不会是null,因此,您的第三个参数将永远不是字段名。

长话短说,您只需要定义两个参数,第一个将包含要验证的字段的数据,第二个是在rule数组中定义的附加值。

下面是一个示例,它检查在$query_field中传递的字段是否存在以及其值是否等于Other,如果返回,则返回当前字段的值是否不为空(我假设Validation::notEmpty()中的内容足以满足您的"非空"检查需求。如果$query_field字段的值不等于Other,则此规则将始终成功验证,即,则不需要该值不为空。

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;
    }
}