'Laravel backpack fields - select_from_array functionality

I am using laravel backpack. Have created a new Request form. Have created several fields to choose from using 'select_from_array':

$this->crud->field('range')->type('select_from_array)->label(__('number range'))
   ->options(Group::NUMBER_RANGE);

$this->crud->field('range1')->type('select_from_array)->label(__('letter range'))
   ->options(Group::LETTER_RANGE);

$this->crud->field('range2')->type('select_from_array)->label(__('symbol range'))
   ->options(Group::SYMBOL_RANGE);

For example, each field has got 3 dropdown values to choose from (to make it more clear, let's say number range has 1 / 2 / 3, then letter range has A / B / C, and symbol range has Sun / Moon / Wind).

I want to apply this functionality - if from number range I select 1, I want that letter range to show me just A and B (and C should disappear from the value choices), and symbol range show me just Wind. Or if I choose field letter range and I choose option value B I want that symbol range field would show me just Sun.

In general I want that fields would react with each other depending on the choices I made on the previous field the next field would show different options I could choose from.

How can I do this?

Thank you in advance :)



Solution 1:[1]

Backpack doesn’t currently make it easy to do that, but it doesn’t make it difficult either.

Option A - javascript

You can push a bit of javascript onpage, using the script widget, that will do whatever you want, including this functionality.


Widget::add()->type('script')->content('assets/js/admin/request_form.js'); 

There’s an active pull request trying to make it easier to interact with fields on the front-end too (PR #4312) but until that is merged, you can use vanilla JS or jQuery to do whatever you want.

Option B - select2_from_ajax

Alternatively, you could use the select2_from_ajax field type, which does allow you to do that using the “dependent” attribute. Since you’re in control of the AJAX endpoint, you can return different results depending on other form choices.

But:

  • I think making these 3 selects make AJAX requests is overkill, when a bit of JS can do the same for regular selects;
  • This is a PRO field, so it’s only available if you purchased the PRO addon;

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 tabacitu