gpt4 book ai didi

cakephp - CakePHP 中的 HABTM 表单验证

转载 作者:行者123 更新时间:2023-12-04 16:15:27 25 4
gpt4 key购买 nike

我有一个项目表和一个用户表,它们通过 HABTM 关系链接。在“添加”新项目页面中,我有一个多个复选框部分,用于为新项目选择用户。我希望该项目至少有一名用户。在 CakePHP 中解决这个问题的最佳方法是什么?

最佳答案

尝试这个:

// app/models/project.php
/**
* An additional validation check to ensure at least one User is
* selected. Spoofs Cake into thinking that there are validation
* errors on the Project model by invalidating a non-existent field
* on the Project model, then also invalidates the habtm field as
* well, so when the form is re-displayed, the error is displayed
* on the User field.
**/
function beforeValidate() {
if (!isset($this->data['User']['User'])
|| empty($this->data['User']['User'])) {
$this->invalidate('non_existent_field'); // fake validation error on Project
$this->User->invalidate('User', 'Please select at least one user');
}
return true;
}

关于cakephp - CakePHP 中的 HABTM 表单验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2044102/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com