Extand Rainlab Users with a primary_group_id field

Hi,

I extend the Rainlab User plugin and added a primary_group_id field which stores the display group id for better availability.

The problem: The user groups are not saved before I do the check for the new primary group id on the save() of a user.

I tried the following solutions:

  • Saving the groups before saving the model so I can properly calculate the new primary group in the beforeSave()
  • Calculating the new primary group id in the afterSave() of the model, but I recognized the groups are not saved at that time as well
  • Building an observer which listen for “upated”, but I might have implemented it wrong, it’s executed before the models save
  • I’ve read something about an event triggered after the model was saved which I could use to silently save the model with the new group again: “eloquent.saving: User” and $model->saveQuietly() to not trigger this event again
  • Modifying the groups relation somehow so the groups are saved immediatly and not deferred
  • Adding a Model for the Users Groups Relation and handling the update of the user there
  • … and several other approaches

However, nothing worked properly and I am very frustrated currently.

A point in the right direction which is the “way to go” for such a problem in combination with extending a plugin would be very welcome.

Thanks a lot!!

This is (semi)official example of extending RainLab.User plugin: userplus-plugin/classes/ExtendUserPlugin.php at master · rainlab/userplus-plugin · GitHub
including really elegant System\Classes\ModelBehavior extension: userplus-plugin/behaviors/UserPlusModel.php at master · rainlab/userplus-plugin · GitHub

2 Likes

Thx for the tip. It brought me to another way which I could finally get to work:

October has Events for attaching and detaching relations:
https://octobercms.com/docs/api/model/relation/attach

Here’s my solution extending Rainlab Users

            $model->bindEvent('model.relation.attach', function (string $relationName, array $ids) use ($model) {
                if ($relationName !== "groups") return;
                $model->load("groups");
                # ...doing some magic with the groups
                $model->saveQuietly();
            });

Hope this is helpful for somebody.

1 Like

Thanks for sharing your solution.

1 Like