Display Image next to HABTM checkboxes

断了今生、忘了曾经 提交于 2020-01-06 13:50:06

问题


Cane Somebody give me an ideas on this Please!

I Generate multiple checkboxes from a table that is related with another table with HABTM relationship association. I would like to generate multiple checkboxes with an image along with the text in the label.

My two tables are items and items_characteristics. So an Item HasAndBelongToMany characteristics, and an ItemCharacteristic HasAndBelongToMany Items.

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

This code generate the list of the checkboxes properly and works perfect: This is what i have:

Which is generated from DB from the table items_characteristics.

And this is what i wanna have:

Does Anyone have any Idea how i can achieve this Please?


回答1:


I assume that in your controller you did something like:

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

so that $data contains the information about selected characteristics in form of a subarray,

edit: I also assume that Item habtm ItemCharacteristic

then in your view

$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
        )
    );
}

edit: from your comment I understand that $itemCharacteristics come from a find('list') statement.

change it into a find('all', array('recursive' => -1));

now your code becomes

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/display-image-next-to-habtm-checkboxes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!