velvt
velvt

Reputation: 153

laravel 5.2 dynamic dropdown list

I have an event and i want to add artists to it from artists table. I want to do so by using a dropdown list where it need to get populated by artists name and their is a small '+' next to it to add other artists. Upon doing that a 3rd transitive table where event id and artist id should be inserted as foreign keys. When I create the event

In my view:

<div class="form-group">
<label for="task-artist" class="col-sm-3 control-label">Artist:</label>
<div class="col-sm-6">
   <select name="artist" id="artist" class="form-control input-sm">
    <option value=""></option>
      @foreach($artists as $artist)
          {{$artist->stage_name}} 
       @endforeach
    </select>
</div>
</div>

my controller:

public function index(Request $request)
    {
        return view('tasks.index', [
            'tasks' => $this->tasks->forUser($request->user()),
             'artists' => DB::table('artists')->pluck('stage_name', 'id'),
        ]);
    }

    public function show($id)
    {
        //Get results by targeting id
        $task = Task::find($id);
        //$artist = Artist::lists('stage_name', 'id');
        //$artist = Artist::where('active', true)->orderBy('stage_name')->pluck('stage_name', 'id');
        //
        return view('tasks.show')->with('task',$task);
    }

How shall i proceed ? Please help.

Upvotes: 0

Views: 1697

Answers (1)

Murlidhar Fichadia
Murlidhar Fichadia

Reputation: 2609

Javascript is your friend here.

Let me write some steps that you can follow to achieve what you are looking for :

1) Have the Div tag and

2) use $.get() function in javascript to get the dynamic values from a controller.

3) $.each() to loop through the data and show it in select input field

4) on either selecting the value or clicking + button that you mentioned do another Javascript call to add the artist to the event.

Example :

HTML
<div class="uk-margin-bottom">
    <div id="your select dropdown"></div>
</div>

JAVASCRIPT
$("#artist").change(function() {
    getArtists();
});

    function getArtist() {
    var artist= $('#your div id');
    artist.empty();
    var code = '';
    $.get("/url/" + variable_id, function(data) {
        artist.empty();
        console.log(data);// once you create route and controller you should see your artists lists here

        code += '<label for="event_id" class="uk-form-label">Select Artist</label><select class="uk-width-1-1" name="artist_name" id="artist_name" value="select">';
        code += '<option value="">Select Artists</option>';
        $.each(data.artist, function(index, value) {

            code += '<option value="' + value.artist_name+ '">' + value.artist_name + '</option>';
        });
        code += '</select>
        artist.append(code);

    });
}

have a form and add javascript to post artist to the controller and store data into events table. Try and see if you can achieve and follow my steps.

Upvotes: 2

Related Questions