首页 > 解决方案 > 在 laravel 表单中使用数据属性选择

问题描述

如何将数据属性添加到 laravel{{Form::select}}数组?

例如,我希望我的每个选项看起来像这样

<option value="1" data-days="182">6 Months</option>
<option value="2" data-days="365">1 Year</option>

如何在以下选择数组中添加数据属性?

天数表

id | days |   name
1  |  182 |   6 Months
2  |  365 |   1 Year

看法

{{Form::select('amount_of_days', $days, null, ['placeholder' => 'Amount of days'])}}

标签: phplaravellaravel-5

解决方案


将自定义值设置为 form::select 的最佳方法是使用 form::select 函数的属性参数。

控制器.php

$contact_options = Contact::all();

$contact_attributes = $contact_options->mapWithKeys(function ($item) {
    return [$item->id => ['data-otherInfo' => $item->otherInfo]];
})->toArray();

$contact_options = $contact_options->pluck('name', 'id')->toArray();

刀片.php

{!! Form::select('contact_id', $contact_options, old('contact_id', null), ['class'=>"form-control", 'id'=>"contact_id", 'required' => 'required'], $contact_attributes) !!}

推荐阅读