• This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn more.

XF 2.0 Optimal code for pulling UserGroups.

LPH

Well-known member
#1
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;
    }
}
 

Mike

XenForo developer
Staff member
#2
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()
 

LPH

Well-known member
#3
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.
 

Chris D

XenForo developer
Staff member
#4
It's just this:
PHP:
$groupRepo = \XF::app()->repository('XF:UserGroup');
$usergroups = $groupRepo->getUserGroupTitlePairs();
 

LPH

Well-known member
#5
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.
 

LPH

Well-known member
#6
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: