php Laravel - 表单输入 - 多选一对多关系
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24627902/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel - Form Input - Multiple select for a one to many relationship
提问by datavoredan
One of the requirements in an application that I am building is for a form input which takes in a varying number of items for a single field. For instance, sports that I play are ('Soccer','Tennis','Croquet').
我正在构建的应用程序中的一个要求是表单输入,它为单个字段接收不同数量的项目。例如,我参加的运动是(“足球”、“网球”、“门球”)。
There are a finite number of sports one can play (arguably), so these items should be selected from a "drop down" type list in the form input.
可以玩的运动数量有限(可以说),因此应从表单输入中的“下拉”类型列表中选择这些项目。
Downstream of this form will be two tables which have a one-to-many relationship. So from the above, the "user" table would have a single row, while the "user_sports" table would have three rows. These would then be linked by the id field in the user table.
这种形式的下游将是两个具有一对多关系的表。所以从上面可以看出,“user”表只有一行,而“user_sports”表只有三行。然后这些将通过用户表中的 id 字段链接。
I have not been able to find the sort of functionality where this can be achieved in the documentation (perhaps I am not searching for the correct thing). Below was the closest that I found, but is only for selecting a single item from a drop down list.
我无法在文档中找到可以实现的功能(也许我没有在寻找正确的东西)。下面是我找到的最接近的,但仅用于从下拉列表中选择一个项目。
http://laravel.com/docs/html#drop-down-lists
http://laravel.com/docs/html#drop-down-lists
Is there a workaround out there that will enable me to get this form element up and running using the Laravel framework?
是否有解决方法可以让我使用 Laravel 框架启动并运行这个表单元素?
Alternatively, are there other ways that this sort of functionality can be achieved, without damaging the user experience?
或者,是否有其他方法可以在不损害用户体验的情况下实现此类功能?
回答by SamMonk
I agree with user3158900, and I only differ slightly in the way I use it:
我同意 user3158900,我只是在使用它的方式上略有不同:
{{Form::label('sports', 'Sports')}}
{{Form::select('sports',$aSports,null,array('multiple'=>'multiple','name'=>'sports[]'))}}
However, in my experience the 3rd parameter of the select is a string only, so for repopulating data for a multi-select I have had to do something like this:
但是,根据我的经验,select 的第三个参数只是一个字符串,因此要为多选重新填充数据,我必须执行以下操作:
<select multiple="multiple" name="sports[]" id="sports">
@foreach($aSports as $aKey => $aSport)
@foreach($aItem->sports as $aItemKey => $aItemSport)
<option value="{{$aKey}}" @if($aKey == $aItemKey)selected="selected"@endif>{{$aSport}}</option>
@endforeach
@endforeach
</select>
回答by Sushant Aryal
@SamMonk your technique is great. But you can use laravel form helper to do so. I have a customer and dogs relationship.
@SamMonk 你的技术很棒。但是你可以使用 laravel 表单助手来做到这一点。我有客户和狗的关系。
On your controller
在您的控制器上
$dogs = Dog::lists('name', 'id');
On customer create view you can use.
在客户创建视图上,您可以使用。
{{ Form::label('dogs', 'Dogs') }}
{{ Form::select('dogs[]', $dogs, null, ['id' => 'dogs', 'multiple' => 'multiple']) }}
Third parameter accepts a list of array a well. If you define a relationship on your model you can do this:
第三个参数接受一个数组 a 的列表。如果您在模型上定义关系,则可以执行以下操作:
{{ Form::label('dogs', 'Dogs') }}
{{ Form::select('dogs[]', $dogs, $customer->dogs->lists('id'), ['id' => 'dogs', 'multiple' => 'multiple']) }}
Update For Laravel 5.1
Laravel 5.1 更新
The lists method now returns a Collection. Upgrading To 5.1.0
列表方法现在返回一个集合。 升级到 5.1.0
{!! Form::label('dogs', 'Dogs') !!}
{!! Form::select('dogs[]', $dogs, $customer->dogs->lists('id')->all(), ['id' => 'dogs', 'multiple' => 'multiple']) !!}
回答by Ben K.
Laravel 4.2
Laravel 4.2
@SamMonkgave the best alternative, I followed his example and build the final piece of code
@ SamMonk给出了最好的选择,我按照他的例子构建了最后一段代码
<select class="chosen-select" multiple="multiple" name="places[]" id="places">
@foreach($places as $place)
<option value="{{$place->id}}" @foreach($job->places as $p) @if($place->id == $p->id)selected="selected"@endif @endforeach>{{$place->name}}</option>
@endforeach
</select>
In my project I'm going to have many table relationships like this so I wrote an extension to keep it clean. To load it, put it in some configuration file like "app/start/global.php". I've created a file "macros.php" under "app/" directory and included it in the EOF of global.php
在我的项目中,我将有很多这样的表关系,所以我写了一个扩展来保持它的整洁。要加载它,请将其放在一些配置文件中,例如“app/start/global.php”。我在“app/”目录下创建了一个文件“macros.php”,并将其包含在 global.php 的 EOF 中
// app/start/global.php
require app_path().'/macros.php';
// macros.php
Form::macro("chosen", function($name, $defaults = array(), $selected = array(), $options = array()){
// For empty Input::old($name) session, $selected is an empty string
if(!$selected) $selected = array();
$opts = array(
'class' => 'chosen-select',
'id' => $name,
'name' => $name . '[]',
'multiple' => true
);
$options = array_merge($opts, $options);
$attributes = HTML::attributes($options);
// need an empty array to send if all values are unselected
$ret = '<input type="hidden" name="' . HTML::entities($name) . '[]">';
$ret .= '<select ' . $attributes . '>';
foreach($defaults as $def) {
$ret .= '<option value="' . $def->id . '"';
foreach($selected as $p) {
// session array or passed stdClass obj
$current = @$p->id ? $p->id: $p;
if($def->id == $current) {
$ret .= ' selected="selected"';
}
}
$ret .= '>' . HTML::entities($def->name) . '</option>';
}
$ret .= '</select>';
return $ret;
});
Usage
用法
List without pre-selected items (create view)
没有预选项目的列表(创建视图)
{{ Form::chosen('places', $places, Input::old('places')) }}
Preselections (edit view)
预选(编辑视图)
{{ Form::chosen('places', $places, $job->places) }}
Complete usage
完整使用
{{ Form::chosen('places', $places, $job->places, ['multiple': false, 'title': 'I\'m a selectbox', 'class': 'bootstrap_is_mainstream']) }}
回答by user1669496
A multiple select is really just a select with a multiple
attribute. With that in mind, it should be as easy as...
多重选择实际上只是具有multiple
属性的选择。考虑到这一点,它应该像……一样简单。
Form::select('sports[]', $sports, null, array('multiple'))
The first parameter is just the name, but post-fixing it with the []
will return it as an array when you use Input::get('sports')
.
第一个参数只是名称,但是[]
当您使用Input::get('sports')
.
The second parameter is an array of selectable options.
第二个参数是一组可选选项。
The third parameter is an array of options you want pre-selected.
第三个参数是您要预先选择的选项数组。
The fourth parameter is actually setting this up as a multiple select dropdown by adding the multiple
property to the actual select element..
第四个参数实际上是通过将multiple
属性添加到实际选择元素来将其设置为多选下拉列表。
回答by Raul Fernandez Marques
My solution, it′s make with jquery-chosen and bootstrap, the id is for jquery chosen, tested and working, I had problems concatenating @foreach but now work with a double @foreach and double @if:
我的解决方案,它是使用 jquery-chosen 和 bootstrap 制作的,id 用于选择、测试和工作的 jquery,我在连接 @foreach 时遇到了问题,但现在使用双 @foreach 和双 @if:
<div class="form-group">
<label for="tagLabel">Tags: </label>
<select multiple class="chosen-tag" id="tagLabel" name="tag_id[]" required>
@foreach($tags as $id => $name)
@if (is_array(Request::old('tag_id')))
<option value="{{ $id }}"
@foreach (Request::old('tag_id') as $idold)
@if($idold==$id)
selected
@endif
@endforeach
style="padding:5px;">{{ $name }}</option>
@else
<option value="{{ $id }}" style="padding:5px;">{{ $name }}</option>
@endif
@endforeach
</select>
</div>
this is the code por jquery chosen (the blade.php code doesn′t need this code to work)
这是选择的 jquery 代码(blade.php 代码不需要此代码即可工作)
$(".chosen-tag").chosen({
placeholder_text_multiple: "Selecciona alguna etiqueta",
no_results_text: "No hay resultados para la busqueda",
search_contains: true,
width: '500px'
});
回答by Tom van Tilburg
This might be a better approach than top answer if you need to compare 2 output arrays to each other but use the first array to populate the options.
如果您需要将 2 个输出数组相互比较但使用第一个数组填充选项,这可能是比最佳答案更好的方法。
This is also helpful when you have a non-numeric or offset index (key) in your array.
当数组中有非数字或偏移索引(键)时,这也很有用。
<select name="roles[]" multiple>
@foreach($roles as $key => $value)
<option value="{{$key}}" @if(in_array($value, $compare_roles))selected="selected"@endif>
{{$value}}
</option>
@endforeach
</select>
回答by Kaushik shrimali
Just single if conditions
只是单身 if 条件
<select name="category_type[]" id="category_type" class="select2 m-b-10 select2-multiple" style="width: 100%" multiple="multiple" data-placeholder="Choose" tooltip="Select Category Type">
@foreach ($categoryTypes as $categoryType)
<option value="{{ $categoryType->id }}"
**@if(in_array($categoryType->id,
request()->get('category_type')??[]))selected="selected"
@endif**>
{{ ucfirst($categoryType->title) }}</option>
@endforeach
</select>