簡體   English   中英

為 Laravel 表單中的選擇列表添加默認值::選擇

[英]Add default value to select list in Laravel form::select

簡單的問題,我希望。

我需要在我的選擇列表“請選擇”中添加一個默認值,並將其設置為禁用。

<select name="myselect" id="myselect">
  <option value="" disabled>Please Select</option>
  <option value="1">Item 1</option>
  <option value="2">Item 2</option>
</select>

我目前的 Laravel 表單::選擇是

{{
Form::select(
    'myselect',
    $categories,
    $myselectedcategories,
    array(
        'class' => 'form-control',
        'id' => 'myselect'
    )
}}

如何修改它以包含默認選項值?

在 Laravel 5.1 中,如果列表是一個集合( Eloquent::lists()結果),您可以預先添加默認項

$categories = Category::lists('name', 'id');
$categories->prepend('None');

您可以像這樣使用array_merge

{{
Form::select(
    'myselect',
    array_merge(['' => 'Please Select'], $categories),
    $myselectedcategories,
    array(
        'class' => 'form-control',
        'id' => 'myselect'
    ))
}}

或者,您可以在選擇之前的某處設置占位符:

$categories[''] = 'Please Select';

更新

要添加禁用屬性,您可以嘗試以下操作:(未經測試)

{{
Form::select(
    'myselect',
    array_merge(['' => ['label' => 'Please Select', 'disabled' => true], $categories),
    $myselectedcategories,
    array(
        'class' => 'form-control',
        'id' => 'myselect'
    ))
}}

'placeholder' => 'Please Select'Form::select

{!!
  Form::select(
    'myselect', 
    $categories, 
    null, 
    ['class' => 'form-control', 'placeholder' => 'Please Select'])
!!}

或者只是放置占位符,例如:

[
    'class' => 'form-control',
    'id' => 'myselect',
    'placeholder' => 'None'
]

這樣就行了。

$categories = Category::lists('name', 'id');
$categories->prepend('None', 0);

For, prepending Please Select with empty value

$categories = Category::lists('name', 'id');
$categories->prepend('Please Select', '');

這段代碼將填充這樣的東西,

$categories[''] = 'Please Select';
$categories[0] = 'item 1',
$categories[1] = 'item 2';

現在你可以使用這樣的東西:

{!! Form::select('myselect', $categories, '',['id'=>'myselect']) !!}

這也有助於表單驗證,例如required

我把我的解決方案放在這篇文章中。 我希望可以幫助某人

我使用 php 函數向模型數組添加一個選項

array_unshift($model, ['value' => '', 'name' => 'Select value']);

我使用了占位符,它對我有用

{!! Form::select('supplier', $suppliers, null, ['class' => 'form-control', 'placeholder' => '請選擇']) !!}

現在,默認印度被選中

{{ Form::select('terms_agreement_type', [null => 'Select Control'] + ['India' => 'India', 'Nepal' => 'Nepal'], 'India') }}

你可以使用采摘

控制器

$role = Model::all();

{{ Form::select('nameselect', $role->pluck('name', 'id')->prepend('default value...', ""))}}

Laravel 5.3

{{ Form::select('role', ['' => 'Select Role'] +$roles, null, ['class' => 'form-control']) }}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM