Assign role at registration

Question:
How can a role be assigned automatically at new user registration via a checkbox?

Product:
Wix editor

What are you trying to achieve:
Assign role to user at successful new registration when they check a checkbox on a custom sign-up Lightbox.

What have you already tried:
ChatGPT helped me with this code:

import wixUsersBackend from 'wix-members';

// This function is called when the user clicks the register button
export function onRegisterButton_click(event) {
// Retrieve user input from your registration form
    const email = $w('#input2').value;
    const password = $w('#input1').value;
    // Add additional fields as needed

    // Check if the checkbox is checked
    const isCoachCheckboxChecked = $w('#coachCheckbox').checked;

    // Perform user registration
    wixUsers.register(email, password)
        .then((result) => {
            // Registration successful
            const userId = result.user.id;

            // Assign 'Coach' role to the new user if the checkbox is checked
            if (isCoachCheckboxChecked) {
                assignRoleToUser('Coach', userId);
            }

            // Add any additional logic you need after successful registration
            console.log(`User ${userId} registered successfully.`);
        })
        .catch((error) => {
            // Handle registration errors
            console.error('Registration error:', error);
        });
}

function assignRoleToUser(roleName, userId) {
    wixUsersBackend.roles.assignRole(roleName, userId, { suppressAuth: true })
        .then(() => {
            console.log(`${roleName} role has been assigned to user ${userId}`);
        })
        .catch((error) => {
            console.error(`Error assigning role: ${error}`);
        });
}

Additional information:
Unable to test due to Lightbox

This won’t work as it’s trying to use backend code in the frontend.

The way to assign a rule would be to use this event hook: onMemberCreated - Velo API Reference - Wix.com and to then assign the role for the user within the hook using assignRole - Velo API Reference - Wix.com

Thank you for the assistance.

My implementation didn’t work,
Attempted to use the following code console.log("value: " + isCoachCheckboxChecked); but didn’t return anything

import { roles } from "wix-groups.v2";

export function wixMembers_onMemberCreated(event) {
    const memberNickname = event.entity.profile.nickname;
    const creationEventId = event.metadata.id;

    // Check if the checkbox is checked (replace 'checkboxId' with the actual ID of your checkbox)
    const isCoachCheckboxChecked = $w('#coachCheckbox').checked;
    console.log("value: " + isCoachCheckboxChecked);
    // Assign 'coach' role to the new user if the checkbox is checked
    if (isCoachCheckboxChecked) {
        // Pass an array containing the memberNickname
        assignRole([memberNickname], 'coach', {});
    }

    // Add any additional logic you need after member creation
    console.log(`Member ${memberNickname} created successfully with event ID ${creationEventId}`);
}

export function assignRole(identifiers, role, options) {
    return roles.assignRole(identifiers, role, options)
        .then((response) => {
            console.log(response);
        })
        .catch((error) => {
            console.error(error);
        });
}

I used the import reference from this link: assignRole - Velo API Reference - Wix.com

The import for “wix-groups-backend” was not found in the editor. What am I doing wrong?

Sorry it should be from wix-members-backend: assignRole - Velo API Reference - Wix.com

Also may want to check the following:

  1. That the code using import { roles } from "wix-members-backend"; is being done in the backend

  2. The wixMembers_onMemberCreated function needs to be defined in a file titled events.js in the backend. These functions don’t work in frontend code.

  3. The call to assignRole seems incorrect. The first argument should be an object that contains a field which is an array of memberIds. There’s also other things you can define in the object if needed.

  4. $w cannot be reference in the backend files, you’ll need to assign role in a different way. There’s a few options which I’ve listed in order of complexity:

    • Make setting a user as a coach role a separate function and define it in a velo web module that you can call from the frontend after the user is registered.
    • Make a velo web module function that registers users when called and takes an extra argument on whether or not they’re supposed to be a coach.
    • Get the isCoach data in your wixMembers_onMemberCreated function by defining a custom field for your members and set that when the member is created so that you can access this data from onMemberCreated with theevent.entityobject in the backend. Though I’d probably not recommend this way.

For all of the above options I’m not sure if being able to set yourself as a coach is something any user should do or not. If it’s intended only for admins to be able to set then you might want to set permissions on your functions