Programmatically setting block permissions

Hello everyone!

I am working on a package containing a helper to automate a few setup tasks, like creating user groups, setting permissions etc.

Currently, I am struggling with the block permissions. Ideally, I would want to allow certain user groups to add a certain selection of blocks.

This is the code I tried:

        $groups = [...];
        $blockTypeIds = [...];

        $pk = Key::getByHandle('add_block');
        $pa = AddBlockBlockTypeAccess::create($pk);

        foreach ($groups as $group) {
            if (!$group) {
                continue;
            }
            $groupEntity = GroupEntity::getOrCreate($group);

            $pa->addListItem($groupEntity);
        }

        foreach ($pa->getAccessListItems() as $item) {
            /** @var AddBlockBlockTypeListItem $item */
            $item->setBlockTypesAllowedPermission('C');
            $item->setBlockTypesAllowedArray($blockTypeIds);
        }

        $pa->save();

        $pt = $pk->getPermissionAssignmentObject();
        $pt->assignPermissionAccess($pa);

This adds the permissions for my user groups, though they allow each group to access ALL the blocks instead of the specified ones.

This looks like this under /dashboard/blocks/permissions:

What I’m really looking for is this:

I am not sure why $item→setBlockTypesAllowedArray() has no effect.

Any help on this problem would me much appreciated!

I can’t help you with the coding but have a look at this post. There’s a whole other area of the Dashboard that might hold some clues for the way forward.

Thank you for your input.

After digging in the core files for a bit, I found a way that works. Here’s my solution:

        $groups = [...];
        $blockTypeIds = [...];

        $pk = Key::getByHandle('add_block');
        $pa = AddBlockBlockTypeAccess::create($pk);

        $pt = $pk->getPermissionAssignmentObject();
        $pt->assignPermissionAccess($pa);

        $blockTypesIncluded = [];
        $btIDInclude = [];
        foreach ($groups as $group) {
            if (!$group) {
                continue;
            }
            $groupEntity = GroupEntity::getOrCreate($group);

            $pa->addListItem($groupEntity);

            $blockTypesIncluded[] = 'C';
            $btIDInclude[] = $blockTypeIds;
        }
        
        $pa->save([
            'blockTypesIncluded' => $blockTypesIncluded,
            'btIDInclude' => $btIDInclude,
        ]);
1 Like