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); ?>