We launched new forums in March 2019—join us there. In a hurry for help with your website? Get Help Now!
    • 38970
    • 59 Posts
    Hello,

    I am trying to create a new user and then assign that user a usergroup and role:
    //create the user
    $user = $modx->newObject('modUser', array ('username'=>$ipn['info']['email']));
    $userProfile = $modx->newObject('modUserProfile');
    //join the usergroup and assign role
    $user->joinGroup(5,4);
    
    //set the fields
    foreach ($ipn['info'] as $key => $ui) {
         $userProfile->set($key,$ui);
    }
    //add extended info
    $userProfile->set('extended',$ipn['extended']);
    $success = $user->addOne($userProfile);
    
    //set the password as their phone number
    $user->set('password',md5($ipn['info']['phone']));
    
    if ($success) {
        $user->save();
        $modx->log(modX::LOG_LEVEL_ERROR,'Profile Created: '.print_r($_POST,true));
    } else {
        $modx->log(modX::LOG_LEVEL_ERROR,'Profile Denied: '.print_r($_POST,true));
    }
    


    Everything is working fine except : $user->joinGroup(5,4); which produces this in the error log:
    modUserGroupMember: Attempt to set NOT NULL field member to NULL
      • 3749
      • 24,544 Posts
      The joinGroup() user method doesn't accept a comma-separated list (though it would be a nice feature). You'll have to call it twice. The resource joinGroup() method works the same way.


      ------------------------------------------------------------------------------------------
      PLEASE, PLEASE specify the version of MODX you are using.
      MODX info for everyone: http://bobsguides.com/modx.html
        Did I help you? Buy me a beer
        Get my Book: MODX:The Official Guide
        MODX info for everyone: http://bobsguides.com/modx.html
        My MODX Extras
        Bob's Guides is now hosted at A2 MODX Hosting
        • 18373 ☆ A M B ☆
        • 3,141 Posts
        Mark Hamstra Reply #3, 14 years ago
        Slightly off-topic, but this may be important for you at another time.

        This bit of code:
        //set the password as their phone number
        $user->set('password',md5($ipn['info']['phone']));

        actually sets the users password to an md5 hash of their phone number. Whatever you pass to set('password') is automatically hashed using the users' hash_class as of Revo 2.1. See https://github.com/modxcms/revolution/blob/release-2.2/core/model/modx/moduser.class.php#L51
          Mark Hamstra • Developer spending his days working on Premium Extras and a MODX Site Dashboard with the ability to remotely upgrade MODX and extras to make the MODX world a little better.

          Tweet me @mark_hamstra, check my infrequent blog at markhamstra.com, my slightly more frequent ramblings at MODX.today or see code at Github.
          • 14951
          • 151 Posts
          Not to contradict the great BobRay.. but as far as I can see his syntax is correct.

          The joinGroup() method takes two parameters separated by comma, the first being the id of the group and the second (optional) the role to assign.

          I'd apprehend that the issue is that the joinGroup() method is being run prior to saving the user, therefore the user does not yet have an "id".

          If you save the user prior to joinGroup(), you should be good to go!
            • 3749
            • 24,544 Posts
            Contradict away -- I'm wrong all the time. wink

            I incorrectly assumed that the OP was trying to have the user join two group at once (though the post clearly says otherwise).

              Did I help you? Buy me a beer
              Get my Book: MODX:The Official Guide
              MODX info for everyone: http://bobsguides.com/modx.html
              My MODX Extras
              Bob's Guides is now hosted at A2 MODX Hosting
              • 10378
              • 375 Posts
              Using this old thread to clarify a problem I have with the joinGroup method (MODX Revo 2.3.1):

              I'm just using the joinGroup method for a new add-on an it seems this method has a problem when trying to only assign a group without a role.

              $user->joinGroup(intval($group), intval($role)); // where $role = '0' (= NONE in 'modx-combo-role' ExtJS element)
              
              or 
              
              $user->joinGroup(intval($group));
              


              Both method calls writes a role with id 1 to the modx_member_groups table.
              Don't know why this happens!? Could be a bug in joinGroup method:

                  /**
                   * Join a User Group, and optionally assign a Role.
                   *
                   * @access public
                   * @param mixed $groupId Either the name or ID of the User Group to join.
                   * @param mixed $roleId Optional. Either the name or ID of the Role to
                   * assign to for the group.
                   * @return boolean True if successful.
                   */
                  public function joinGroup($groupId,$roleId = null) {
                      $joined = false;
              
                      $groupPk = is_string($groupId) ? array('name' => $groupId) : $groupId;
                      /** @var modUserGroup $userGroup */
                      $userGroup = $this->xpdo->getObject('modUserGroup',$groupPk);
                      if (empty($userGroup)) {
                          $this->xpdo->log(xPDO::LOG_LEVEL_ERROR,'User Group not found with key: '.$groupId);
                          return $joined;
                      }
              
                      /** @var modUserGroupRole $role */
                      if (!empty($roleId)) {
                          $rolePk = is_string($roleId) ? array('name' => $roleId) : $roleId;
                          $role = $this->xpdo->getObject('modUserGroupRole',$rolePk);
                          if (empty($role)) {
                              $this->xpdo->log(xPDO::LOG_LEVEL_ERROR,'Role not found with key: '.$role);
                              return $joined;
                          }
                      }
              
                      /** @var modUserGroupMember $member */
                      $member = $this->xpdo->getObject('modUserGroupMember',array(
                          'member' => $this->get('id'),
                          'user_group' => $userGroup->get('id'),
                      ));
                      if (empty($member)) {
                          $rank = count($this->getMany('UserGroupMembers'));
                          $member = $this->xpdo->newObject('modUserGroupMember');
                          $member->set('member',$this->get('id'));
                          $member->set('user_group',$userGroup->get('id'));
                          $member->set('rank', $rank);
                          if (!empty($role)) {
                              $member->set('role',$role->get('id'));
                          }
                          $joined = $member->save();
                          if (!$joined) {
                              $this->xpdo->log(xPDO::LOG_LEVEL_ERROR,'An unknown error occurred preventing adding the User to the User Group.');
                          } else {
                              unset($_SESSION["modx.user.{$this->get('id')}.userGroupNames"]);
                          }
                      } else {
                          $joined = true;
                      }
                      return $joined;
                  }
              


              I think the problem lies in line 42, where we try to determine whether the non existent object $role is empty(). [ed. note: gadgetto last edited this post 12 years, 2 months ago.]
                Freelancer @bitego http://www.bitego.com
                ---
                GoodNews - one of the most advanced and integrated Group Mailer premium add-ons for MODX Revolution!
                More infos here: http://www.bitego.com/extras/goodnews/
                • 3749
                • 24,544 Posts
                I think putting this at line 12 would solve it:

                $role = null;


                As the code is written, $role is undefined if $roleId is empty.
                  Did I help you? Buy me a beer
                  Get my Book: MODX:The Official Guide
                  MODX info for everyone: http://bobsguides.com/modx.html
                  My MODX Extras
                  Bob's Guides is now hosted at A2 MODX Hosting
                  • 10378
                  • 375 Posts
                  Quote from: BobRay at Aug 06, 2014, 05:38 PM
                  I think putting this at line 12 would solve it:

                  $role = null;


                  As the code is written, $role is undefined if $roleId is empty.

                  I just found out, that the role field in modx_member_groups has a default value of 1.
                  So with the current joinGroup method of the moduser.class.php its not possible to programmatically add a user to a group without assigning a role. Because if you pass 0 as role parameter the role field in modx_member_groups table will always be 1.
                  Its only possible to set the role to 0=NONE through the manager while editing a users access permissions.

                  Now my question is, is it intended that you can add a user to a group without assigning a role? Or should a user at least have the role Member (=1)?

                  [ed. note: gadgetto last edited this post 12 years, 2 months ago.]
                    Freelancer @bitego http://www.bitego.com
                    ---
                    GoodNews - one of the most advanced and integrated Group Mailer premium add-ons for MODX Revolution!
                    More infos here: http://www.bitego.com/extras/goodnews/
                    • 3749
                    • 24,544 Posts
                    If you can have no role in the Manager, I assume it's OK not to set one.

                    Now that you mention it, I recall reading that the default behavior is to set the role to "member."

                    I think this would work for you (and it won't change the default behavior):

                    Change this:

                    if (!empty($role)) {
                       $member->set('role',$role->get('id'));
                    }


                    To this:

                    if (!empty($role)) {
                       $member->set('role',$role->get('id'));
                    }
                    
                    if ($roleId === '0' || $roleId === 0) {  
                       $member->set('role', 0);
                    }
                    

                    [ed. note: BobRay last edited this post 12 years, 2 months ago.]
                      Did I help you? Buy me a beer
                      Get my Book: MODX:The Official Guide
                      MODX info for everyone: http://bobsguides.com/modx.html
                      My MODX Extras
                      Bob's Guides is now hosted at A2 MODX Hosting
                      • 10378
                      • 375 Posts
                      I probably didn't clarify this enough, but the joinGroup method above is from the MODX core (class moduser.class.php).
                      With this method its not possible to programmatically add a user to a group without assigning a role.
                      Needs to be fixed in core.

                        Freelancer @bitego http://www.bitego.com
                        ---
                        GoodNews - one of the most advanced and integrated Group Mailer premium add-ons for MODX Revolution!
                        More infos here: http://www.bitego.com/extras/goodnews/