使用Illuminate \ html在select元素中添加一个选项

时间:2017-08-17 09:34:24

标签: php laravel illuminate-container

我有一个像这样的创建方法:

public function create()
{
    $categories = App\CategoryModel::pluck('name', 'id');
    return view('posts.create', compact('categories'));
}

我希望使用Illuminate\html添加一些选项来选择元素。

这是我的选择元素:

{!! Form::label('category', 'Category') !!}
{!! Form::select(null, $categories, null, ['class' => 'form', 'style' => 'height: 40px;', 'name' => 'category']); !!}

但是我想再添加一个这样的选项元素:

<option disabled selected> -- Select a category -- </option>

我该怎么办?

3 个答案:

答案 0 :(得分:0)

使用prepend() Laravel助手:

{!! Form::label('category', 'Category') !!}
{!! Form::select(null, 
    ["value" => "Select a category", "id" => 0] + $categories, 
    null,
    ['class' => 'form', 'style' => 'height: 40px;', 'name' => 'category']) !!}

查看官方文档here以获取更多信息。

希望这会对你有所帮助。

答案 1 :(得分:0)

您只需使用array_merge在$ categories数组中添加新值:

{{
Form::select(
    null,
    array_merge(['' => ['label' => '-- Select a category --', 'disabled' => true], $categories),
    null,
    ['class' => 'form', 'style' => 'height: 40px;', 'name' => 'category']
}}

答案 2 :(得分:0)

您可以创建自定义宏来实现此目的。按代码检查以下步骤:
1)在 app/lib/macro.php

下创建宏
<?php
//My custom macro...
Form::macro('mySelect', function($name, $list = array(), $selected = null, $disabled = null, $options = array())
{
    $selected = $this->getValueAttribute($name, $selected);
    $disabled = $this->getValueAttribute($name, $disabled);

    $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['id'], $selected);
        $disabledAttribute = $this->getSelectedValue($list_el['id'], $disabled);
        $option_attr = array('value' => e($list_el['id']), 'selected' => $selectedAttribute, 'disabled' => $disabledAttribute);
        $html[] = '<option'.$this->html->attributes($option_attr).'>'.e($list_el['value']).'</option>';
    }

    $options = $this->html->attributes($options);

    $list = implode('', $html);

    return "<select{$options}>{$list}</select>";
});

2)将宏注册到 app/Providers/MacroServiceProvider.php

<?php

namespace App\Providers;

use App\Services\Macros\Macros;
use Collective\Html\HtmlServiceProvider;

/**
 * Class MacroServiceProvider
 * @package App\Providers
 */
class MacroServiceProvider extends HtmlServiceProvider
{
    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        //
        require base_path() . '/app/lib/macro.php';
    }

.
.
.
}

3)使用我的自定义宏

{!!Form::mySelect('category',array(array('id' => '0', 'value'=>'-- Select a category --'), array('id' => '1', 'value'=>'My value1'), array('id' => '2', 'value'=>'My value2')), 0, 0) !!}

希望您了解自定义宏。用laravel 5.2测试