1

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...

3 Answers 3

1

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

3 Comments

Your answer starts with the assumtion that another library can be used despite the fact that the question specifically mentions select2. If you got a question regarding the limitations for the question I recommend that you first comment on the question, instead of answering the question. There might be several reasons why select2 is used in this case. However, your answer is properly formatted.
Thank you for the feedback. I had tried adding a comment to the question, however the lack of reputation prevented me from doing that. More importantly, although DepDrop is a different plugin, it has the option of setting the type of dropdown to be generated and supports Select2 plugin.
Yes, you're right regarding your reputation. I didn't think of the reputation part and you couldn't have done it any other way. My bad. You can disregard the comment. Anyway, great that you decided to post your first answer! It's well formed and it's great that you included such a big piece of the code in the example. Good luck!
0

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.