Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

http://www.yiiframework.com/doc/api/1.1/CHtml#dropDownList-detail

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">
    <?php
        echo $form->dropDownList($model, 'id',
        Chtml::listData(UsersTeam::model()->findAllByAttributes(array('coachId'=>$model->id)), 'id', 'teamName'),
        array('empty'=>'Select Team'))
    ?>
</div>

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'),
like image 312
user2205196 Avatar asked Jun 25 '13 15:06

user2205196


2 Answers

$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>
</select>
like image 106
casraf Avatar answered Oct 24 '22 06:10

casraf


You can easily do the same with CHtml::activeDropDownList.

So your code will look like:

<div class="row">
    <?php
        echo CHtml::activeDropDownList($model, 'id',
        Chtml::listData(UsersTeam::model()->findAllByAttributes(array('coachId'=>$model->id)), 'id', 'teamName'),
        array('empty'=>'Select Team'))
    ?>
</div>
like image 26
dev1234 Avatar answered Oct 24 '22 07:10

dev1234