Trying to create a form selection input for an array of nested entities. I've achieved it this way "manually", but it doesn't feel very cakey.
<select name="restaurant_id" class="form-control" id="restauarnt-id">
<option value="">Select Restaurant</option>
<?php foreach($post->city->restaurants as $restauarnt): ?>
<option value="<?= $restauarnt->id?>"><?= $restauarnt->name ?></option>
<?php endforeach; ?>
</select>
Something like this feel more right:
$this->Form->input('restauarnt_id', ['options' => $post->city->restaurants, 'empty' => 'Select Restaurant', 'class' => 'form-control', 'label' => false]);
but that gives me:
<select name="restauarnt_id" class="form-control" id="restauarnt-id">
<option value="">Select Restaurant</option>
<option value="0">{"id": 1, "city_id": 1, "name": "Some Place"}</option>
</select>
What's the best way to go about it?
(Cake Version 3.x)
in Controller add:
$restaurants = $this->Restaurants->find('list');
$this->set(compact('restaurants'));
In View
<?= $this->Form->input('restauarnt_id', ['type' => 'select', 'options' => $restaurants, 'empty' => __('Select Restaurant'), 'label' => false]) ?>
in Controller:
$restaurants = $this->[(whatever $post is)]->Cities->Restaurants->find('list'
'keyField' => 'id',
'valueField' => 'name'
);
$this->set(compact('restaurants'));
in View:
<?= $this->Form->input('retaurant_id', [
'empty' => '--',
'label' => 'Restaurants'
]); ?>