请给我个主意吧!
我从与另一个与HABTM关系关联的表关联的表中生成多个复选框。我想要生成多个复选框,连同标签中的文本一起生成图像。
我的两个表是items、和items_characteristics。因此,一个项目的HasAndBelongToMany特征,和一个ItemCharacteristic HasAndBelongToMany项目。
echo $this->Form->input('Item.ItemCharacteristic',array(
'label' =>false,
'type'=>'select',
'multiple'=>'checkbox',
'options' => $itemCharacteristics ,
'selected' => $this->Html->value('ItemCharacteristic.ItemCharacteristic')
));
这段代码正确地生成复选框的列表,并且工作非常完美:这就是我所拥有的:
它是从表items_characteristics的DB生成的。
这就是我想要的
有人知道我怎么能做到这一点吗?
发布于 2014-04-07 04:56:12
我假设在你的控制器里你做了如下的事情:
$this->request->data = $this->Item->find('first', ... );
因此,$data
以子数组的形式包含有关所选特征的信息,
编辑:--我还假设Item
habtm ItemCharacteristic
在你看来
$checked_characteristics = Hash::extract($this->data, 'ItemCharacteristic.{n}.id');
foreach($itemCharacteristics as $id => $itemCharacteristic )
{
$checked = in_array($id, $checked_characteristics );
$img = $this->Html->image('cake.icon.png'); // put here the name
// of the icon you want to show
// based on the charateristic
// you are displayng
echo $this->Form->input(
'ItemCharacteristic.ItemCharacteristic.',
array(
'between' => $img,
'label' => $itemCharacteristic,
'value' => $id,
'type' => 'checkbox',
'checked' => $checked
)
);
}
编辑:从您的评论中,我了解到$itemCharacteristics
来自find('list'
)语句。
将其转换为find('all', array('recursive' => -1));
现在你的代码变成
foreach($itemCharacteristics as $itemCharacteristic )
{
$id = $itemCharacteristic['ItemCharacteristic']['id'];
$icon_name = $itemCharacteristic['ItemCharacteristic']['icon_name']; //or wherever you get your icon path
$img = $this->Html->image($icon_name);
$itemCharacteristicName = $itemCharacteristic['ItemCharacteristic']['name'];
// same as above
}
https://stackoverflow.com/questions/22910137
复制