Sunilkumar P
Sunilkumar P

Reputation: 11

Yii2 select2 ajax dropdown loading

I am using two select2 ajax loading dropdown list using Yii2 kartik widget. I need to change selection of second dropdown while changing selection of first dropdown.

First Dropdown

 <?php

     $qtnno = '';
     $qtn = ServiceQuotation::find()->where(['UDNO' => $model->QTN_UDNO])->one();
     if($qtn != null)  $qtnno = $qtn->UDNO;

    echo $form->field($model, 'QTN_UDNO')->widget(Select2::classname(), [
    'initValueText' => $qtnno, // set the initial display text
    'options' => ['placeholder' => 'Search for a Quotation ...',
             'onchange'=>'
		                $.getJSON( "'.Url::toRoute('getqtndetails').'", { id: $("#servicejobcard-qtn_udno").val() } )
		                    .done(function( data ) {
		                        $( "#'.Html::getInputId($model, 'QTNNO').'" ).val( data.qtnno );
		                        $( "#'.Html::getInputId($model, 'QTNDATE').'" ).val( data.qtndate );
		                        $( "#'.Html::getInputId($model, 'PCODE').'" ).select2({ data: [{id: data.pcode, text: data.pname}]});;
                                $( "#'.Html::getInputId($model, 'PCODE').'" ).select2("val",data.pcode);
                                $( "#'.Html::getInputId($model, 'PROJECTNAME').'" ).val( data.projectname );
		                    }
		                );'
                 ],
      'pluginOptions' => [
        'allowClear' => true,
        'minimumInputLength' => 3,
        'ajax' => [
            'url' => $urlQtn,
            'dataType' => 'json',
            'data' => new JsExpression('function(params) { return {q:params.term}; }')
        ],
        'escapeMarkup' => new JsExpression('function (markup) { return markup; }'),
        'templateResult' => new JsExpression('function(data) { return data.text; }'),
        'templateSelection' => new JsExpression('function (data) { return data.text; }'),
    ],
]);
         ?>

Second Drop Down

  <?php

     $cusName = empty($model->PCODE) ? '' : Customer::findOne($model->PCODE)->PNAME;

    echo $form->field($model, 'PCODE')->widget(Select2::classname(), [
    'initValueText' => $cusName, // set the initial display text
    'options' => ['placeholder' => 'Search for a Customer ...',
                 ],
      'pluginOptions' => [
        'allowClear' => true,
        'minimumInputLength' => 3,
        'ajax' => [
            'url' => $url,
            'dataType' => 'json',
            'data' => new JsExpression('function(params) { return {q:params.term}; }')
        ],
        'escapeMarkup' => new JsExpression('function (markup) { return markup; }'),
        'templateResult' => new JsExpression('function(party) { return party.text; }'),
        'templateSelection' => new JsExpression('function (party) { return party.text; }'),
    ],
]);
         ?>

Using the above code i'm able to change the selection in second dropdown. But after the change, i'm not able to make selection in second dropdown.

Please help...

Upvotes: 1

Views: 4368

Answers (3)

r&#252;ff0
r&#252;ff0

Reputation: 943

you can add this kind of query to make the job.

$cusname=QtnUdno::find()->select('PCODE')->where(['UDNO'=>$model->QTN_UDNO])->one();

Upvotes: 0

sm1979
sm1979

Reputation: 290

If you are not restricted to using only Select2 widget, I would suggest you use the Kartik V's DepDrop Widget specifically created for dependent drop-downs.

Since you have not given a lot of context to what your code is actually doing, I am giving a simple 2 level dependency example (slightly modified version of example given in Kartik V's depdrop widget page).

/*
 * 2-level dependency example
 */
// THE VIEW
use kartik\widgets\DepDrop;

// Parent 
echo $form->field($model, 'cat')->dropDownList($catList, ['id'=>'cat-id']);

// Dependent Dropdown (Child)
echo $form->field($model, 'subcat')->widget(DepDrop::classname(), [
    'options'=>['id'=>'subcat-id'],
    'pluginOptions'=>[
        'depends'=>['cat-id'],
        'placeholder'=>'Select...',
        'url'=>Url::to(['/site/subcat'])
    ]
]);   

// THE SITE CONTROLLER (/site/subcat)
public function actionSubcat() {
    $out = [];
    if (isset($_POST['depdrop_parents'])) {
        $parents = $_POST['depdrop_parents'];
        if ($parents != null) {
            $cat_id = $parents[0];
            $out = self::getSubCatList($cat_id); 
            // the getSubCatList function will query the database based on the
            // cat_id and return an array like below:
            // [
            //    ['id'=>'<sub-cat-id-1>', 'name'=>'<sub-cat-name1>'],
            //    ['id'=>'<sub-cat_id_2>', 'name'=>'<sub-cat-name2>']
            // ]
            echo Json::encode(['output'=>$out, 'selected'=>'']);
            return;
        }
    }
    echo Json::encode(['output'=>'', 'selected'=>'']);
}

The above code can be customized to your requirements.

Here is the link for more details: http://demos.krajee.com/widget-details/depdrop

Upvotes: 1

SiZE
SiZE

Reputation: 2267

Try to use onchange event this way:

[
    'options' => [],
    // other settings
    'pluginEvents' => [
        'change' => "function() { alert('change'); }",
    ]
]

You can find additional information on that page http://demos.krajee.com/widget-details/select2

Upvotes: 1

Related Questions