I have some group of inputs each with same name, as shown in the picture
I want to save each category with each number of rooms and standard rate. All category inputs have the same name (<input name="category[]">
) same for No. of rooms and standard rate.
So far I've tried:
foreach($data['category'] as $cat){
$this->Model->save($cat)
//Will save only categories without No. of rooms and standard rate.
}
Is there a way I can foreach
through the 3 groups of inputs and save data in different rows accordingly? My table columns are named after inputs name.
Are you able to send this type of format to your controller, then you can use saveMany() function in Caek php "
http://book.cakephp.org/2.0/en/models/saving-your-data.html
$data = array(
array('field1' => 'valuea', 'field2' => 'valuea'),
array('field1' => 'valueb', 'field2' => 'valueb'),
array('field1' => 'valuec', 'field2' => 'valuec')
)
or in
$data = array(
array('Model' => array('field1' => 'valuea', 'field2' => 'valuea')),
array('Model' => array('field1' => 'valueb', 'field2' => 'valueb')),
array('Model' => array('field1' => 'valuec', 'field2' => 'valuec'))
)
format.
You can do like this $this->Model->saveMany($data);
This is simple to achieve using the FormHelper and saveMany
. Firstly in your View you want to include the form elements using the FormHelper using something like:-
echo $this->Form->input('Model..category');
Where you need to replace Model
with your model alias. The ..
will cause it to output an input with a name like Model[][category]
. If you want to control the numeric index (for example in a loop to associate it with other fields) you can change this to $this->Form->input('Model.1.category')
which would produce an input with the name Model[1][category]
.
Then in your controller you can save this data using saveMany
:-
$this->Model->saveMany($this->request->data);
Again replacing Model
with your model's alias.