JHTML通用列表将数据属性添加到选项Joomla 2.5中

pat*_*her 4 joomla joomla2.5

我需要在Joomla 2.5的JHtml通用列表中为各个选项添加数据属性.

在标准html中,选择列表如下所示:

<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>
Run Code Online (Sandbox Code Playgroud)

通常在创建选项时我会这样做:

$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);
Run Code Online (Sandbox Code Playgroud)

如何为每个选项添加data-alternative-spellings ="AF"?

谢谢

Ola*_*kin 13

事实上可能:

$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);
Run Code Online (Sandbox Code Playgroud)

这将导致:

<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>
Run Code Online (Sandbox Code Playgroud)

说明:我已经延长JHtmlSelect和重写genericlist() ,当我发现我真的上设置genericlist一个选项()需要:"option.attr".

JHtmlSelect :: genericlist()的参数相当复杂,但很简单:如果第三个参数是数组,并且它是您传递的最后一个参数,它将用于填充genericlist的选项.

'option.attr'将为您选项的额外属性设置关键字.如果设置了此项,您可以根据需要为选项添加任意数量的属性,如上面的$ data数组所示.