在我的 Yii2 下拉列表中,我需要我的 'id' 列作为我的选项的值,名称列是用户在 select 选项中看到的内容

In my Yii2 dropdown list I need my 'id' column to be the value of my options and the name column to be what the user sees in the select option

在我的 Yii2 dorpdown 列表中,我需要我的 'id' 列作为我的选项的值,名称列作为用户在 select 下拉列表

中看到的内容

我的代码输出如下:

<select id="gatewayproviders-id" class="form-control" name="GatewayProviders[id]">
<optgroup label="0">
<option value="id">Authorize.net</option>
</optgroup>
<optgroup label="1">
<option value="id">NMI</option>
</optgroup>
</select>

但是我希望它输出以下内容:

<select id="gatewayproviders-id" class="form-control" name="GatewayProviders[id]">
<option value="1">Authorize.net</option>
<option value="2">NMI</option>
</select>

生成此代码的我的 yii2 代码如下:

<?php
    $gatewayTypes = \app\models\GatewayProviders::find()->select('gateway_provider')->orderBy('gateway_provider')->asArray()->all();
    $gatewayProviders = new \app\models\GatewayProviders();
    ?>
    <?= $form->field($gatewayProviders, 'id')->dropDownList(\app\models\GatewayProviders::find()->select(['id' => 'gateway_provider'])->orderBy('id')->asArray()->all())?>

如有任何帮助,我们将不胜感激!

您应该使用 ArrayHelper::map() 创建类型映射(按 ID 索引的名称):

<?php
$gatewayProviders = new \app\models\GatewayProviders();
$gatewayTypes = \app\models\GatewayProviders::find()
    ->select(['id', 'gateway_provider'])
    ->orderBy('gateway_provider')
    ->asArray()
    ->all();
$types = \yii\helpers\ArrayHelper::map($gatewayTypes, 'id', 'gateway_provider');
?>
<?= $form->field($gatewayProviders, 'id')->dropDownList($types)?>