1

I'd like to assign a user to a custom group instead a some standard Joomla group, based on a dropdown choice. I've created a user group named "students". Then I added a new custom custom field for the registration form (it's just one for everyone). The custom field is a dropdown and if the user select "yes", I want that at the end of the registration it'll be automatically assigned to the "students" group instead of the guests. Any help would be really appreciated! :)

Thank you all!

2
  • Do you want only students group assigned when user select the Yes in drop down ? What happen when user choose No ? Commented Apr 26, 2018 at 10:39
  • Hello, I want that if the user select Yes in the dropdown he'll be automatically assigned to the Student group, and if he chose No, he'll be automatically assigned to the Registered group Commented Apr 26, 2018 at 11:01

1 Answer 1

3
  • Write user plugin which will have the below file structure
    • plugins/user/plugins_name/
      • plg_add_group.php
      • plg_add_group.xml
  • plg_add_group.xml - Write plugin manifest code here you can refere below link for the same. https://docs.joomla.org/J3.x:Creating_a_Plugin_for_Joomla

  • plg_add_group.php : Write below php code in this file.

<?php

defined('_JEXEC') or die('Unauthorized Access');

class PlgUserTest extends JPlugin
{ 
  public function onUserAfterSave($data, $isNew, $result, $error)
  {
      if($data['com_fields']['do-you-want-to-become-student']==1)
      {
       //Note - This code in your case need little bit modification as here I not removed current user group which is register in your case, So if you wanted to add only student group you should be removing all other groups before adding student group.  
          jimport('joomla.user.helper');
          JUserHelper::addUserToGroup($data['id'], 3); 
          // 3 Should be your student user group id

      }
      return true;
  }
}
?>

Joomla gives user type of plugin which have onUserBeforeSave() trigger, but this trigger never sends updated/injected data to save method of user hence we need to use onUserAfterSave() trigger to update group of user after it saves, If you see the code we have called addGroup method of joomla user helper to add group if User choose Yes in registration form 'Do you want to become Student field'.

$data['com_fields']['do-you-want-to-become-student'] 

This line is for getting your Yes/No field value, so the key need to update according to your fields name.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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