October CMS resources and help articles

Simple and to the point. Optimized by the community.

Define permissions for columns and fields in the backend

16
by Samuell, last modified on May 20th, 2020

This feature is available in Core starting from Build 460: https://github.com/octobercms/october/pull/4520

Create a trait that extends the controller and form fields.

traits/ColumnFieldPermissions.php

trait ColumnFieldPermissions
{
    public function formExtendFields($form, $fields)
    {
        foreach ($fields as $name => $field) {
            $permissionValue = array_get($field->config, 'permission');
            if ($permissionValue && !$this->user->hasAccess($permissionValue)) {
                if (array_get($field->config, 'permissionReadOnly')) {
                    $field->readOnly = true;
                    $field->disabled = true;
                } else {
                    $form->removeField($name);
                }
            }
        }
    }

    public function listExtendColumns($list)
    {
        foreach ($list->columns as $name => $column) {
            $permissionValue = array_get($column, 'permission');
            if ($permissionValue && !$this->user->hasAccess($permissionValue)) {
                $list->removeColumn($name);
            }
        }
    }
}

Example of usage

use Samuell\Plugin\Traits\ColumnFieldPermissions;

class YourController extends Controller
{
    use ColumnFieldPermissions;

    ....
}

Then we can use it in columns or fields like

name:
    permission: my.custom.permission

Discussion

5 comments

1
Rike-cz
Post on March 1st, 2019 9:26 PM

This trick calls for core integration! Really good idea.

0
Samuell
Post on August 10th, 2019 8:07 AM
1
adam
Post on March 20th, 2019 7:18 PM

Does not work with relationship manager, the columns are all displayed.

0
Samuell
Post on May 21st, 2019 9:06 AM

Yeah it wasnt created with relations in mind. Maybe we can somehow extend it to relation manager

0
larryb
Post on April 26th, 2019 7:34 PM

It would be nice to implement some sort of role check here, especially for isSuperUser() in the Backend. I frequently need to hide fields for users who are not super users.

Also, how can we make this handle multiple permissions, and if roles are implemented, multiple of those as well?

We use cookies to measure the performance of this website. Do you want to accept these cookies?