I am trying to validate dynamically added controls on the form. I have a registration form where I have an option for users to add 1 to 5 education info. I am using Jquery to handle add remove fields.
HTML Code
<input name="data[Usereducation][0][schoolname]" id="Usereducation0Schoolname" type="text">
<input name="data[Usereducation][1][schoolname]" id="Usereducation1Schoolname" type="text">
...................
On submission this generates the array as..
Array ( [0] => Array ( [schoolname] => ) [1] => Array ( [schoolname] => ) [3] => Array ( [schoolname] => )
My modal has following validation.
public $validate = array(
'schoolname'=>array(
'School Name'=>array(
'rule'=>'notEmpty',
'message'=>'Please enter your School Name.'
)
)
);
In the controller I am trying to validate these with $this->Usereducation->validates();
But nothing happens. Any suggestions on how to handle this?
Method 1:
Use saveMany For validating the multiple records at once
In your controller just use saveMany/saveAll
method of model instead of validates
, since you're having too many records to validated.
if ($this->UserInformation->saveMany($this->request->data)) {
// do your stuff
} else {
// check the validation errors here.
pr($this->UserInformation->validationErrors);exit;
}
and your $this->request->data
should be like this
Array(
'Userinformation' => array(
0 => array(
'schoolname' => 'school 0'
),
1 => array(
'schoolname' => 'school 1'
),
2 => array(
'schoolname' => 'school 2'
),
)
)
Method 2:
Here is an another way of validating multiple records at once:
If you want to validate the records, and don't want to perform save operation it is useful..
$this->ModelName->validateMany($data['ModelName']);
Here $data
should look like as below
$data = array(
'ModelName' => array(
'field1' => 'value1'
'field2' => 'value2'
'field3' => 'value3'
)
);
And you can access the validation errors (on unsuccessful validation) Using $this->ModelName->validationErrors
In Your case
if ($this->UserInformation->validateMany($this->request->data['Userinformation'])) {
// do your stuff
} else {
// check the validation errors here.
pr($this->UserInformation->validationErrors);exit;
}
and your $this->request->data
should be like this
Array(
'Userinformation' => array(
0 => array(
'schoolname' => 'school 0'
),
1 => array(
'schoolname' => 'school 1'
),
2 => array(
'schoolname' => 'school 2'
),
)
)