vreedom18
vreedom18

Reputation: 341

select2 field that depends on another field

I want to implement the code show in this tutorial:

https://backpackforlaravel.com/docs/4.1/crud-how-to#add-a-select2-field-that-depends-on-another-field

However, this line returns null value:

$form = collect($request->input('form'))->pluck('value', 'name');

I don't know if i should use input('form') here as it is taken from the documentation for version 3.4 Does someone know if it works in version 4.

CrudController:

// CRUD::field('sub_district_id')
//     ->type('select2')
//     ->label('Kecamatan')
//     ->entity('sub_district')
//     ->attribute('sub_district_name')
//     ->model('App\Models\SubDistrict')
//     ->wrapper(['class' => 'form-group col-md-6']);
CRUD::field('sub_district_id')
    ->type('relationship')
    ->label('Kecamatan')
    ->attribute('sub_district_name')
    ->include_all_form_fields(true)
    ->wrapper(['class' => 'form-group col-md-6']);
CRUD::field('village_id')
    ->type('select2_from_ajax')
    ->label('Desa/Kelurahan')
    ->entity('village')
    ->attribute('village_name')
    ->model("App\Models\Village")
    ->wrapper(['class' => 'form-group col-md-6'])
    ->data_source(url('api/village'))
    ->placeholder('Pilih Desa/Kelurahan')
    ->minimum_input_length(0)
    ->dependencies(['sub_district_id'])
    ->method('GET'); // optional - HTTP method to use for the AJAX call (GET, POST)

ApiController:

$search_term = $request->input('q');
$form = collect($request->input('form'))->pluck('value', 'name');
// dump($form);

$options = Village::query();

if (!$form['sub_district_id']) {
    return [];
}

// if a category has been selected, only show articles in that category
if ($form['sub_district_id']) {
    $options = $options->where('sub_district_id', $form['sub_district_id']);
}

if ($search_term) {
    $results = $options->where('village_name', 'LIKE', '%' . $search_term . '%')->paginate(10);
} else {
    $results = $options->paginate(10);
}

return $options->paginate(10);

Upvotes: 2

Views: 1210

Answers (2)

vreedom18
vreedom18

Reputation: 341

Just add this line to village's field

->include_all_form_fields(true)

and it will return all the value from the form

CrudController:

// ...
CRUD::field('village_id')
    ->type('select2_from_ajax')
    ->label('Desa/Kelurahan')
    ->entity('village')
    ->attribute('village_name')
    ->model("\App\Models\Village")
    ->wrapper(['class' => 'form-group col-md-6'])
    ->data_source(url('api/village'))
    ->placeholder('Pilih Desa/Kelurahan')
    ->minimum_input_length(0)
    ->dependencies(['sub_district_id'])
    ->include_all_form_fields(true)
    ->method('GET'); // optional - HTTP method to use for the AJAX call (GET, POST)
// ...

Upvotes: 3

Irshad Khan
Irshad Khan

Reputation: 432

Try this

$form = collect($request->all())->get('value', 'name');

Upvotes: 0

Related Questions