Need to assign role based on form submission for members already in the system.

I am trying to create a form that, upon submission, will automatically assign a specific role for the user. I am struggling to connect the Velo code and get it to actually assign the role on submission. I’ve attempted to follow these forum posts but can’t manage to make anything work:

/velo/forum/coding-with-velo/i-have-made-a-register-page-and-used-the-function-assign-role-still-the-role-is-not-assigned-to-the-member

/velo/forum/coding-with-velo/role-to-be-assigned

Any help would be greatly appreciated.

Page Code:
import { roles } from ‘wix-users-backend’ ;

export function assignRole ( roleId , memberId ) {
let role = roleId
let member = memberId
return roles . assignRole ( role , member , { suppressAuth : true })
. then ( () => {
console . log ( “Role assigned to member” );
})
. catch (( error ) => {
console . log ( error );
});
}

roles.jsw code:
import { roles } from ‘wix-users-backend’ ;

export function assignRole ( roleId , memberId ) {
let role = roleId
let member = memberId
return roles . assignRole ( role , member , { suppressAuth : true })
. then ( () => {
console . log ( “Role assigned to member” );
})
. catch (( error ) => {
console . log ( error );
});
}

Please read this doc:
https://www.wix.com/velo/reference/wix-users-backend/roles-obj/assignrole

Hi J.D., I have already read that document. However, it does not provide me with anything more than the base function of assignRole, not how to implement it on an actual page. If you look at the code I posted, it already has those elements present. However, when I click the button that is supposed to trigger the assignRole function, nothing happens. I need to know what is preventing the role from being assigned but my expertise is in Salesforce coding and Velo language/debugging is relatively new to me.

@conormcleod

Well there are some mistakes in your code.
The first one is located directly in your FIRST codeline of your frontend-code…
Instead of this one…

import wixUsersBackend from 'wix-users-backend';

You surely wanted to do this one…

import {assignRole} from 'backend/roles.jsw';

You do not want to import wix-users-backend to your frontend!
You want to import your exported function, called → assignRole() .

And the second one is now provided by me, which will give you all needed informations about the USER directly from the BACKEND, called → get_userData()

So you have now two exported functions running on your BACKEND.

  1. get_userData()
  2. assignRole()

Now you will have to call first the get_userData-function to get all informations about the current logged-in USER.

After you have done this, you can take all collected informations about the current logged-in user, to use this information in your next step → assigning a role to the current logged-in-user.

Your code then would look like the following…

FRONTEND-CODE:

import {get_userData(), assignRole()} from 'backend/roles.jsw';

$w.onReady(function() {
  $w('#anyButtonIDhere').onClick(async()=>{console.log("Button clicked!");
    let userData = await get_userData(); console.log("DATA: ", userData);
    console.log("USER: ", userData.USER);
    console.log("User-ID: ", userData.userID); 
    console.log("User-Logged-In: ", userData.loginSTATUS);
    console.log("User-Email: ", userData.userEmail);
    console.log("User-Roles: ", userData.userRoles);
    
    // first take a look onto the given RESULT-OUTPUT in your CONSOLE!!!
    // make clear how to continue...
    
    // CONTINUE here to assign the right chosen role.....
    assignRole(userData.userRoles[0], userData.userID);
  });
});

BACKEND-CODE: —> roles.jsw


export async function get_userData() {
  let USER = await wixUsersBackend.currentUser;               
  let userID = await USER.id;
  let isLoggedIn = USER.loggedIn; 
  let userEmail = await USER.getEmail(); 
  let userRoles = await USER.getRoles(); 

  let DATA = {}
      DATA.USER = USER;
      DATA.userID = userID;
      DATA.loginSTATUS = isLoggedIn;
      DATA.userEMAIL = userEmail;
  return(DATA)
}
  
export function assignRole(roleId, memberId) {
  return roles.assignRole(roleId, memberId, {suppressAuth: true})
    .then(() => {console.log("Role assigned to member");})
    .catch((error)=> {console.log(error);});
}

Now you normaly should be able to complete your task. Good luck! :wink:

To see a working example, take a look at this one…

https://russian-dima.wixsite.com/login-system/vnloginmgm

  1. Navigate first to the SETUP and CHECK if the MAIN-REGISTRATION-OPTION is activated…


