尝试为嵌套实体数组创建表单选择输入。我已经用这种方式"手动"完成了它,但它感觉不是很硬。
<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>
像这样的东西感觉更合适:
$this->Form->input('restauarnt_id', ['options' => $post->city->restaurants, 'empty' => 'Select Restaurant', 'class' => 'form-control', 'label' => false]);
但是这给了我:
<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>
最好的方法是什么?
(Cake Version 3.x)
控制器:
$restaurants = $this->[(whatever $post is)]->Cities->Restaurants->find('list'
'keyField' => 'id',
'valueField' => 'name'
);
$this->set(compact('restaurants'));
在视图:<?= $this->Form->input('retaurant_id', [
'empty' => '--',
'label' => 'Restaurants'
]); ?>
在控制器添加:
$restaurants = $this->Restaurants->find('list');
$this->set(compact('restaurants'));
<<p> 视图/strong> <?= $this->Form->input('restauarnt_id', ['type' => 'select', 'options' => $restaurants, 'empty' => __('Select Restaurant'), 'label' => false]) ?>