default selected value in dropdown list not showing even if it's set in htmlOptions

Hi, I’m new to Yii and I’m trying to set the default selected value in my dropdown list in _form.php.

My question is, where should I look next if I have set the default values in htmlOptions but the presumed output does not show?

Basically I have this snippet for the dropdown code:


<div class="row">

	<?php echo $form->labelEx($model,'contactId'); ?>

	<?php echo $form->dropDownList($model,'contactId',  array('prompt' => '-- Select one --') + CHtml::listData(Contactdetails::model()->findAll(), 'id', 'name')); ?>

	<?php echo $form->error($model,'contactId'); ?>

</div>

And it shows the following html code:


<option value="prompt">-- Select one --</option>

<option value="1" selected="selected"> asdfghjkl </option>

<option value="2" qwertyuiop ></option>

<option value="3"> zxcvbnm </option>

Thanks!

Try the following code:

I needed to show Mumbai as default selection and my key-value pair was ‘MUM’=>‘Mumbai’;

It worked for me, you can also try it in yourcase.

<?php echo $form->dropDownList($model,‘city’,Yii::app()->params[‘city’],array(‘options’ => array(‘MUM’=>array(‘selected’=>true)))) ?>

OR

In your controller, you can specify the value that needs to be selected by default

eg: $model->columnname=value;

Do like if my solutions are helping you out. :D

Does this mean I still need to change the DB for this?

I can’t do that because I don’t have the access to the database. :(

Bump. Anyone? :(

Hi

Clarify your case:

  • What does show?

  • What do you expect?

  • The code you show is the correct code? What do you want to show.

Based on what you write, I remind you that:

  • The initially selected value should correspond to the value provided by the model. If the model’s value does not correspond to one of the entries, then the prompt should be shown (if provided). If the value is empty, the ‘empty’ value should be shown if provided.

Do not hesitate to read some of the Core code to know how it is supposed to work .

hi

you can try it :


<?php echo CHtml::ActiveDropDownList($model, 'companySnd', $model->getComName(), array('prompt' => ' '))); ?>

>>> It doesn’t show the default value that I declared.

>>> I expect that it shows because it worked with the other drop down lists.

>>> Yep I think it’s correct.

I tried declaring prompt and empty but it is not selected as the default value. However, the value in both of them are in the options.

Solved my problem. The SQL has declared its own default, and it has overriden the default option of dropDownList.