XF 2.0 Optimal code for pulling UserGroups.

LPH

Well-known member
I'm rebuilding a function to grab the usergroups. This appears to work but I am wondering if this is optimal.

PHP:
function xenwordGetUGIds() {
    $idArr = array();

    if ( class_exists( '\XF' ) ) {
       $groupRepo = \XF::app()->repository('XF:UserGroup');
       $usergroups = $groupRepo->finder('XF:UserGroup');

        foreach ( $usergroups as $usergroup ) {
            $id           = $usergroup['user_group_id'];
            $title        = $usergroup['title'];
            $idArr[ $id ] = $title;
        }

        asort( $idArr );
        return $idArr;
    }
}
 
If you're creating a repository, then you probably want to use a specific method in it (or just skip it and create the finder directly).

As it happens though, the user group repo has a method that is pretty much doing what you're doing: getUserGroupTitlePairs()
 
  • Like
Reactions: LPH
the user group repo has a method that is pretty much doing what you're doing: getUserGroupTitlePairs()

Yes. I saw it but couldn't figure out how to call it properly from outside XF. There was a method not found error. I'll keep tinkering.
 
It's just this:
PHP:
$groupRepo = \XF::app()->repository('XF:UserGroup');
$usergroups = $groupRepo->getUserGroupTitlePairs();
 
  • Like
Reactions: LPH
Hi

I tried that earlier and couldn't remember the error. It turns out there is an illegal offset for the user_group_id.

An exception occurred: [ErrorException] Illegal string offset 'user_group_id'

I'll try a dump(var) to see what is being returned.

Second Question:
When I type in $usergroups = $groupRepo-> then the option for getUserGroupTitlePairs(s) is not shown. I suspect this is because I didn't put a comment to look for it in the repository in PhpStorm.
 
Smack me in the face! I was making it way too complicated.

PHP:
function xenwordGetUGIds() {

    if ( class_exists( '\XF' ) ) {

       /** @var \XF\Repository\UserGroup $groupRepo */
       $groupRepo = \XF::app()->repository('XF:UserGroup');
       $usergroups = $groupRepo->getUserGroupTitlePairs();

       return $usergroups;
    }
}

Updated with the comment for PhpStorm to find getUserGroupTitlePairs().
 
Last edited:
Back
Top Bottom