简体   繁体   中英

Set selected options into PHP multi-select input while loading

<?php
$arrayData = myModel::all();
foreach($arrayData as $arrayList){
   $pureData = array_add($pureData, $arrayList->elementValue, $arrayList->elementText);
}
echo Form::select('multiSelectName', $pureData, null, array());
?>
  1. I'm trying to get data from database to fill values into multiselect field.
  2. I'm trying to make some values selected, on this multiselect field.

How can I achieve that?

Thanks in advance.

One solution would be to get all available options and the already selected ones then find out if they match and create a select element with a selected parameter set to it.

I don't think this can be done using the Form helper (I know it can be done with just a single value, but have not tried it with multiple values)

Example

Get all the available options (try to get something to uniquely identify them like the id)

$all_options=Model::lists('id','name');

I'm using the lists method that will return me an array with all the available id's as the value and the name as the keys of the array.

Then get all the selected values

$already_selected_options =Model::with('related_model')->lists('id','name');

(If you are using eloquent something like this to get the related ids will work)

Then in your view

<select multiple>
@foreach($all_options as $name => $id)
    @if(in_array($id,$already_selected_options))
       <option value="{{$id}}" selected>{{$name}}</option>
      @else
       <option value="{{$id}}">{{$name}}</option>
    @endif
@endforeach
<select>

I'm of the opinion that you should do it in javascript instead if at all possible. It's barely noticeable in terms of latency, and doesn't waste cycles server side. Here's an example from one of my recent projects. as a bonus, if you declare an onchange event inline on the select, it will call it for you immediately following the execution of the function.

$('select.select-onload').each(function(index){
    if(typeof $(this).attr('data-selected') !== 'undefined'){
        if($(this).attr('data-selected') == ''){
            return false;
        }
        $(this).val( $(this).attr('data-selected') );
        //we may have a callback. lets manually invoke it.
        if(typeof $(this).attr('onchange') !== 'undefined'){
            var callback = $(this).attr('onchange').replace('();','').trim();
            window[callback].call(window);
        }
    }
});

usage:

<select class="select-onload" data-selected="{{id}}"> <!--whatever options value is 5 is the one that will be selected.--> </select>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM