【问题标题】:Require one of several values需要几个值之一
【发布时间】:2019-09-07 01:55:48
【问题描述】:

我有一个包含 5 个布尔列的表。我想强制用户至少选择一个。有没有办法使用 Table PHP 中的 CakePHP $validator 对象来做到这一点?

我可以很容易地在控制器中完成此操作,但使用内置的东西似乎不太错误。文档中的任何内容都没有引起我的注意。 .

控制器示例:

if (false === $val1 === $val2 === $val3 === $val4 === $val5){
   //return with error
}

【问题讨论】:

    标签: cakephp cakephp-3.x cakephp-3.7


    【解决方案1】:

    这似乎是规则的情况,而不是验证。

    public function buildRules(RulesChecker $rules) {
        $rules->add(function (EntityInterface $entity, Array $options) {
            return $entity->val1 || $entity->val2 || $entity->val3 || $entity->val4 || $entity->val5;
        }, 'selectOne', [
            'errorField' => 'val1',
            'message' => __('You must select at least one of these fields.'),
        ]);
    
        return $rules;
    }
    

    【讨论】:

      猜你喜欢
      • 2015-01-02
      • 1970-01-01
      • 2023-02-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-25
      • 1970-01-01
      • 2023-03-28
      相关资源
      最近更新 更多