Search code examples
phpjqueryajaxlaraveldropdown

Populate dropdown based on another dropdown selected value in laravel - edit form


I found how to accomplish this on another site and I got it working. My issue is though that I need to use it in my edit form (preferably in the same form as my create form, since my create and edit views use the same form). When I go to my edit page, the "Section" dropdown value is selected as it should be. But the "Subsection" is not, because ofcourse I did not click it. Probably it's a fix too easy for me to see, but I am not quite good with javascript. I basically need the second dropdown (the subsection one) to show the correct options based on which "section" (first dropdown) is selected, on my edit view.

Section Model:

public function subsections()
{
    return $this->hasMany('App\Subsection');
}

Subsection Model:

public function section()
{
    return $this->belongsTo('App\Section');
}

View:

{!! Form::select('section_id', [null=>'-- Select Section --'] + $sections, null, array('id' => 'section')) !!}

<select id="subsection" name="subsection_id" class="select">
    <option>-- First Select Section --</option>
</select>

From my controller: $sections = Section::lists('section', 'id');

Script:

<script>
$(document).ready(function($){
    $('#section').change(function(){
        $.get("{{ url('api/dropdown')}}", 
        { option: $(this).val() }, 
        function(data) {
            $('#subsection').empty(); 
            $.each(data, function(key, element) {
                $('#subsection').append("<option value='" + key +"'>" + element + "</option>");
            });
        });
    });
});
</script>

Route:

Route::get('api/dropdown', function(){
    $id = Input::get('option');
    $subsections = Section::find($id)->subsections;
    return $subsections->lists('subsection', 'id');
});

Solution

  • In my controller I added:

        $subsections = Subsection::where('section_id', '=', $transaction->section_id)->orderBy('subsection', 'asc')->lists('subsection', 'id');
    

    And in my view I did this:

        @if(isset($transaction))
        {!! Form::select('subsection_id', [null=>'-- Select Subsection --'] + $subsections, null, array('class' => 'select', 'id' => 'subsection')) !!}
        @else
            <select id="subsection" name="subsection_id" class="select">
                <option>-- First Select Section --</option>
            </select>
        @endif
    

    Problem solved :)