How to pass a search string as an argument to ajax and optionally an identifier? For example, I want to select a car brand in the first field of select2, a model in the second field, respectively, I want to select from the directory of models only those that belong to this brand, it turns out I need to transfer also the brand ID. So far, it turns out to transmit only what is typed in the search bar.
Description of the parameters of the plugin Select2
I use a PHP wrapper in my program from Kartika
Here is a sample code:

$brandUrl = Url::to('record/brandsearch'); echo $form->field($model, 'brandId')->widget(Select2::classname(), [ 'language' => 'ru', 'options' => [ 'placeholder' => 'Укажите бренд ...', 'theme' => \kartik\select2\Select2::THEME_BOOTSTRAP, ], 'pluginOptions' => [ 'allowClear' => true, 'minimumInputLength' => 0, 'ajax' => [ 'url' => $brandUrl, 'dataType' => 'json', 'data' => new JsExpression('function(params) { return {q:params.term}; }') ], 'escapeMarkup' => new JsExpression('function (markup) { return markup; }'), 'templateResult' => new JsExpression('function(brand) { return brand.text; }'), 'templateSelection' => new JsExpression('function (brand) { return brand.text; }'), ], ]); 

This field works correctly. I would like to add a second field, in which, additionally, in the parameters transmitted by ajax, there will also be an ID of the first one. Alas, there is no such example anywhere.

  • 1) show your current code. 2) select2 - is it a plugin or something else? - Alex
  • @ Apron63, edit your question by adding your code and link to the plugin. - Pavel Parshin
  • @ Apron63, please insert your code into the text of the question and bring it to a readable form. - Alex

2 answers 2

In my project, I decided this as follows:

  1. Slave select2 not active until the main value is not selected from the drop-down list;

  2. On the select2:opening event, select2:opening hang the function that will receive the value from the main select2 and form the final url that returns the required list

     return { q: params.term, brand: brandId } 

    Where brandId is the id of the first select