Yii2 Select2 Howto Add New Item When Not Found


How can an item be added when it does not exist in the Kartik Select2 widget.

For example when I have an order and want to choose a customer, while typing and when the customer does not exist,

A question should popup asking if a new customer should be created.

When yes has been choosen, a new insert customer form should popup, after creating the new customer and closing the popup, the new customer should be selected in the Select2 Widget.

Here’s the code to select a customer.

In views\orders\_form:

<?php use kartik\widgets\Select2;


    // usage with ActiveForm and model

    echo $form->field($model, 'customer_id')->widget(Select2::classname(), [

      'language' => 'nl',

      'data' => ArrayHelper::map(\app\models\Customers::find()->orderBy('customername')->all(), 'id', 'customername'),

      'options' => ['placeholder' => 'Select a name ...'],

      'pluginOptions' => [

        'allowClear' => true



Select2 does not have this feature, you would have to code it.

This is an alternative, take a look.

The widget looks promising,

but now, how to achieve the things I’ve asked above, in Yii2?

'data' => array_merge(["" => ""], $data),

I’ve already tried

'data' => array_merge(ArrayHelper::map(\app\models\Customers::find()->orderBy('customername')->all(), 'id', 'customer'),[0 => "Add New"]),

But then I get an error message and it seems that it is not taking customer_id as a reference but the array id…

The SQL being executed was: UPDATE orders SET customer_id=0 WHERE id=2

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (yii2basic.orders, CONSTRAINT relorderscustomers FOREIGN KEY (customer_id) REFERENCES customers (id))

How to set a default selected value for Select2 ? :-\

I use


									echo &#036;form-&gt;field(&#036;modelReferences, &quot;[{&#036;iiii}]reference_country&quot;)-&gt;widget(Select2::classname(), [

									'data' =&gt; &#036;countrylist,

									'options' =&gt; ['placeholder' =&gt; 'Select country ...'],

									'pluginOptions' =&gt; [

									'allowClear' =&gt; true