Search code examples
phpsilverstripesilverstripe-4

Silverstripe 4 - exclude specific group from view


Hi i'm trying to exclude some groups from view buttons in navigation. I see option in Pages->Page->Settings to show element for specific group but i want add exclude group option. Did anyone know how to do it?

I tried to create it by extend SiteTree class by adding SiteTreeExtension class. My class extends DataExtension and have 1 variable and 1 method.

private static $db = [
        'ExcludedRoles' => 'Varchar(255)'
    ];
public function updateSettingsFields($fields)
    {
        $groups = Group::get()->map('ID', 'Title');
        $fields->addFieldToTab('Root.Settings', new ListboxField('ExcludedRoles', 'Exclude page for specific groups', $groups, '', 4, true));
        }
    }

But its not saving data to the SiteTree.ExcludedRoles table. Im not sure that its all but if im doing something wrong can you help me please?


Solution

  • Instead of a db field, you should use a many_many relationship to the Group class. That way you will be able to correctly store the relation, and query it, which is what you'll need to do to check whether the current user is in any of the excluded groups.

    You should probably also reconsider the name of the relation - ExcludedRoles suggests that you're excluding PermissionRoles rather than groups.

    As for adding the ListBoxField itself, you're passing in an empty string for the value which tells it you never have a value. I can't remember whether you should pass in the relation, but try that - and if that doesn't work, then just don't pass anything (or pass null if you must pass something). Finally, unless you're intentionally passing in a size and know what that will do, just don't pass in a size.

    $fields->addFieldToTab('Root.Settings', ListboxField::create(
        'ExcludedGroups',
        'Exclude page for specific groups',
        $groups,
        $this->owner->ExcludedGroups()
    ));