user2205196 user2205196 - 1 year ago 86
PHP Question

how to use Chtml::DropDownList()

i'm currently a newbie when it comes to the yii framework / php. I would like some assistance creating this Chtml::DropDownList.

Chtml::dropDownList($name, $select, $data)

I understand that $data is the array of data I will be loading in from my Database.

But can someone explain to me how $name, and $select truly works. I have a hard time finding documentation that explains this at a extremely dumbdown level.

I manage to get this piece of code working, but I would prefer using Chtml::dropdownlist.

<div class="row">
echo $form->dropDownList($model, 'id',
Chtml::listData(UsersTeam::model()->findAllByAttributes(array('coachId'=>$model->id)), 'id', 'teamName'),
array('empty'=>'Select Team'))

I would like to be able to display all teamName for the current user that he is enlisted in.

I'm currently displaying this in the model view of a User, but the information I need is from UserTeam which holds the teams for the users.

'memberOfTeams' => array(self::MANY_MANY, 'UsersTeam', '{{teamMembers}}(userId, teamId)'),
'coachOfTeams' => array(self::HAS_MANY, 'UsersTeam', 'coachId'),

Answer Source

$name is the name="mySelect" form value it will have (the one that will be passed if sent as a form i.e. $_POST['mySelect']).

$select is the preselected ID. Say you have an array...

$options = array('12' => 'Twelve', '10' => 'Ten');

And your dropdown looks like this...

echo CHtml::dropDownList('mySelect', '12', $options);

Then 'Twelve' will be the preselected item in the dropdown and $_POST['mySelect'] will be the value passed when the form is sent.

You can add additional html options to each <option> tag, using the fourth parameter CHtml::dropDownList accepts, like so:

$htmlOptions = array(
    // adds to the select element
    'style' => 'cursor: pointer;',
    // adds to the actual options
    'options' => array(
        '12' => array('title' => '12')

And updating the call to:

echo CHtml::dropDownList('mySelect', '12', $options, $htmlOptions);

The finished list would look like this:

<select name="mySelect" style="cursor: pointer;">
    <option value="12" selected="selected" title="12">Twelve</option>
    <option value="10">Ten</option>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download