Jump to content

loginRegister Module addHookBefore - Not able to add role


Dean
 Share

Recommended Posts

I don't seem to be able to add a role to a user when they register.

I have a function to return the role as text based on the option that was chosen on the register form. I have checked that this function is returning the correct value by echoing it to the page. If I pass that text into the addRole function (as $myRole) it doesn't work. If I hard code the exact same text into addRole it does work.

Do I need to change my getRole function to return the text in a different format?

function getRole($role) {
	// return name of role based on id from register_member_role
	switch ($role) {
		case 1:
			return "type1";
			break;
		case 2:
			return "type2";
			break;
		case 3:
			return "type3";
			break;
		default:
			return "type1";
	}
}
$loginRegister = $modules->get('LoginRegister');

$myRole = getRole($input->post('register_member_role'));
										
wire()->addHookBefore('LoginRegister::createdUser', function($event) {
	$u = $event->arguments[0]; 
	$u->addRole($myRole);
	$u->save();
});
					
echo $loginRegister->execute();

 

Link to comment
Share on other sites

Or you could also inherit the variable in your closure (anonymous function) from the parent scope (see the use() keyword) :

wire()->addHookBefore('LoginRegister::createdUser', function($event) use($myRole) {
...

 

  • Like 2
Link to comment
Share on other sites

Thank you so much @elabx and @flydev ??. I thought that was it, that I wasn't passing the variable into the function.

However, it is now somehow giving the user the default value returned from getRole(), rather than the value it should give. And yet, if I echo the value returned from getRole() before and after executing loginRegister, it is correct! ?

$myRole = getRole($input->post('register_member_role'));

echo $input->post('register_member_role').' gives '.$myRole; // value is correct here
					
wire()->addHookBefore('LoginRegister::createdUser', function($event) use($myRole) {
	$u = $event->arguments[0]; 
	$u->addRole($myRole);
	$u->save();
});
					
echo $loginRegister->execute();
die($myRole); // value is correct here

 

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...