YII Relation Quiries in Forms
Introduction
I’ve inherited this application built totally on Yii. It’s a administration site that handles the management of some of our tools and I’ve been tasked with setting up user management.I just got user auth working with salted passwords. Which works wonders and was (looking back) easier then thought to implement. Now I’m tasked with setting up user role management.My schema looks like:User--------------------------
UserID, Name, Email, PasswordUserInRoles
-----------------
PK, userID, RoleIDRoles
-------------------
roleID, Name, AccessLevelWhen you build out your models (I used Giix to generate it) you can override the default relations() function to create relations between tables. Great, I did that. Then I ran the CRUD for Giix. I got user in roles, and a few other junk tables I really didn’t need.What I needed was to take the user from the user table, associate it with a role I select and post that into the userinroles table. Easy? So, I thought.How to:1. Setup relations in your models In terms of how things are laid out, this is your knowledge of your app comes in. My user stuff related to userinroles which related to roles. I defined these relations in each class2. Run Giix to create the CRUD interface3. Now go into the view you want to be the central entry point for managing all these relations, for me it was the _form.php user view.3 a. In the _form.php it generated.
<label>Tools Access</label> <?php echo $form->checkBoxList($model, 'toolaccesses', GxHtml::encodeEx(GxHtml::listDataEx(Toolaccess::model()->findAllAttributes(null, true)), false, true)); ?>
3 b. So this automatically generated one out of 3 of my relations for this view, so I duplicated it twice, updated Toolaccess:: to reflect the controllers Role & tool, and the , 'toolaccesses' to reflect the model I wanted to update and tested it. It renders the form correctly but post doesn’t work. Well you need to update the user controller ( the controller for this view )4. That’s easy enough, in my user controller update, I check if the userinroles post has been defined, if so iterate over that array and create a new class, pass in my attributes and update the record.
if(isset($_POST['User']['userinroles'])){
foreach($_POST['User']['userinroles'] as $role){
$userInRoles = new Userinroles:
$userInRoles->setAttribute('userid', $id);
$userInRoles->setAttribute('roleid', $role);
$userInRoles->save();
}
}
4 A. Just duplicate for actionCreate() and actionDelete(), with some modifications but you now have a basic way to add roles to a user. It may be smart in the update method to check if the user already has this role, if so, don’t do an update, if the user has new roles but not old ones, delete the old ones. But this gives you the basic structure to get you going.