activeDropDownList MANY_TO_MANY

I’ve searched the Interwebs for an example of how to create an activeDropDownList from a many-to-many relation, but have not had much success.

I have three tables in my database:

  1. employee(id, firstname, lastname)

  2. department(id, name)

  3. employee_department(employee_id FK references employee.id, department_id FK references department.id)

I have not generated a model/CRUD views for employee_department (do I have to?).

In my Employee model, a relation is defined where each employee can belong to zero-to-many departments:




'departments' => array(self::MANY_MANY, 'Department', 'employee_department(employee_id, department_id)')



In my Departments model, I have:




'employees' => array(self::MANY_MANY, 'Employee', 'employee_department(department_id, employee_id)')



I now want to modify the Gii generated Employee/create view so that it contains a dropdown with department names. How would I do this? I don’t even know where to begin, so any help would be appreciated.

This method will generate the data for your dropdownlist. In your create view you’ll want to show all departments, so the first parameter would read




Department::model()->findAll()



/Tommy

Hi tri: thanks for your reply.

Does this mean I have to generate a model for the employee_department MANY_MANY table?

In the _form.php partial-view (for Employee) I would have something like:




<?phpp echo activeDropDownList(EmployeeDepartment::model(), 'department_id', CHtml::listData(Department::model()->findAll(), 'id', 'name')); ?>



How would I then populate the EmployeeDepartment.employee_id?

Creating a model for the association table is e.g. needed if you want to access additional attributes from that table. Not relevant to your case.

Note: you should use the model instance passed to your view as parameter 1 to your dropdownlist.

There are a couple of extensions that can help saving related records. E.g. have a look at CAdvancedArBehavior.

/Tommy