Search code examples
modxmodx-revolution

assign users to group modx


How can i assign newly created user to the particular group in modx Programmaticaly ? Below is my code

if(isset($_POST) && count($_POST)){
  $oUser = $modx->newObject('modUser');
  $oUser->set('username', "test");
  //$oUser->set('password', "test");

  $oProfile = $modx->newObject('modUserProfile');
  $oProfile->set('fullname', $_POST['fname']);
  $oProfile->set('email', $_POST['email']);
  $oUser->addOne($oProfile);
  if($oUser->save()===false){
    echo "Error";
  }else
    echo "Done";
}

I googled but all i find is graphical tutorial how to create groups and edit user and then assign roles, If you know any tutorial then also its fine.


Solution

  • Here is how I have been doing it, this is a posthook snippet that fires after a user registers [and the user is created]

    <?php
    $specialty = $hook->getValue('specialty');
    $country =  strtolower($hook->getValue('excountry'));
    $username = $hook->getValue('username');
    $staff = $hook->getValue('staff-or-resident'); //Staff | Resident
    
    $joingroup = '';
    $joinrole = '';
    $blockuser = 'false';
    
    switch ($specialty){
    
        case 'Other' :
            $joingroup = 15; // Other 
            $joinrole = 1; //member
            $blockuser = 'true';
            break;
    
        // there are about 15 different groups and roles here... 
    
        default :
            $joingroup = '0'; // none
            $joinrole = '0'; // none 
            break;  
    }
    
    if($joingroup > 0 && $joinrole > 0){
        $user = $modx->getObject('modUser', array('username'=>$username));
        $internalkey = $user->get('id');
        $profile = $user->getOne('Profile',array('internalKey'=>$internalkey));
    
        $user->joinGroup($joingroup, $joinrole);
    
        if($blockuser == 'true'){ //block user if they belong to the "other" group
            $profile->set('blocked',1);
        }
    
        if(!$user->save()){
            return false;
        };
    }
    
    return true;
    

    The key is the: $user->joinGroup($joingroup, $joinrole); where joingroup is the group id ~ or name and the joinrole is the role id ~ or name. It's documented here: http://api.modx.com/revolution/2.1/_model_modx_moduser.class.html#%5CmodUser::joinGroup()