Active dropdown list with selected

I have the following active drop down list


<?php 

echo CHtml::activeDropDownList($project, 'city', CHtml::listData(City::model()->findAll(), 'id', 'name'), array('class'=>'st-form', 'onchange' => 'getLocationByCity(this)')); 

?>

I want to add selected option to the 10th value in the drop down list when the list is being created, how do I do it.

Thanks.

The thing is CHtml::activeDropDownList helper will automatically, by design, select the value (in your code, ‘id’) in the list corresponding to the value of $project->city (which I suppose matches ‘id’, not ‘name’). Meaning it will output the needed HTML to achieve that.

But If you use CHtml:dropDownList, you can specify the value to be selected.

Or if activeDropDownList is needed, you could simply have some jQuery code to change that selected value to the 10th one in the dropdown.

Hi bennouna,

I know it can be achieved by using javascript or a normal dropdownlist, what I want to know how to do it using activeDropDownList().

I didnt quite get your first part of the answer, can you please elaborate or give some code example if possible.

Thanks.

Hello. I was saying that you can’t do it otherwise (as far as I know) and I was giving 2 alternatives, which you knew already. Sorry.

:slight_smile: thank you for your answers.

Hello!

I’m thinking, that I’ve found a solution.

You’re using activeDropDownList and it means that:

  1. You have a (blank) model, which was created before.

  2. You have a value to be set as selected in php code.

So you can just make it by simple assigment:




$city_id = 10; 

...

$project = new Project();

$project->city = $city;

...

echo CHtml::activeDropDownList($project, 'city', CHtml::listData(City::model()->findAll(), 'id', 'name'),); 



Good luck!