We launched new forums in March 2019—join us there. In a hurry for help with your website? Get Help Now!
    • 44195
    • 293 Posts
    How would I go about only displaying users in a certain usergroup?

    I've stolen this from the modx core (can't remember if I've modified it at all) but it currently displays all users.
    If I pass it the name of a usergroup, what query would I use to only display the members of that group?

    <?php
    class AssignedJudgesGetListProcessor extends modObjectGetListProcessor {
        public $classKey = 'modUser';
        public $languageTopics = array('user');
        public $permission = 'view_user';
        public $defaultSortField = 'email';
    
    
        public function initialize() {
            $initialized = parent::initialize();
            $this->setDefaultProperties(array(
                'usergroup' => false,
                'query' => '',
            ));
            if ($this->getProperty('sort') == 'username_link') $this->setProperty('sort','username');
            if ($this->getProperty('sort') == 'id') $this->setProperty('sort','modUser.id');
            return $initialized;
        }
    
        public function prepareQueryBeforeCount(xPDOQuery $c) {
            $c->leftJoin('modUserProfile','Profile');
    
            $query = $this->getProperty('query','');
            if (!empty($query)) {
                $c->where(array('modUser.username:LIKE' => '%'.$query.'%'));
                $c->orCondition(array('Profile.fullname:LIKE' => '%'.$query.'%'));
                $c->orCondition(array('Profile.email:LIKE' => '%'.$query.'%'));
            }
    
            $userGroup = $this->getProperty('usergroup',0);
            if (!empty($userGroup)) {
                $c->innerJoin('modUserGroupMember','UserGroupMembers');
                $c->where(array(
                    'UserGroupMembers.user_group' => $userGroup,
                ));
            }
    
    
    
            /*
             !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
             I tried adding this but I'm not really sure what I'm doing...obviously not working :)
            */
            $userGroupName = 'Judges#'.$this->getProperty('galleryId');
            if(!empty($galleryId)) {
                $c->where(array(
                    'UserGroupMembers.user_group' => $userGroupName,
                ));
            }
    
    
    
    
            return $c;
        }
    
        public function prepareQueryAfterCount(xPDOQuery $c) {
            $c->select($this->modx->getSelectColumns('modUser','modUser'));
            $c->select($this->modx->getSelectColumns('modUserProfile','Profile','',array('fullname','email','blocked')));
            //$this->setProperty('username', $this->getProperty('email'));
            return $c;
        }
    
        /**
         * Prepare the row for iteration
         * @param xPDOObject $object
         * @return array
         */
        public function prepareRow(xPDOObject $object) {
            $objectArray = $object->toArray();
            $objectArray['blocked'] = $object->get('blocked') ? true : false;
            $objectArray['cls'] = 'pupdate premove pcopy';
            unset($objectArray['password'],$objectArray['cachepwd'],$objectArray['salt']);
            return $objectArray;
        }
    }
    return 'AssignedJudgesGetListProcessor';
    


    To be clear the user groups I programmatically create are Judges# combined with the galleryID.
    e.g. Judges#19

    I'm sure much of the above processor is redundant but trying to learn!

    Thank you!

    This question has been answered by Bruno17. See the first response.

      I'm lead developer at Digital Penguin Creative Studio in Hong Kong. https://www.digitalpenguin.hk
      Check out the MODX tutorial series on my blog at https://www.hkwebdeveloper.com
      • 44195
      • 293 Posts
      Or feel free to ignore what I have above if it's too convoluted.

      How can I get a list of users that belong to a specific group?


        I'm lead developer at Digital Penguin Creative Studio in Hong Kong. https://www.digitalpenguin.hk
        Check out the MODX tutorial series on my blog at https://www.hkwebdeveloper.com
        • 44195
        • 293 Posts
        ok I feel I'm a bit closer with this but still not working

        $judgesGroup = 'JudgesGallery#'.$this->getProperty('galleryId');
        if(!empty($judgesGroup)) {
            $c->innerJoin('modUserGroup', 'PrimaryGroup');
            $c->where(array('PrimaryGroup.name' => $judgesGroup));
        }
        


        $judgesGroup is definitely holding the required string but it's not matching the query.
          I'm lead developer at Digital Penguin Creative Studio in Hong Kong. https://www.digitalpenguin.hk
          Check out the MODX tutorial series on my blog at https://www.hkwebdeveloper.com
        • discuss.answer
          • 4172
          • 5,888 Posts
          what about something like that?

          if ($usergroup = $this->modx->getObject('modUserGroup',array('name' => $judgesGroup))){
              if ($usercollection = $usergroup->getUsersIn()){
                  foreach ($usercollection as $userobject){
                      //do something with the userobject
                  }
              }
          }
            -------------------------------

            you can buy me a beer, if you like MIGX

            http://webcmsolutions.de/migx.html

            Thanks!
            • 44195
            • 293 Posts
            Thanks for your reply Bruno!

            I can see what you're doing there but I'm not sure how to incorporate that into the xPDOQuery of the modObjectGetListProcessor..
            The result needs to be returned to a grid in the manager.

            IS it possible just to bypass the xPDOQuery object or something like that?
              I'm lead developer at Digital Penguin Creative Studio in Hong Kong. https://www.digitalpenguin.hk
              Check out the MODX tutorial series on my blog at https://www.hkwebdeveloper.com
              • 4172
              • 5,888 Posts
              why does it need to be a modObjectGetListProcessor?
                -------------------------------

                you can buy me a beer, if you like MIGX

                http://webcmsolutions.de/migx.html

                Thanks!
                • 44195
                • 293 Posts
                Quote from: Bruno17 at Apr 23, 2014, 06:56 AM
                why does it need to be a modObjectGetListProcessor?

                Hmmm... purely an assumption on my part. It's the only way I've done it so far! I'll go have a play around and see how I go without using one smiley
                  I'm lead developer at Digital Penguin Creative Studio in Hong Kong. https://www.digitalpenguin.hk
                  Check out the MODX tutorial series on my blog at https://www.hkwebdeveloper.com
                  • 44195
                  • 293 Posts
                  I couldn't work out how to return the result to the extjs grid panel in a way it would display it but I've tried a different approach...

                  I've overridden the getData() method in modObjectGetListProcessor and added my own data thanks to your function above.
                  public function getData() {
                  
                          $data = array();
                          $limit = intval($this->getProperty('limit'));
                          $start = intval($this->getProperty('start'));
                  
                          $userCollection = array();
                          $judgesGroup = 'JudgesGallery#'.$this->getProperty('galleryId');
                          if ($userGroup = $this->modx->getObject('modUserGroup',array('name' => $judgesGroup))) {
                              $userCollection = $userGroup->getUsersIn();
                          }
                  
                          /* query for chunks */
                          $c = $this->modx->newQuery($this->classKey);
                          $c = $this->prepareQueryBeforeCount($c);
                          //$data['total'] = $this->modx->getCount($this->classKey,$c);
                          $data['total'] = sizeof($userCollection);
                          $c = $this->prepareQueryAfterCount($c);
                  
                          $sortClassKey = $this->getSortClassKey();
                          $sortKey = $this->modx->getSelectColumns($sortClassKey,$this->getProperty('sortAlias',$sortClassKey),'',array($this->getProperty('sort')));
                          if (empty($sortKey)) $sortKey = $this->getProperty('sort');
                          $c->sortby($sortKey,$this->getProperty('dir'));
                          if ($limit > 0) {
                              $c->limit($limit,$start);
                          }
                  
                          //$data['results'] = $this->modx->getCollection($this->classKey,$c);
                          $data['results'] = $userCollection;
                  
                          return $data;
                      }
                  


                  It's working in that it's returning the correct users however I don't seem to be getting anything from modUserProfile..

                  For example, my grid has 3 columns (fullname, email, username). Only the username is displaying. I assume this to be because the 'username' field is in the modUser table and the 'email' and 'fullname' fields are in the modUserProfile table.

                  Is there an easy way of having these values returned as well?



                  This is what's being returned
                  {"total":"2","results":
                  [{"id":45,"username":"user1","class_key":"modUser","active":true,"remote_key":null,"remote_data":null,"hash_class":"hashing.modPBKDF2","p
                  rimary_group":0,"session_stale":null,"sudo":false,"role":"Judge","role_name":"Judge","blocked":false,"cls":"pupdate premove 
                  pcopy"},
                  {"id":46,"username":"user2","class_key":"modUser","active":true,"remote_key":null,"remote_data":null,"hash_class":"hashing.modPBKDF2","
                  primary_group":0,"session_stale":null,"sudo":false,"role":"Judge","role_name":"Judge","blocked":false,"cls":"pupdate premove 
                  pcopy"}]}
                  
                  [ed. note: muzzstick last edited this post 10 years ago.]
                    I'm lead developer at Digital Penguin Creative Studio in Hong Kong. https://www.digitalpenguin.hk
                    Check out the MODX tutorial series on my blog at https://www.hkwebdeveloper.com
                    • 44195
                    • 293 Posts
                    Ok so here's my simplified getData function.
                    by using getOne() I can definitely get the related field values from the 'Profile' object but they are not being saved/returned together.

                    Does anyone know how I can merge the tables together and pass them as one array of objects?

                    public function getData() {
                    
                            $data = array();
                            $userCollection = array();
                            $judgesGroup = 'JudgesGallery#'.$this->getProperty('galleryId');
                            if ($userGroup = $this->modx->getObject('modUserGroup',array('name' => $judgesGroup))) {
                                $userCollection = $userGroup->getUsersIn();
                                foreach ($userCollection as $userObject) {
                                    $username = $userObject->get('username');
                                    $this->modx->log(modX::LOG_LEVEL_DEBUG, 'The current value of username : ' . $username);
                                    $profile = $userObject->getOne('Profile');
                                    $this->modx->log(modX::LOG_LEVEL_DEBUG, 'The current value of fullname : ' . $profile->fullname);
                                }
                            }
                    
                            $data['total'] = sizeof($userCollection);
                            $data['results'] = $userCollection;
                    
                            return $data;
                        }
                    


                    I also tried this but no good.
                    $userCollection->leftJoin('modUserProfile', 'Profile');
                    
                      I'm lead developer at Digital Penguin Creative Studio in Hong Kong. https://www.digitalpenguin.hk
                      Check out the MODX tutorial series on my blog at https://www.hkwebdeveloper.com
                      • 44195
                      • 293 Posts
                      SOLVED! I'm a fool.

                      There's no wonder the query wasn't working. When I was creating the user and adding them to the group I wasn't assigning a value to the modUser primary_group field. Of course the association between tables wasn't working!

                      For anyone who may need the answer to this in the future...

                      Here's my create processor
                      class SingleJudgeCreateProcessor extends modObjectProcessor {
                      
                          public $object;
                      
                          public function process() {
                              // gets the id of current gallery
                              $galleryId = $this->getProperty('galleryId');
                      
                              // creates a group using the gallery id if one doesn't already exist
                              if (!$group = $this->modx->getObject('modUserGroup', array('name' => 'JudgesGallery#'.$galleryId))) {
                                  $group = $this->modx->newObject('modUserGroup', array('name' => 'JudgesGallery#'.$galleryId));
                                  $group->save();
                              }
                      
                      
                              // creates the appropriate role for the user if it doesn't already exist
                              if (!$role = $this->modx->getObject('modUserGroupRole', array('name' => 'Judge'))) {
                                  $role = $this->modx->newObject('modUserGroupRole',
                                      array('name' => 'Judge',
                                          'authority' => '7'));
                                  $role->save();
                              }
                      
                              // creates the user account with all the fields the judge will need
                              if(!$user = $this->modx->getObject('modUserProfile', array('email' => $this->getProperty('email')))) {
                                  $user = $this->modx->newObject('modUser', array('username' => $this->getProperty('email')));
                                  $user->set('primary_group', $group->get('id')); // here's the bit I wasn't doing!!
                                  $user->set('password', md5($this->getProperty('password')));
                                  $profile = $this->modx->newObject('modUserProfile');
                                  $profile->set('fullname', $this->getProperty('fullname'));
                                  $profile->set('email', $this->getProperty('email'));
                                  $profile->save();
                                  $user->addOne($profile);
                      
                      
                                  $success = $user->save();
                              } else {
                                  $success = false;
                              }
                      
                              // Assign the user both a group and a role
                              $joinSuccess = $user->joinGroup($group->get('id'), $role->get('id'));
                      
                      
                              if ($success && $joinSuccess) {
                                  $this->modx->log(modX::LOG_LEVEL_ERROR,'Profile Created: '.print_r($_POST,true));
                                  return $this->success();
                              } else {
                                  $this->modx->log(modX::LOG_LEVEL_ERROR,'Profile Denied: '.print_r($_POST,true));
                                  return $this->failure();
                              }
                      
                          }
                      
                      }
                      return 'SingleJudgeCreateProcessor';
                      



                      and here's my getlist processor:
                      class AssignedJudgeGetListProcessor extends modObjectGetListProcessor {
                          public $classKey = 'modUser';
                          public $languageTopics = array('user');
                          public $permission = 'view_user';
                          public $defaultSortField = 'username';
                      
                          public function initialize() {
                              $initialized = parent::initialize();
                              $this->setDefaultProperties(array(
                                  'usergroup' => false,
                                  'query' => '',
                              ));
                              if ($this->getProperty('sort') == 'username_link') $this->setProperty('sort','username');
                              if ($this->getProperty('sort') == 'id') $this->setProperty('sort','modUser.id');
                              return $initialized;
                          }
                      
                          public function prepareQueryBeforeCount(xPDOQuery $c) {
                              $c->leftJoin('modUserProfile','Profile');
                      
                              $query = $this->getProperty('query','');
                              if (!empty($query)) {
                                  $c->where(array('modUser.username:LIKE' => '%'.$query.'%'));
                                  $c->orCondition(array('Profile.fullname:LIKE' => '%'.$query.'%'));
                                  $c->orCondition(array('Profile.email:LIKE' => '%'.$query.'%'));
                              }
                      
                              $userGroup = $this->getProperty('usergroup',0);
                              if (!empty($userGroup)) {
                                  $c->innerJoin('modUserGroupMember','UserGroupMembers');
                                  $c->where(array(
                                      'UserGroupMembers.user_group' => $userGroup,
                                  ));
                              }
                      
                              // This bit here is all that needed to be added after assigning a value to 'primary_group'
                              $userGroupName = $this->getProperty('usergroupname',0);
                              if (!empty($userGroupName)) {
                                  $c->innerJoin('modUserGroup','PrimaryGroup');
                                  $c->where(array(
                                      'PrimaryGroup.name' => $userGroupName,
                                  ));
                              }
                      
                              return $c;
                          }
                      
                          public function prepareQueryAfterCount(xPDOQuery $c) {
                              $c->select($this->modx->getSelectColumns('modUser','modUser'));
                              $c->select($this->modx->getSelectColumns('modUserProfile','Profile','',array('fullname','email','blocked')));
                              return $c;
                          }
                      
                          /**
                           * Prepare the row for iteration
                           * @param xPDOObject $object
                           * @return array
                           */
                          public function prepareRow(xPDOObject $object) {
                              $objectArray = $object->toArray();
                              $objectArray['blocked'] = $object->get('blocked') ? true : false;
                              $objectArray['cls'] = 'pupdate premove pcopy';
                              unset($objectArray['password'],$objectArray['cachepwd'],$objectArray['salt']);
                              return $objectArray;
                          }
                      }
                      return 'AssignedJudgeGetListProcessor';
                      


                        I'm lead developer at Digital Penguin Creative Studio in Hong Kong. https://www.digitalpenguin.hk
                        Check out the MODX tutorial series on my blog at https://www.hkwebdeveloper.com