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

6.5k views Asked by At

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'),
    );
}
3

There are 3 answers

1
Suriyan Suresh On BEST ANSWER

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;')
                ); ?>
0
schmunk On

Checkout these gii extension for generating extended CRUDs:

Both are able to render forms with relation inputs. GTC uses a relation widget for these inputs which can be customized.

0
elmig On

Don't forget to uncomment

$this->performAjaxValidation($model)

on the Controller or you'll have to items created instead of one!