I need to add data attributes to individual options in a JHtml generic list in Joomla 2.5.
In standard html, the select list looks like:
<select class="field" placeholder="<?php echo JText::_('COUNTRY')?>" name="country" id="country" autofocus="autofocus" autocorrect="off" autocomplete="off">
<option value="" selected="selected">Select Country</option>
<option value="Afghanistan" data-alternative-spellings="AF">Afghanistan</option>
<option value="Åland Islands" data-alternative-spellings="AX Aaland Aland" data-relevancy-booster="0.5">Åland Islands</option>
<option value="Albania" data-alternative-spellings="AL">Albania</option>
...
</select>
Normally when creating an option I would do:
$options=array();
$options[]=JHTML::_( 'select.option', "Afghanistan", "Afghanistan" );
$options[]=JHTML::_( 'select.option', "Albania", "Albania" );
...
$dropdown = JHTML::_('select.genericlist',$options,'country','id="country" autofocus="autofocus" autocorrect="off" autocomplete="off"','value','text',$default);
How would I add the data-alternative-spellings="AF" to each option?
Thanks
It is in fact possible:
$data = array(
array(
'value' => 'redapple',
'text' => 'Red apple',
'attr' => array('data-price'=>'5'),
),
array(
'value' => 'greenapple',
'text' => 'Green apple',
'attr' => array('data-price'=>'3'),
),
);
$options = array(
'id' => 'applesfield', // HTML id for select field
'list.attr' => array( // additional HTML attributes for select field
'class'=>'field-apples',
),
'list.translate'=>false, // true to translate
'option.key'=>'value', // key name for value in data array
'option.text'=>'text', // key name for text in data array
'option.attr'=>'attr', // key name for attr in data array
'list.select'=>'greenapple', // value of the SELECTED field
);
$result = JHtmlSelect::genericlist($data,'apples',$options);
This will result in:
<select id="applesfield" name="apples" class="field-apples">
<option value="redapple" data-price="5">Red apple</option>
<option value="greenapple" data-price="3" selected="selected">Green apple</option>
</select>
Explanation: I had already extended JHtmlSelect and overridden genericlist() when I found out I really on needed to set an option for genericlist(): 'option.attr'.
The parameters of JHtmlSelect::genericlist() are rather complicated, but simply: if the third parameter is array and it's the last parameter you pass, it will be used to populate genericlist's options.
'option.attr' will set the key for your option's extra attributes. If this is set, you can add as many attributes to your options as you like, as shown in the $data array above.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With