Question

How to implement the following Yii code to Yii2:

<?php 
   echo $form->dropDownList($model, 
                           'project', 
                           $model->getProjectOptions(), 
                           array('empty' => 'Empty string')
   ); 
?>
Was it helpful?

Solution

Why not

<?
    dropDownList($model, 
        'project', 
        $model->getProjectOptions(), 
        array('prompt'=>'Empty string')
    ); ?>
  • prompt: string, a prompt text to be displayed as the first option;

Here is old CHtml https://github.com/yiisoft/yii2/blob/master/framework/yii/helpers/base/Html.php

Can find there if you need something more.

OTHER TIPS

Use the following code to get the dropdownlist in yii2 friend.

<?php 
    //use app\models\Country;
    $countries=Country::find()->all();

    //use yii\helpers\ArrayHelper;
    $listData=ArrayHelper::map($countries,'code','name');

    echo $form->field($model, 'name')->dropDownList(
                                    $listData, 
                                    ['prompt'=>'Select...']);
    ?>

Try this : You can remove the templet if you want.

<?php
  $form = ActiveForm::begin([
    'id' => 'test-form',
    'options' => ['class' => 'form-horizontal'],
    'enableClientValidation'=> true,
    'enableAjaxValidation'=> false,
    'validateOnSubmit' => true,
    'validateOnChange' => true,
    'validateOnType' => true,
    'action' => Yii::$app->homeUrl . 'your/url/path'
  ]);
?>

    echo $form->field($model, 
                'your_field_name', 
                ['template' => '<div class="col-md-3">
                                     {label}
                                </div>
                               <div class="col-md-9"> 
                                     {input}{error}{hint}
                               </div>'
                ])
                ->dropdownList($option_array, ['prompt' => '--Select--']);

<?php ActiveForm::end(); ?>

You are looking something like this?

<?=$form->field($model, 'project')
        ->dropDownList(ArrayHelper::map(['empty'=>'Empty string'], 'id', 'value'))
        ->label(false);
?>

When you make the projectOptions array, just make the first index had a null key, like that:

[
  null => 'Empty option',
  ... // Your options
]

And in your view you just add

$form->field($model, 'project')->dropDownList($model->projectOptions);

When your function name starts with 'get' followed by an uppercase letter, the yii understand that as an attribute, so

public function getSomeOptions(){ ..

is the same someOptions, is the same principle of the table relationships

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top