![](/img/trans.png)
[英]Cakephp 2.+ $this->Model->validates(); always return true
[英]cakephp $this->validates multiple recode set many
我正在嘗試驗證表單上動態添加的控件。 我有一份注冊表,可以讓用戶添加1到5個教育信息。 我正在使用Jquery處理添加刪除字段。
HTML代碼
<input name="data[Usereducation][0][schoolname]" id="Usereducation0Schoolname" type="text">
<input name="data[Usereducation][1][schoolname]" id="Usereducation1Schoolname" type="text">
...................
提交后,生成數組as ..
Array ( [0] => Array ( [schoolname] => ) [1] => Array ( [schoolname] => ) [3] => Array ( [schoolname] => )
我的模態具有以下驗證。
public $validate = array(
'schoolname'=>array(
'School Name'=>array(
'rule'=>'notEmpty',
'message'=>'Please enter your School Name.'
)
)
);
在控制器中,我試圖用$this->Usereducation->validates();
來驗證它們$this->Usereducation->validates();
但是什么也沒發生。 有關如何處理此問題的任何建議?
方法1:
使用saveMany一次驗證多個記錄
在您的控制器中,只需使用saveMany/saveAll
方法而不是validates
,因為您有太多要驗證的記錄。
if ($this->UserInformation->saveMany($this->request->data)) {
// do your stuff
} else {
// check the validation errors here.
pr($this->UserInformation->validationErrors);exit;
}
並且您的$this->request->data
應該像這樣
Array(
'Userinformation' => array(
0 => array(
'schoolname' => 'school 0'
),
1 => array(
'schoolname' => 'school 1'
),
2 => array(
'schoolname' => 'school 2'
),
)
)
方法2:
這是一次驗證多個記錄的另一種方法:
如果您想驗證記錄,並且不想執行保存操作,則很有用。
$this->ModelName->validateMany($data['ModelName']);
這里$data
應該如下所示
$data = array(
'ModelName' => array(
'field1' => 'value1'
'field2' => 'value2'
'field3' => 'value3'
)
);
並且您可以使用$this->ModelName->validationErrors
訪問驗證錯誤(驗證失敗)
就你而言
if ($this->UserInformation->validateMany($this->request->data['Userinformation'])) {
// do your stuff
} else {
// check the validation errors here.
pr($this->UserInformation->validationErrors);exit;
}
並且您的$this->request->data
應該像這樣
Array(
'Userinformation' => array(
0 => array(
'schoolname' => 'school 0'
),
1 => array(
'schoolname' => 'school 1'
),
2 => array(
'schoolname' => 'school 2'
),
)
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.