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

96
May 15, 2018, at 1:50 PM

In my Yii2 dorpdown 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 dropdownlist

My code is outputting the below:

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

However I want it to output the below:

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

My yii2 code that is generating this is below:

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

Any help on this would be greatly appreciated!

Answer 1

You should use ArrayHelper::map() to create map of types (names indexed by IDs):

<?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)?>
READ ALSO
Reuse oci_connect() connection identifier through different apache-php requests or oci_pconnect() conection pooling

Reuse oci_connect() connection identifier through different apache-php requests or oci_pconnect() conection pooling

I'm facing this problemA client call an API one method each time, API use at least one oci_connect() for each request

66
Form.php file not sending through inputted data

Form.php file not sending through inputted data

I have been working on a form in a php fileAs you'll see from the code below I have written everything in a PHP file including the form tag

34