Search code examples
laravellaravel-form

How to hide dropdown and how to multiselect from dropdown?


I have dropdown list with weekdays i want to select multiple days, like 'Monday' and 'Tuesday' I have several question on it

  • 1) How to hide multiselect dropdown? Because it is showing all list
  • 2) How to multiselect it? should I hold CTRL to multiselect?
  • 3) How it will be saved in database if i gonna put it as a string to same column i mean will it be like 'MondayTuesday', or 'Monday Tuesday', or 'Monday, Tuesday'

Here is my view

        <div class="form-group">
            {{Form::label('weekdays', 'Week Days')}}

            {{Form::select('weekdays',$weekdays,null,array('name'=>'weekdays[]', 'multiple' => 'multiple'))}}
            {{Form::select('timetable',$time,null,array('name'=>'time[]'))}}
        </div>

Controller

        $categories_name = Category::pluck('category_name','id');    
        $data = array(
            'weekdays' => [
                'Monday',
                'Tuesday',
                'Wednesday'
            ],
            'time' => [
                '2p.m',
                '3p.m'
            ],
            'categories_name' => $categories_name
        );
        return view('pages.clubs.create_club')->with($data);
    }

see the screenshot to understand what i mean


Solution

  • For 1 and 2, you can use the plugin called chosen, it is well documented and very easy to implement.

    For number 3 question, you can save it in json format on the database like so:

    $days = "Monday,Tuesday,Wednesday"; 
    //or $days = $request->weekdays;
    $parsed = explode(",", $days);
    $selected_weekdays = json_encode($parsed);
    
    Model::create(['weekdays' => $selected_weekdays]);
    

    You can then display the value on the blade by decoding the json string like so:

    $selected_weekdays = json_decode($model->weekdays);
    
    {{Form::select('weekdays[]',$weekdays,$selected_weekdays,array('multiple' => 'multiple'))}}
    

    UPDATE 1:

    It is advisable to install it using bower:

    bower install chosen
    

    To use chosen:

    <link rel='stylesheet' type="text/css" href="{{ asset('bower_components/chosen/chosen.min.css') }}" rel="stylesheet">
    
    {{Form::select('weekdays[]',$weekdays,$selected_weekdays,array('multiple' => 'multiple', 'class' => 'chosen-select'))}}
    
    <script src="{{ asset('bower_components/chosen/chosen.jquery.min.js') }}"></script>
    
    <script>
        $(".chosen-select").chosen();
    </script>