如何在yii2

时间:2018-11-11 12:30:00

标签: yii yii2 yii2-advanced-app

我想在一个下拉列表中归因于kodepos和kabupaten。以及kodepos和kabupaten属性包含在数据库中。谁能帮我?谢谢

<?= $form->field($model, 'origin')->label('Origin')->widget(Select2::classname(), [
    'data' => ArrayHelper::map(MKota::find()->all(),'kodepos','kodepos'),
    'theme' => Select2::THEME_BOOTSTRAP,
    'language' => 'en',
    'options' => ['placeholder' => 'Pilih Kode Pos','required' => true,'style'=>'width:500px','maxlength' => true],
    'pluginOptions' => [
    'allowClear' => true
    ],
    ]);
?>

<?= $form->field($model, 'origin_name')->label('Origin')->widget(Select2::classname(), [
    'data' => ArrayHelper::map(MKota::find()->all(),'kabupaten','kabupaten'),
    'theme' => Select2::THEME_BOOTSTRAP,
    'language' => 'en',
    'options' => ['placeholder' => 'Pilih Kota Asal','required' => true,'style'=>'width:500px','maxlength' => true],
    'pluginOptions' => [
    'allowClear' => true
    ],
    ]);
?>

1 个答案:

答案 0 :(得分:0)

您需要将ArrayHelper::map()更改为将closure用于第三个参数或$to参数,并返回您想要连接的2个字段。

不清楚您想在第一个和第二个下拉列表中以文本形式显示的字段名称,因此我假设整数值来自id字段。

我将添加将idkodepos串联在一起的代码作为第一个下拉菜单的文本,并将idkabupaten串联在一起的代码显示为第二个下拉菜单的文本。在代码中进行相应的更改

<?= $form->field($model, 'origin')->label('Origin')->widget(Select2::classname(), [
    'data' => ArrayHelper::map(MKota::find()->all(),'kodepos',function($model){return $model->id.$model->kodepos}),
    'theme' => Select2::THEME_BOOTSTRAP,
    'language' => 'en',
    'options' => ['placeholder' => 'Pilih Kode Pos','required' => true,'style'=>'width:500px','maxlength' => true],
    'pluginOptions' => [
    'allowClear' => true
    ],
    ]);
?>

<?= $form->field($model, 'origin_name')->label('Origin')->widget(Select2::classname(), [
    'data' => ArrayHelper::map(MKota::find()->all(),'kabupaten',function($model){return $model->id.$model->kabupaten}),
    'theme' => Select2::THEME_BOOTSTRAP,
    'language' => 'en',
    'options' => ['placeholder' => 'Pilih Kota Asal','required' => true,'style'=>'width:500px','maxlength' => true],
    'pluginOptions' => [
    'allowClear' => true
    ],
    ]);
?>

编辑:

您希望将kodeposkabupaten放在一个下拉列表中,而不是进行两个下拉列表,因此将代码更改为以下内容

<?= $form->field($model, 'origin')->label('Origin')->widget(Select2::classname(), [
    'data' => ArrayHelper::map(MKota::find()->all(),function($model){return $model->kodepos.$model->kabupaten}),function($model){return $model->kodepos.$model->kabupaten}),
    'theme' => Select2::THEME_BOOTSTRAP,
    'language' => 'en',
    'options' => ['placeholder' => 'Pilih Kode Pos','required' => true,'style'=>'width:500px','maxlength' => true],
    'pluginOptions' => [
    'allowClear' => true
    ],
    ]);
?>