Form for MANY_MANY relationship?

Hi all,

Has anyone written up a tutorial on how to handle and create a form for a many to many relationship? I see people asking the question (some years old) but can’t find what I thought would be a straight forward solution.

I dont know of a tutorial like that. Can you provide more information and an example?, maybe we can help out =)


Say I have a table that contains users (User) for which each user can select a number of groups that they want to belong to. I would therefore have a seperate table named something like User_has_Group to store the user/group relationships.

I could list all the available groups with CHtml::listBox() in a form but I don’t know what I need to do to:

  • Pre-populate the box with alerady saved friends

  • save the friends in the User_has_User table in the Yii way

Any ideas?

EDIT: The listBox will have the multiple attribute set to allow multiple selections.

i would do it like this:

  • get names/id from tbl_groups to populate form inputs (multi select box or checkboxes)

  • get group_id from tbl_user_has_group where user_id = current user, make form items selected.

  • user submits form, get params. on group items use ActiveRecord ( to do do something like this:


foreach ($groups as $groupId)


    if (!$groupId==FALSE)


        $userHasGroup = new UserHasGroup;

        $userHasGroup->userId = $user->id;

        $userHasGroup->groupId = $groupId;

        if (!$userHasGroup->save()) print_r($userHasGroup->errors);




Also check these out!:

Thanks 3amsleep,

I think I glanced over the LarryUllman post but as he defines the relationship as a HAS_MANY in relations() I didn’t think it was what I was after.

However I have created a variation of his example and have it working well. If I get a chance over the weekend I would like to make my own blog post illustrating how this can be done.

I Think the best way to do it is to make models for "middle" tables (like user_has_group) and use "Through" relations instead of MANY_MANY (MANY_MANY is pretty much deprecated and it wont be included into Yii 2.0).

Also, give With Related Behavior Extension a try, it’s made by the yii team and maybe it’s all you need =).