1

I'm trying to register a user from the front-end and assign them to a specific group. I know that via control panel I can set a default user group, but there is a registration instance where I need the registrant to be assigned to a different group.

I tried this to no avail...

<input type="hidden" name="groups" value="4">
1

You can only do this with custom PHP otherwise this is going to be a high security risk. Imagine someone just changes your HTML and inserts a different group id: everyone could just join the group he/she likes.

Instead you can Enhancing a Craft CMS 3 Website with a Custom Module - there is already a default one and insert an event to do this by yourself but you need to be careful. I wouldn't trust user input in that case too much.

Event::on(
    Elements::class,
    Elements::EVENT_AFTER_SAVE_ELEMENT,
    function(ElementEvent $event){
        if(\get_class($event->element) === User::class){
            $joinSpecialGroup = (bool)Craft::$app->getRequest()->getBodyParam('joinSpecialGroup');
            if($joinSpecialGroup === true){
                Craft::$app->getUsers()->assignUserToGroups($event->element->id, [4]);
            }
        }
    }
);

Note: I woulnd't call the property joinSpecialGroup - it is just for demonstration

  • Thanks for the example. Before others implement - To get the from an unrestricted form parameter is hugely unsafe as malicious users would be able to assign themselves to an arbitrary group (i.e. with control panel rights for example) – 24HOURSMEDIA Sep 10 at 12:08
1

We just had to do this and tried Freeform Pro and their Element Connection feature. It took a few minutes to build the whole thing including all the required emails.

https://solspace.com/craft/freeform/docs/user-registration-forms/

Also - just noticed Craftquest has a free tutoarial on building user registration form using Freeform.

https://craftquest.io/courses/managing-forms-with-solspace-freeform/5246

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.