Custom Readonly transformation to remove actions which shouldn't be present for a readonly state.

@return GridField
185508
public function performReadonlyTransformation()
    {
        $copy = clone $this;
        $copy->setReadonly(true);
        $copyConfig = $copy->getConfig();

        // get the whitelist for allowable readonly components
        $allowedComponents = $this->getReadonlyComponents();
        foreach ($this->getConfig()->getComponents() as $component) {
            // if a component doesn't exist, remove it from the readonly version.
            if (!in_array(get_class($component), $allowedComponents)) {
                $copyConfig->removeComponent($component);
            }
        }

        // As the edit button may have been removed, add a view button if it doesn't have one
        if (!$copyConfig->getComponentByType(GridFieldViewButton::class)) {
            $copyConfig->addComponent(new GridFieldViewButton);
        }

        return $copy;
    }
1075783
public function clear()
    {
        parent::clear();

        $this->with = [];
        $this->primaryCriteria = null;
        $this->formatter = null;
        $this->select = null;

        return $this;
    }
79818
public function clearValues()
    {
        foreach ($this->fields as $name => $field) {
            $field->setValue(null);
        }

        return $this;
    }
291510
public function pushBack(){
		
		if($this->_ReadOnly){
			throw new ReadOnlyException(\get_called_class() . ' is read only');
		}
		
		$this->_Arr = \array_merge($this->_Arr, \func_get_args());
		
		return $this;
		
	}
708796
public function getCMSFields()
    {
        $fields = new FieldList(
            new TabSet(
                "Root",
                new Tab(
                    'Members',
                    _t(__CLASS__ . '.MEMBERS', 'Members'),
                    new TextField("Title", $this->fieldLabel('Title')),
                    $parentidfield = DropdownField::create(
                        'ParentID',
                        $this->fieldLabel('Parent'),
                        Group::get()->exclude('ID', $this->ID)->map('ID', 'Breadcrumbs')
                    )->setEmptyString(' '),
                    new TextareaField('Description', $this->fieldLabel('Description'))
                ),
                $permissionsTab = new Tab(
                    'Permissions',
                    _t(__CLASS__ . '.PERMISSIONS', 'Permissions'),
                    $permissionsField = new PermissionCheckboxSetField(
                        'Permissions',
                        false,
                        Permission::class,
                        'GroupID',
                        $this
                    )
                )
            )
        );

        $parentidfield->setDescription(
            _t('SilverStripe\\Security\\Group.GroupReminder', 'If you choose a parent group, this group will take all it\'s roles')
        );

        if ($this->ID) {
            $group = $this;
            $config = GridFieldConfig_RelationEditor::create();
            $config->addComponent(new GridFieldButtonRow('after'));
            $config->addComponents(new GridFieldExportButton('buttons-after-left'));
            $config->addComponents(new GridFieldPrintButton('buttons-after-left'));
            $config->removeComponentsByType(GridFieldDeleteAction::class);
            $config->addComponent(new GridFieldGroupDeleteAction($this->ID), GridFieldPageCount::class);

            /** @var GridFieldAddExistingAutocompleter $autocompleter */
            $autocompleter = $config->getComponentByType(GridFieldAddExistingAutocompleter::class);
            /** @skipUpgrade */
            $autocompleter
                ->setResultsFormat('$Title ($Email)')
                ->setSearchFields(array('FirstName', 'Surname', 'Email'));
            /** @var GridFieldDetailForm $detailForm */
            $detailForm = $config->getComponentByType(GridFieldDetailForm::class);
            $detailForm
                ->setValidator(Member_Validator::create())
                ->setItemEditFormCallback(function ($form) use ($group) {
                    /** @var Form $form */
                    $record = $form->getRecord();
                    $groupsField = $form->Fields()->dataFieldByName('DirectGroups');
                    if ($groupsField) {
                        // If new records are created in a group context,
                        // set this group by default.
                        if ($record && !$record->ID) {
                            $groupsField->setValue($group->ID);
                        } elseif ($record && $record->ID) {
                            // TODO Mark disabled once chosen.js supports it
                            // $groupsField->setDisabledItems(array($group->ID));
                            $form->Fields()->replaceField(
                                'DirectGroups',
                                $groupsField->performReadonlyTransformation()
                            );
                        }
                    }
                });
            $memberList = GridField::create('Members', false, $this->DirectMembers(), $config)
                ->addExtraClass('members_grid');
            // @todo Implement permission checking on GridField
            //$memberList->setPermissions(array('edit', 'delete', 'export', 'add', 'inlineadd'));
            $fields->addFieldToTab('Root.Members', $memberList);
        }

        // Only add a dropdown for HTML editor configurations if more than one is available.
        // Otherwise Member->getHtmlEditorConfigForCMS() will default to the 'cms' configuration.
        $editorConfigMap = HTMLEditorConfig::get_available_configs_map();
        if (count($editorConfigMap) > 1) {
            $fields->addFieldToTab(
                'Root.Permissions',
                new DropdownField(
                    'HtmlEditorConfig',
                    'HTML Editor Configuration',
                    $editorConfigMap
                ),
                'Permissions'
            );
        }

        if (!Permission::check('EDIT_PERMISSIONS')) {
            $fields->removeFieldFromTab('Root', 'Permissions');
        }

        // Only show the "Roles" tab if permissions are granted to edit them,
        // and at least one role exists
        if (Permission::check('APPLY_ROLES') &&
            PermissionRole::get()->count() &&
            class_exists(SecurityAdmin::class)
        ) {
            $fields->findOrMakeTab('Root.Roles', _t(__CLASS__ . '.ROLES', 'Roles'));
            $fields->addFieldToTab(
                'Root.Roles',
                new LiteralField(
                    "",
                    "<p>" .
                    _t(
                        __CLASS__ . '.ROLESDESCRIPTION',
                        "Roles are predefined sets of permissions, and can be assigned to groups.<br />"
                        . "They are inherited from parent groups if required."
                    ) . '<br />' .
                    sprintf(
                        '<a href="%s" class="add-role">%s</a>',
                        SecurityAdmin::singleton()->Link('show/root#Root_Roles'),
                        // TODO This should include #Root_Roles to switch directly to the tab,
                        // but tabstrip.js doesn't display tabs when directly adressed through a URL pragma
                        _t('SilverStripe\\Security\\Group.RolesAddEditLink', 'Manage roles')
                    ) .
                    "</p>"
                )
            );

            // Add roles (and disable all checkboxes for inherited roles)
            $allRoles = PermissionRole::get();
            if (!Permission::check('ADMIN')) {
                $allRoles = $allRoles->filter("OnlyAdminCanApply", 0);
            }
            if ($this->ID) {
                $groupRoles = $this->Roles();
                $inheritedRoles = new ArrayList();
                $ancestors = $this->getAncestors();
                foreach ($ancestors as $ancestor) {
                    $ancestorRoles = $ancestor->Roles();
                    if ($ancestorRoles) {
                        $inheritedRoles->merge($ancestorRoles);
                    }
                }
                $groupRoleIDs = $groupRoles->column('ID') + $inheritedRoles->column('ID');
                $inheritedRoleIDs = $inheritedRoles->column('ID');
            } else {
                $groupRoleIDs = array();
                $inheritedRoleIDs = array();
            }

            $rolesField = ListboxField::create('Roles', false, $allRoles->map()->toArray())
                    ->setDefaultItems($groupRoleIDs)
                    ->setAttribute('data-placeholder', _t('SilverStripe\\Security\\Group.AddRole', 'Add a role for this group'))
                    ->setDisabledItems($inheritedRoleIDs);
            if (!$allRoles->count()) {
                $rolesField->setAttribute('data-placeholder', _t('SilverStripe\\Security\\Group.NoRoles', 'No roles found'));
            }
            $fields->addFieldToTab('Root.Roles', $rolesField);
        }

        $fields->push($idField = new HiddenField("ID"));

        $this->extend('updateCMSFields', $fields);

        return $fields;
    }
