Temat: Saving HABTM VS dokumentacja
Zrobiłem sobie podsumowanie z doc, zeby to w końcu zrozumieć jak trzeba, ale doc mi togo nie wytłumaczyło.
Znasz się na tym więc nie trać czasu na czytanie :)
Assuming that User hasAndBelongsToMany Group. In your controller, set a camelCase plural variable (group -> groups in this case, or ExtraFunkyModel -> extraFunkyModels) with the select options. In the controller action you would put the following:
$this->set('groups', $this->User->Group->find('list'));
And in the view a multiple select can be created with this simple code:
echo $this->Form->input('Group');
If you want to create a select field while using a belongsTo - or hasOne - Relation, you can add the following to your Users-controller (assuming your User belongsTo Group):
$this->set('groups', $this->User->Group->find('list'));
Afterwards, add the following to your form-view:
echo $this->Form->input('group_id');
If your model name consists of two or more words, e.g., “UserGroup”, when passing the data using set() you should name your data in a pluralised and camelCased format as follows:
$this->set('userGroups', $this->UserGroup->find('list'));
// or
$this->set('reallyInappropriateModelNames', $this->ReallyInappropriateModelName->find('list'));
Other ways we might want to present our associated data can include a select drop down list. The data can be pulled from the model using the find('list') method and assigned to a view variable of the model name. An input with the same name will automatically pull in this data into a <select>:
// in the controller:
$this->set('tags', $this->Recipe->Tag->find('list'));
// in the view:
$this->Form->input('tags');
A more likely scenario with a HABTM relationship would include a <select> set to allow multiple selections. For example, a Recipe can have multiple Tags assigned to it. In this case, the data is pulled out of the model the same way, but the form input is declared slightly different. The tag name is defined using the ModelName convention:
// in the controller:
$this->set('tags', $this->Recipe->Tag->find('list'));
// in the view:
$this->Form->input('Tag');
Using the preceding code, a multiple select drop down is created, allowing for multiple choices to automatically be saved to the existing Recipe being added or saved to the database.