aga*_*ode 5 php arrays jquery laravel
有没有一种方法可以将HTML属性添加到带有blade的下拉选择中的选项中Form::select()?
好吧,因为我需要这样的东西:(向option标签添加不同的CSS类)
<select id="colors" name="colors">
<option value="1" class="blue">blue</option>
<option value="2" class="red">red</option>
<option value="3" class="yellow">yellow</option>
</select>
Run Code Online (Sandbox Code Playgroud)
UPDATE(CSS类名称不应与文本名称相同。css类来自数据库中的表。)
<select id="colors" name="colors">
<option value="1" class="blue">colors-blue</option>
<option value="2" class="red">something-red</option>
<option value="3" class="yellow">banana is yellow</option>
</select>
Run Code Online (Sandbox Code Playgroud)
如果这只是添加到所有这些选项中的一个CSS类,那么我可以使用jQuery轻松做到这一点。但是我需要添加多个。
PS:我将类名存储在数据库的表中。
从文档中,我看不到任何曙光。我也看过API。
更新2(提供一些更多代码细节)
// In my create view I have this:
{{ Form::select( 'colored_stuffs', $colorsList, null, ['id'=>'colored_stuffs'] ) }}
// The $colorsList generate an array in the ColorsController@create
public function getCreate()
{
$colorsList = $this->colors->listAll();
}
// listAll() is defined here is this repository
public function listAll()
{
$colors = $this->model->lists('name', 'id', 'color_class');
return $colors;
}
// the HTML optput of the create view it's this
<select id="colored_stuffs" name="colored_stuffs">
<option value="1">Red is used to alert something</option>
<option value="2">A banana is yellow</option>
<option value="3">Sorry no color here</option>
</select>
// But I want this
<select id="colored_stuffs" name="colored_stuffs">
<option value="1" class="red">Red is used to alert something</option>
<option value="2" class="light-yellow">A banana is yellow</option>
<option value="3" class="black">Sorry no color here</option>
</select>
Run Code Online (Sandbox Code Playgroud)
默认Form::select()助手将不支持您所请求的内容,但您可以使用Macro添加其他表单助手:
Form::macro('fancySelect', function($name, $list = array(), $selected = null, $options = array())
{
$selected = $this->getValueAttribute($name, $selected);
$options['id'] = $this->getIdAttribute($name, $options);
if ( ! isset($options['name'])) $options['name'] = $name;
$html = array();
foreach ($list as $list_el)
{
$selectedAttribute = $this->getSelectedValue($list_el['value'], $selected);
$option_attr = array('value' => e($list_el['value']), 'selected' => $selectedAttribute, 'class' => $list_el['class']);
$html[] = '<option'.$this->html->attributes($option_attr).'>'.e($list_el['display']).'</option>';
}
$options = $this->html->attributes($options);
$list = implode('', $html);
return "<select{$options}>{$list}</select>";
});
Run Code Online (Sandbox Code Playgroud)
class您可以根据需要将此新方法与其他方法一起使用:
$options = [
[
'value' => 'value-1',
'display' => 'display-1',
'class' => 'class-1'
],
[
'value' => 'value-2',
'display' => 'display-2',
'class' => 'class-2'
],
[
'value' => 'value-3',
'display' => 'display-3',
'class' => 'class-3'
],
];
echo Form::fancySelect('fancy-select', $options);
Run Code Online (Sandbox Code Playgroud)