代码之家  ›  专栏  ›  技术社区  ›  erlandmuchasaj

在HABTM复选框旁边显示图像

  •  0
  • erlandmuchasaj  · 技术社区  · 10 年前

    有人给我一个主意请!

    我从与另一个具有HABTM关系关联的表相关的表中生成多个复选框。 我想在标签中生成多个带有图像和文本的复选框。

    我的两张桌子是 项目 和items_characteristics。因此,Item HasAndBelongToMany特性和ItemCharacteristic HasAndBelong ToMany项。

    echo $this->Form->input('Item.ItemCharacteristic',array(
        'label' =>false,
        'type'=>'select',
        'multiple'=>'checkbox',
        'options' => $itemCharacteristics ,
        'selected' => $this->Html->value('ItemCharacteristic.ItemCharacteristic')
    ));
    

    这段代码可以正确生成复选框列表,效果非常好: 这就是我所拥有的: enter image description here

    它是从表items_characteristics中的DB生成的。

    这就是我想要的:

    enter image description here

    有人知道我如何做到这一点吗?

    1 回复  |  直到 10 年前
        1
  •  4
  •   arilia    10 年前

    我假设在你的控制器中你做了类似的事情:

    $this->request->data = $this->Item->find('first',  ... ); 
    

    因此 $data 以子阵列的形式包含关于所选特征的信息,

    编辑: 我还假设 Item 哈比姆语 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
    }