doulu1907 2016-11-11 18:23 采纳率: 100%
浏览 36

如果实体有关系,CakePHP 3.x自定义验证

Trying to get my head around some slightly more complex custom CakePHP validation rules.

I have Posts that have to be associated with a City Some (larger) cities have SubCities. My Posts table has both city_id and sub_city_id, so in some cases, sub_city_id will be Null.

I have a nice ajax form working that loads and lets you select a SubCity if you've first selected a City that has some. I would like to write a validation rule so you can't have a sub_city_id of Null if SubCities are available on the city_id field.

Any help on the best way to go about this?

  • 写回答

1条回答 默认 最新

  • duanqinqian5299 2016-11-11 20:19
    关注

    Did you try to check the manual? Read about Conditional validation

    When defining validation rules, you can use the on key to define when a validation rule should be applied. If left undefined, the rule will always be applied. Other valid values are create and update. Using one of these values will make the rule apply to only create or update operations.

    Additionally, you can provide a callable function that will determine whether or not a particular rule should be applied:

    $validator->add('picture', 'file', [
        'rule' => ['mimeType', ['image/jpeg', 'image/png']],
        'on' => function ($context) {
            return !empty($context['data']['show_profile_picture']);
        }
    ]);
    

    ↑ This example is taken from the book. So modify it to your needs. Inside the callback put your logic for checking the cities.

    评论

报告相同问题?

悬赏问题

  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别
  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?