Question

Using CakePHP (2.3), is there a way to easily add extra parameters to the option element of a select box?

When creating a select dropdown in a template using the following code :

echo $this->Form->input('icon_id', array(
  'label' => 'Icon',
  'empty' => ' ',
  'class' => 'selectbox'
));

The following HTML is output (which is correct) :

<div class="input select">
  <select name="data[Link][icon_id]" class="selectbox" id="LinkIconId">
    <option value=""> </option>
    <option value="16">fa-adjust</option>
    <option value="76">fa-anchor</option>
    <option value="135">fa-archive</option>
    <option value="6">fa-arrow-cicle-o-right</option>
    <option value="10">fa-arrow-circle-o-left</option>
...

My question is, can I programmatically add attributes to the option tag like, and specifically, I'd like to add the data-icon attribute, with the value being the same as the option text? For Example :

    <option value="6" data-icon="fa-arrow-circle-o-right">fa-arrow-cicle-o-right</option>

I have a feeling I might need to write a helper to do this.

Was it helpful?

Solution

$options = array(
                 1 => 'One', 
                 2 => array('name' => 'Two', 'value' => 2,  'class' => 'extra'), 
                 3 => 'Three',
                 6 => array('name' => 'Six', 'value' => 6, "data-icon"=>"fa-arrow-circle-o-right")
);

echo $this->Form->input('my_option_id',array('type' =>'select', 'options'=>$options));

HTML=>

<select name="data[my_option_id]" id="my_option_id">
  <option value="1">One</option>
  <option value="2" class="extra">Two</option>
  <option value="3">Three</option>
  <option value="6" data-icon="fa-arrow-circle-o-right" >Six</option>
</select>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top