Automatically add users to the same group as their group admin I am using the Organic group module. I created 2 groups on my site. To each group I assigned 1 user as group admin. Group admins have the permission to create users.

My question is how to automatically assign the users which got created by a group admin to the group admin's group?
In Drupal 7, you can achieve it using hook_user_insert and OG function og_group.


hook_user_insert : Called when a user account is created
og_group : Set an association (e.g. subscribe) an entity to a group


 /**
     * Implemention hook_user_insert
     * @global type $user
     * @param type $edit
     * @param type $account
     * @param type $category
     */
    function HOOK_user_insert(&$edit, $account, $category) {
        global $user;
        $usr_grps = og_get_entity_groups(); //get all user groups
        if (count($usr_grps) > 0) {//if any groups
            $grp_mgr_grps = array();
            foreach ($usr_grps['node'] as $key => $gid) {
                $group_type = 'node';
                $group = entity_load_single($group_type, $gid);
                if (is_object($group)) {
                    if (!empty($group->uid) && ($group->uid == $user->uid)) {//subscribe only the groups where the user is group manager
                        $grp_mgr_grps[] = $gid;
                    }
                }
            }
            if (count($grp_mgr_grps) > 0 && is_object($account)) {
                HOOK_subscribe_grpmgr_groups($grp_mgr_grps, $account); //subscribe the group
            }
        }
    }

    /**
     * 
     * @param type $grp_mgr_grps : array of group ids
     * @param type $account : Object of the user we want to add to the group
     */
    function HOOK_subscribe_grpmgr_groups($grp_mgr_grps, $account) {
        foreach ($grp_mgr_grps as $key => $gid) {
            $group_type = 'node'; //All groups are of type node
            $values = array(
                    'entity_type' => 'user',
                    'entity' => $account->uid,
                    'field_name' => FALSE,
                    'state' => 1,
            );
            og_group($group_type, $gid, $values);
        }
    }