简体   繁体   中英

Laravel Populate Select Box Based on Another Select Box

I am not sure where even to start with this. I am using Laravel and LaravelCollective form fields. What I am looking to do is populate a second select box script (containing dates) based off of the selection in the first select box patient containing names. I'm assuming it will involve JavaScript somehow?

The Script model contains a patient_id column that links it to the Patient model, so that can be used to filter the script dates to only those that the patient owns.

Controller

$patients_select = Patient::orderBy('last_name', 'asc')
    ->get()
    ->pluck('full_name', 'id');

$scripts_select = Script::orderBy('prescribe_date', 'desc')
//      ->where('patient_id', $patient_id)
    ->pluck('prescribe_date', 'id')
    ->map(function ($date, $key) {
        return date('m/d/Y', strtotime($date));
    });

Blade

<div class="form-group">
    {{Form::label('patient', 'Patient')}}
    {{Form::select(
        'patient',
        $patients_select,
        null, 
        ['class' => 'form-control', 'placeholder' => 'Select a Patient']
    )}}
</div><!-- /form-group -->

<div class="form-group">
    {{Form::label('script', 'Script')}}
    {{Form::select(
        'script',
        $scripts_select,
        null, 
        ['class' => 'form-control', 'placeholder' => 'Select a Script']
    )}}
</div><!-- /form-group -->

You're gonna have to listen to change event on event the patient select (yes, in javascript). There are at least two possibilities here:

  1. Store all the "script" data in a javascript variable and, then populate options in the script select.

  2. Render all the possible selects in the .blade file and hide them with display: none . Depending on the patient selection you will have to show only one script select. Be careful not to send them all when submitting the form.

Well you could also reload the page after selecting, but I doubt you wanna do that. ;)

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