Reputation: 691
I have got two models: Rooms and RoomAttributes. There is a many-many relation between them:
$this->hasManyToMany(
"id",
"RoomAttributes",
"roomID",
"attributesID",
"roomattributesrelation",
"id",
array('alias' => 'attributes')
);
Now I'm creating a form to add a new room and I want to have a list of all attributes as checkboxes. What is the best way to do this and how should I save my room model after?
Upvotes: 2
Views: 472
Reputation: 46
Maybe something like this:
use Phalcon\Forms\Element\Select;
class RoomForm extends \Phalcon\Forms\Form {
$attr_arr = ['attr1_id' => 'attr1_name', 'N_id' => 'N_name'];
// or $attr_arr= array_column(RoomAttributes::find()->toArray(),'id','name')
$attributes = new Select(
'attributes[]',
$attr_arr ,
['multiple' => 'multiple'
]);
$this->add($attributes);
}
in controller
****
if($new_room->save()){
$attributes = $_POST['attributes'];
foreach ($attributes as $id){
$new_attribute = new RoomAttributes();
$new_attribute->roomID = $new_room->id;
$new_attribute->attributesID = $id;
$new_attribute->save();
}
}
Upvotes: 1