1370509
protected function getGridPagerState(GridField $gridField)
    {
        $state = $gridField->State->GridFieldPaginator;

        // Force the state to the initial page if none is set
        $state->currentPage(1);
        $state->itemsPerPage($this->getItemsPerPage());

        return $state;
    }
1198337
public function actionDeleteRole ()
		{

			$auth = Yii::$app->getAuthManager();
			$role = $auth->getRole(Yii::$app->request->get('id'));
			$auth->remove($role);
			$url = Yii::$app->request->referrer . '#roles';
			Yii::$app->response->redirect($url);

			Yii::$app->end();
		}
621862
protected function removeReservedFields()
    {
        if (!$this->isMode(static::MODE_CREATE)) {
            return;
        }

        $reservedColumns = [
            $this->form->model()->getKeyName(),
            $this->form->model()->getCreatedAtColumn(),
            $this->form->model()->getUpdatedAtColumn(),
        ];

        $this->fields = $this->fields()->reject(function (Field $field) use ($reservedColumns) {
            return in_array($field->column(), $reservedColumns, true);
        });
    }
409195
public function reset()
    {
        $fields = $this->getFields();
        foreach ($fields as $field) {
            $field->resetValue();
        }
        return $this;
    }
915926
public function unbindAllModels() {
        foreach ($this->getBindings() as $alias => $binding) {
            $this->unbindModel($alias);
        }
        return $this;
    }
