[英]CakePHP 3.x custom validation if entity has relation
Trying to get my head around some slightly more complex custom CakePHP validation rules. 试图绕过一些稍微复杂的自定义CakePHP验证规则。
I have Posts
that have to be associated with a City
Some (larger) cities have SubCities
. 我有必须与
City
关联的Posts
一些 (较大的)城市有SubCities
。 My Posts
table has both city_id
and sub_city_id
, so in some cases, sub_city_id
will be Null. 我的
Posts
表同时具有city_id
和sub_city_id
,因此在某些情况下, sub_city_id
将为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. 我有一个很好的ajax表单,可以加载并允许您选择
SubCity
如果您首先选择的是一个City
。 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. 我想编写一个验证规则,以便在
city_id
字段上可用sub_city_id
的情况下, SubCities
不能为Null。
Any help on the best way to go about this? 对解决此问题的最佳方法有帮助吗?
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.
定义验证规则时,可以使用on键定义何时应应用验证规则。 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.
在回调中放入检查城市的逻辑。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.