If not, change it to → “MAIN” by activating the SETUP-OPTIONS → PW=“12345”
Please do not touch other SETUP!

  1. SAVE the changed OPTIONS!
  2. Navigate back to REGISTRATION/SIGN-UP-PAGE…


4) Click on → " + " -SIGN a new option-window will appear…


5) You can now see a ROLE-OPTION which you can choose (just one ROLE is ACTIVATED). If you want to activate a further ROLE, and you do not know how to do that —> take alook here …

https://russian-dima.wixsite.com/login-system/info

3-different ROLES are AVAILABLE in this INTERACTIVE-EXAMPLE.

  1. You can run a test, by doing a complete registration, or you just use the already given LOGINs to check for further functionalities and features.

At the end you will recognize that everything works and you are able even to assign roles directly on registration.

Have fun!

@russian-dima Thank you so much for your reply! I tried to make the code changes as suggested, but it is now throwing the following error in the console:

public/pages/vn44z.js: Unexpected token, expected "," (1:20)  
>  1 | import {get_userData(), assignRole()} from 'backend/roles.jsw';
     |                     ^   
   2 |   
   3 | $w.onReady(function() {   
   4 |   $w('#button1').onClick(async()=>{console.log("Button clicked!");

Any idea what is going wrong?

@conormcleod
Ohh SORRY! MY FAULT ! (i should check before posting, but no time :sweat_smile:)
You do not need the BRAKETS…

import {get_userData, assignRole} from 'backend/roles.jsw';

Also you do not explecitely need to declare that it is a jsw-file and you can simply do like this… (try it out and check if it works for you.

import {get_userData, assignRole} from 'backend/roles';

The simpler and shorter your code → the better and faster it will work xD

@russian-dima Thank you, that cleared up that error but unfortunately I’ve now hit a new one:

Preview error:

wixUsersBackend is not defined

Console error:

Uncaught (in promise) Error: Unable to handle the request. Contact the site administrator or view site monitoring logs for more information.

Thank you so much for your help with this, genuinely. I’ve been banging my head against a wall with this for the better part of a week now and this is the quickest progress I’ve made so far and it’s all thank to you!

@conormcleod
Learning from ERRORS is the best way of learning!
So what you got as ERROR? What does tells you the shown ERROR-LOG ?

wixUsersBackend is not defined

Exactly → That something is missing! And it tells you even what is missing!
WixUsers-Backend!

And it is like it is! → I did forget to import Wix-Users-Backend on the BACKEND! :sweat_smile:
This happens when you code to fast, without testing and debugging.
And exactly this will be your JOB!

Test it and DEBUG it! → And never forget → CONSOLE is your BEST-FRIEND!
When you can use the console the right way → you never ever will have any problems when generating codes!

import wixUsersBackend from 'wix-users-backend';

Now try to bring this till end on your own! CONSEOLE will help you out!

@russian-dima THANK YOUUUUUUU!!! It finally works, all it needed was that final import line. YOU ARE A LIFE SAVER!!!

@conormcleod
Perhaps this time i am your live-safer → but next time it should be your CONSOLE :wink:

I want to achieve a similar thing : “At the end you will recognize that everything works and you are able even to assign roles directly on registration.”

Could you please let me know where to find the code examples for the same i.e. creating a members dataset, adding data to it using a custom sign up form and assigning roles at the time of signup. It would be critical to speed up my project.

Please open your own POST here inside the VELO-FORUM.
Describe your issue as most detailed as possible, giving all needed information about the problem.

You can link this post to your own issue.

Wouldn’t it become a duplicate post since I want exactly what’s described in your solution. That’s why I didn’t start a new thread.

No i don’t think it would be a doublicate post, since you want to use a DATASET, the coding will be different.

Working with WIX-DATA and DATASETS are 2-different pair of shoes.

Open your post, describe your project-situation (maybe with some pics of your setup). Write down which elements are used, how and which elements are connected with eachother. Also mention if you are working without the usage of the property-panel (only by code), or if you use it.

Show the CODE you already have generated.

All these things are neccessary to be able to help you.

I am a pure CODER, i like to generate my own custom made functions and features, without any boundaries, this is why you won’t see elements like a dataset in my examples that often.

You can link this post with your own one, for better understandings.