Jump to content

Recommended Posts

Posted

Hi all,

I wanted to generate a Customer Code that I can attach to the user registered from ryan's LoginRegister module's front-end sign up. I was aiming to have something like "ABCD-XY12345678" where X and Y are the user's initials and the number is the User object's id field (formatted to 8 digits). Unfortunately, I only got "ABCD-XY00000000". Is there a way to retrieve this newly created user's ID?

Here's the code from LoginRegister.module (I have added new fields to the User template: fname, lname, and customerid):

$user = $users->newUser();
$fname = '';
$lname = '';
$id = sprintf('%08d',$user->id);
// populate values to new user
foreach($values as $key => $value) {
  if(strpos($key, 'register_') !== 0) continue;
  $key = str_replace('register_', '', $key); 
  if($key == 'roles') continue; // don't allow this, just in case
  if($key != 'name' && !$user->template->fieldgroup->hasField($key)) continue;
  if($key == 'fname') $fname = substr($value,0,1);
  if($key == 'lname') $lname = substr($value,0,1);
  $user->set($key, $value); 
}
$customercode = "ABCD-$fname$lname$id";
$user->set('customerid',$customercode);

I did try to edit once more after the $user->save() call down the code but I was greeted with a registration error.

// create the user
try {
  $this->createUserReady($user);
  $user->save();
  $id = sprintf('%08d',$user->id);
  $customercode = "ABCD-$fname$lname$id";
  $user->set('customerid',$customercode);
  $user->save();
} catch(\Exception $e) {
  throw new WireException('Unable to create user');
}

 

Posted

Try using the createdUser() hook as this is called after the new user is actually created, so there will actually be an ID for them.

You can do this by attaching to the hook in your site/ready.php file, like this...

$pages->addHookAfter("LoginRegister::createdUser", function ($event) {
    $new_user = $event->arguments(0);
	// Your code in here.
});

You should be able to save the $new_user after pulling the ID and creating the customer code.

Edited to add: Ah, you're using LoginRegister - not LoginRegisterPro. Fortunately they both have the same method, so I've updated the code to represent this.

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
  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...