[solved] Problem with getting data from another model (using populate)

Greetings,

I am trying to utilize populate select2 from another select2, according to the URL:

[color="#FF0000"][html]“https://mrphp.com.au/blog/populate-select2-from-another-yii2/’]populate Select2”[/html][/color]

When I select a element (cliente_Destino) in the first select2, the second select2, you do not show any element.

However when I press the key F12, if you show the elements of the second select2, but in reality you do not show any element.

I put my codes here:

Controller the Destinos:


public function actionPopulateDestinosCode($id) {

        Yii::$app->response->format = Response::FORMAT_JSON;

        $destinoCodes = DestinosCode::find()->andWhere(['Codde' => $id])->all();

        $data = [['id' => '', 'text' => '']];

        foreach ($destinoCodes as $destinoCode) {

            $data[] = ['id' => $destinoCode->CodOp, 'text' => $destinoCode->Descripcion];

        }

        return ['data' => $data];

    }

Views:

First select2:




 <?=

            	$form->field($model, 'Codde')->widget(Select2::className(), [

                	'model' => $model,

                	'attribute' => 'Codde',

                	'data' => ArrayHelper::map(app\models\Destinos::find()->all(), 'Codde', 'Descripcion'), //ok

                	'options' => $select2Options,

                	'pluginEvents' => [

                    	'select2:select' => 'function(e) { populateDestinosCode(e.params.data.id); }',

                	],

            	]);

            	?>

]/code]

Second select2:

[code]

  <?=

            	$form->field($model, 'CodOp')->widget(Select2::className(), [

                	'model' => $model,

                	'attribute' => 'CodOp', //con client_code o turcad

                	'data' => ArrayHelper::map(app\models\DestinosCode::find()->andWhere(['Codde' => $model->Idn])->all(), 'CodOp', 'Descripcion'), //ok

                	'options' => $select2Options,

            	]);

            	?>

]/code]

In the model

[code]

[['Codde'], 'exist', 'skipOnError' => true, 'targetClass' => Destinos::className(), 'targetAttribute' => ['Codde' => 'Codde']],

[['CodOp'], 'exist', 'skipOnError' => true, 'targetClass' => DestinosCode::className(), 'targetAttribute' => ['CodOp' => 'CodOp']],

.......

public function getCodOp()

	{

    	return $this->hasOne(DestinosCode::className(), ['CodOp' => 'CodOp']);

	}

public function getCodde()

	{

    	return $this->hasOne(Destinos::className(), ['Codde' => 'Codde']);

	}



the script the views:




 <?php ob_start(); // output buffer the javascript to register later ?>

	<script>

   	function populateDestinosCode(Codde) {

        	var url = '<?= Url::to(['destinos/populate-destinos-code', 'id' => '-id-']) ?>';

        	var $select = $('#order-CodOp');

        	$select.find('option').remove().end();

        	$.ajax({

            	url: url.replace('-id-', Codde),

            	success: function(data) {

                	var select2Options = <?= Json::encode($select2Options) ?>;

                	select2Options.data = data.data;

                	$select.select2(select2Options);

                	$select.val(data.selected).trigger('change');

            	}

        	});

    	}

	</script>

	<?php $this->registerJs(str_replace(['<script>', '</script>'], '', ob_get_clean()), View::POS_END); ?>



Good morning one resolved to all, the problem, i’m change the names to the fields of the tables, although the motive was not that one, if not to errors of code for it, now quietly that way:

Now tables are:

  1. salidas (necessary fields):

Idn int autoincremental primary key

destino_id int //for the elements of the 1er select2

destino_code_id int //for the elements of the 2do select2

  1. destinos

Codde int autoincremental primary key, related with destino_id the salidas

Descripcion varchar 100

  1. destinos_code

CodOp int autoincremental (primary key)

destino_id int related with destino_code_id the salidas and with Codde de destinos

Descripcion varchar 100

Now I show the new code:

In the controllador of the tabledestinos


public function actionPopulateDestinosCode($id) {

        Yii::$app->response->format = Response::FORMAT_JSON;

        $destinosCodes = \app\models\DestinosCode::find()->andWhere(['destino_id' => $id])->all();

        $data = [['id' => '', 'text' => '']];

        foreach ($destinosCodes as $destinosCode) {

            $data[] = ['id' => $destinosCode->CodOp, 'text' => $destinosCode->Descripcion];

        }

        return ['data' => $data];

    }

In the views of salidas(form)

For the first select2:


<?=

                $form->field($model, 'destino_id')->widget(Select2::className(), [

                    'model' => $model,

                    'attribute' => 'destino_id',

                    'data' => ArrayHelper::map(app\models\Destinos::find()->all(), 'Codde', 'Descripcion'),

                    'options' => $select2Options,

                    'pluginEvents' => [

                        'select2:select' => 'function(e) { populateDestinosCode(e.params.data.id); }',

                    ],

                ]);

                ?>

For the second select2:


<?=

                $form->field($model, 'destino_code_id')->widget(Select2::className(), [

                    'model' => $model,

                    'attribute' => 'destino_code_id', //con client_code o firmantes

                    'data' => ArrayHelper::map(app\models\DestinosCode::find()->andWhere(['destino_id' => $model->Idn])->all(), 'CodOp', 'Descripcion'),

                    'options' => $select2Options,

                ]);

                ?>

The necessary script in the views:


<script>

       function populateDestinosCode(destino_id) {

            var url = '<?= Url::to(['destinos/populate-destinos-code', 'id' => '-id-']) ?>';

            var $select = $('#datossal-destino_code_id');

            $select.find('option').remove().end();

            $.ajax({

                url: url.replace('-id-', destino_id),

                success: function(data) {

                    var select2Options = <?= Json::encode($select2Options) ?>;

                    select2Options.data = data.data;

                    $select.select2(select2Options);

                    $select.val(data.selected).trigger('change');

                }

            });

        }

        

    </script>

Also you need to initialize and to finalize the procedure with this:


<?php ob_start(); // output buffer the javascript to register later 


<?php $this->registerJs(str_replace(['<script>', '</script>'], '', ob_get_clean()), View::POS_END); ?>

This is the variable utilized in the views:


$select2Options = [

    'multiple' => false,

    'theme' => 'krajee',

    'placeholder' => 'Modo de autocompletar',

    'language' => 'en-US',

    'width' => '100%',

];

Thank you for the visitors, I hope so to somebody else may utilize this procedure.

Thank you very much to all