1342705
protected function getGridPagerState(GridField $gridField = null)
    {
        if (!$this->gridFieldState) {
            $state = $this->getGridField()->State->GridFieldConfigurablePaginator;

            // SS 3.1 compatibility (missing __call)
            if (is_object($state->firstShown)) {
                $state->firstShown = 1;
            }
            if (is_object($state->pageSize)) {
                $state->pageSize = $this->getItemsPerPage();
            }

            // Handle free input in the page number field
            $parentState = $this->getGridField()->State->GridFieldPaginator;
            if (is_object($parentState->currentPage)) {
                $parentState->currentPage = 0;
            }

            if ($parentState->currentPage >= 1) {
                $state->firstShown = ($parentState->currentPage - 1) * $this->getItemsPerPage() + 1;
                $parentState->currentPage = null;
            }

            $this->gridFieldState = $state;
        }

        return $this->gridFieldState;
    }
988432
public function transformReadonly(FieldList $fields)
    {
        foreach ($fields->dataFields() as $field) {
            if ($field instanceof HiddenField) {
                continue;
            }
            $newField = $field->castedCopy(HTMLReadonlyField::class);
            $fields->replaceField($field->getName(), $newField);
        }
        return $fields;
    }
757846
public function removesessionAction()
    {
        $success = false;
        $request = $this->getEvent()->getRequest();
        if ($request instanceof Request && $request->isPost()) {
            $containerName = $request->getPost('containerName', 'Default');
            $keysession = $request->getPost('keysession', '');

            $success = $this->sessionManager
                            ->sessionSetting($containerName, $keysession);
        }

        return new JsonModel([
            'success' => $success,
        ]);
    }
963714
def derive_readonly(self):
        
        readonly = list(self.readonly)
        for key, value in self.field_config.items():
            if 'readonly' in value and value['readonly']:
                readonly.append(key)

        return readonly
337305
public function deactivateTcaFrontendGroupEnableFields(
        /** @noinspection PhpUnusedParameterInspection */
        &$parameters,
        /** @noinspection PhpUnusedParameterInspection */
        $parentObject
    ) {
        $this->originalTca = $GLOBALS['TCA'];

        foreach ($GLOBALS['TCA'] as $tableName => $tableConfiguration) {
            if (isset($GLOBALS['TCA'][$tableName]['ctrl']['enablecolumns']['fe_group'])) {
                unset($GLOBALS['TCA'][$tableName]['ctrl']['enablecolumns']['fe_group']);
            }
        }
    }
538823
protected function grid()
    {
        $permissionModel = config('admin.database.permissions_model');

        $grid = new Grid(new $permissionModel());

        $grid->id('ID')->sortable();
        $grid->slug(trans('admin.slug'));
        $grid->name(trans('admin.name'));

        $grid->http_path(trans('admin.route'))->display(function ($path) {
            return collect(explode("\n", $path))->map(function ($path) {
                $method = $this->http_method ?: ['ANY'];

                if (Str::contains($path, ':')) {
                    list($method, $path) = explode(':', $path);
                    $method = explode(',', $method);
                }

                $method = collect($method)->map(function ($name) {
                    return strtoupper($name);
                })->map(function ($name) {
                    return "<span class='label label-primary'>{$name}</span>";
                })->implode('&nbsp;');

                if (!empty(config('admin.route.prefix'))) {
                    $path = '/'.trim(config('admin.route.prefix'), '/').$path;
                }

                return "<div style='margin-bottom: 5px;'>$method<code>$path</code></div>";
            })->implode('');
        });

        $grid->created_at(trans('admin.created_at'));
        $grid->updated_at(trans('admin.updated_at'));

        $grid->tools(function (Grid\Tools $tools) {
            $tools->batch(function (Grid\Tools\BatchActions $actions) {
                $actions->disableDelete();
            });
        });

        return $grid;
    }
1217391
public function getCMSFields()
    {
        
        $this->beforeUpdateCMSFields(function ($fields) {
            $config = SiteConfig::current_site_config();

            $fields->removeByName("Customisation");

            $fields->addFieldToTab(
                "Root.Main",
                ReadonlyField::create("Key"),
                "Title"
            );

            $fields->addFieldToTab(
                "Root.Main",
                DropdownField::create(
                    "TaxID",
                    $this->fieldLabel("TaxID"),
                    $config->TaxRates()->map()
                ),
                "Weight"
            );

            $fields->addFieldsToTab(
                "Root.Description",
                [
                    HTMLEditorField::create("Content")
                        ->addExtraClass("stacked")
                ]
            );

            // Change unlink button to remove on customisation
            $custom_field = $fields->dataFieldByName("Customisations");

            if ($custom_field) {
                $config = $custom_field->getConfig();
                $config
                    ->removeComponentsByType(GridFieldDeleteAction::class)
                    ->removeComponentsByType(GridFieldDataColumns::class)
                    ->removeComponentsByType(GridFieldEditButton::class)
                    ->removeComponentsByType(GridFieldAddNewButton::class)
                    ->removeComponentsByType(GridFieldAddExistingAutocompleter::class)
                    ->addComponents(
                        new GridFieldEditableColumns(),
                        new GridFieldAddNewInlineButton(),
                        new GridFieldEditButton(),
                        new GridFieldDeleteAction()
                    );
                
                    $custom_field->setConfig($config);
            }
        });

        return parent::getCMSFields();
    }