Hi I am quite new to PHP. Here I have two models that are user and roles, they have a connection through the third model Users_roles.
The following are my models as a user: user.php
public function relationship () {return array ('userRoles' = & gt; array (auto :: HAS_MANY, '' UserRoles '', 'id_users'),); } roles.php
public function relationship () {return array ('userRoles' => array (auto :: HAS_MANY,' UserRoles ',' Id_roles'),); UsersRoles.php Public function relation () {return array ('idUsers' => array (auto :: BELONGS_TO,' user ',' Id_users'), 'idRoles' = & gt; array (auto :: BELONGS_TO,' roles', 'id_roles'),); } Now that I am creating a user, I can use the checkbox
& lt; Php echo $ form- & gt; LabelEx ($ model, 'roles'); ? & Gt; & Lt ;? Php // print_r ($ userRoles); // die; Akho CHtml :: Active Caxbox List ($ userRoles, 'id_roles', CHtml :: list data (roles :: model) -> search (), 'id', 'name'), array ('template' = & gt ; '{Input} {label}',)); ? & Gt; & Lt ;? Php Acor $ form- & gt; Error ($ models, 'roles'); ? & Gt; Now how can I save those checkbox values in my users_roles tables?
There is a typo in your relationships for users and roles, both of which refer to the UserRoles model , When it should be UsersRoles
Now for your question, I will create a function in the UsersRoles model, named Refresh Reals ($ user, role of $). Where $ user is the user id for which you are playing role, and $ roles are an array of roles that should be set. This function will retrieve the list of roles by id_users, and its role is to remove roles that are missing from $ roles, and roles with $ roles, and add roles that are missing from the UsersRoles table.
This will look like this:
function refreshrol ($ user, roles of $) {$ userRoles = $ this- & gt; Search AllByAttribute (array ('id_users' = & gt; $ user)); Foreign currency ($ userRoles $ userRole) {if (! In_array ($ userRole-> id_roles, $ roles)) {$ userRole-> Remove (); } And {$ key = array_search ($ userRole-> id_roles, $ roles)); Not set ($ roles [$ key]); } Foreign Currency ($ role as role role) {$ model = new UsersRoles (); $ Model- & gt; Id_users = $ user; $ Model- & gt; Id_roles = $ role; $ Models & gt; Save (wrong); }} Call this function to your controller immediately after saving your user model (if you are actually saving the user). Note, this is not unwanted, but will give you head direction.
No comments:
Post a Comment