Limit User Group Join Count

I don't my user to join more than 5 groups. I wrote a custom plugin and here's my start.php file.. I am not sure why its not getting executed.

<?php
elgg_register_event_handler('init', 'system', 'improvement_init');

function improvement_init() {
// Exeture this before joining a group
elgg_register_event_handler('update', 'group', 'chk_group_count');
}

function chk_group_count($hook, $type, $result, $params){
// Admin does not have any limit
if(elgg_is_admin_logged_in()){
    system_message("Checking group count deactivated for admins.");
    return true;
}
    $owner = elgg_get_logged_in_user_entity();
    $usergroups_count = elgg_get_entities_from_relationship_count(array('relationship'=> 'member', 'relationship_guid'=> $owner->guid, 'inverse_relationship'=> FALSE, 'type'=> 'group'));
    system_message(elgg_echo("You can join " . (5 - $usergroups_count) . " more groups."));
        if($usergroups_count > 5){
            register_error("You cannot join more that 5 groups!");
            return false;
        }
    return true;
}
?>

Thanks in advance!

  • Listen to create,relationship or join, group event and return false to prevent relationship from being created.

  • This is my updated code. I used elgg_register_event_handler with priority 1, but the user is joining the group first and then my custom plugin is getting executed.

    <?php
    elgg_register_event_handler('init', 'system', 'improvement_init');
    
    function improvement_init() {
      elgg_register_event_handler('join', 'group', 'chk_group_count',1);
    }
    
    function chk_group_count($hook, $type, $result, $params){
    $owner = elgg_get_logged_in_user_entity();
    if(elgg_is_admin_logged_in()){
        system_message(elgg_echo("Checking group count deactivated for admins."));
        $return = true;
    }else{
        $usergroups_count = elgg_get_entities_from_relationship_count(array('relationship'=> 'member', 'relationship_guid'=> $owner->guid, 'inverse_relationship'=> FALSE, 'type'=> 'group'));
        $count = count($usergroups_count);
            if($usergroups_count > 5){
                register_error(elgg_echo("You cannot join more that 5 groups!"));
                $return = false;
            } else {
                $return = true;
            }
    }
        return $return;
    }
    
    ?>

     

     

  • Try create, relationship event and sniff the relationship name.

  • Awesome, create, relationship event did the trick.!!!