Search code examples
phpactiverecordnon-relational-databaseyii

How to have Yii generate drop-down list from known users?


I am just starting learning to use yii, and already managed to do some basic stuff.

Let's say I have two simple tables: "users" and "projects" where the relation is 1 to many (one user can have many projects)

I have generated CRUD using GII, but in the "create/edit user page" this doesn't provide the dropdown but only a text field where I need to enter the user ID.

When editing a project, I would like to have a dropdown list where I can select a user (so the element should display a list of user names).

I assume GII is not able to generate the controller and view code for this

What would be the best practice for doing this?

I have already declared the relationships as instructed in http://www.yiiframework.com/doc/guide/1.1/en/database.arr

public function relations()
{
   return array(
        'projects_rel'=>array(self::BELONGS_TO, 'Users', 'user_id'),
    );
}

and

public function relations()
{
    return array(
        'users_rel'=>array(self::HAS_MANY, 'Projects', 'project_id'),
    );
}

Solution

  • Find the sample code to generate users list

    <?php
        $form = $this->beginWidget('CActiveForm', array(
                    'id' => 'project-form',
                    'enableAjaxValidation' => true,
                ));
    

    ?>

    <?php echo $form->dropDownList($model, 'user_id',
                    CHtml::listData(Projects::model()->with('projects_rel')->findAll(), 'id', 'username'),
                    array('style'=>'width:150px;')
                    ); ?>