class FilterFormatFormBase

Same name in other branches
  1. 9 core/modules/filter/src/FilterFormatFormBase.php \Drupal\filter\FilterFormatFormBase
  2. 8.9.x core/modules/filter/src/FilterFormatFormBase.php \Drupal\filter\FilterFormatFormBase
  3. 11.x core/modules/filter/src/FilterFormatFormBase.php \Drupal\filter\FilterFormatFormBase

Provides a base form for a filter format.

Hierarchy

Expanded class hierarchy of FilterFormatFormBase

File

core/modules/filter/src/FilterFormatFormBase.php, line 15

Namespace

Drupal\filter
View source
abstract class FilterFormatFormBase extends EntityForm {
    
    /**
     * {@inheritdoc}
     */
    public function form(array $form, FormStateInterface $form_state) {
        $format = $this->entity;
        $is_fallback = $format->id() == $this->config('filter.settings')
            ->get('fallback_format');
        $form['#tree'] = TRUE;
        $form['#attached']['library'][] = 'filter/drupal.filter.admin';
        $form['name'] = [
            '#type' => 'textfield',
            '#title' => $this->t('Name'),
            '#default_value' => $format->label(),
            '#required' => TRUE,
            '#weight' => -30,
        ];
        $form['format'] = [
            '#type' => 'machine_name',
            '#required' => TRUE,
            '#default_value' => $format->id(),
            '#maxlength' => 255,
            '#machine_name' => [
                'exists' => [
                    $this,
                    'exists',
                ],
                'source' => [
                    'name',
                ],
            ],
            '#disabled' => !$format->isNew(),
            '#weight' => -20,
        ];
        // Add user role access selection.
        $form['roles'] = [
            '#type' => 'checkboxes',
            '#title' => $this->t('Roles'),
            '#options' => array_map(fn(RoleInterface $role) => Html::escape($role->label()), Role::loadMultiple()),
            '#disabled' => $is_fallback,
            '#weight' => -10,
        ];
        if ($is_fallback) {
            $form['roles']['#description'] = $this->t('All roles for this text format must be enabled and cannot be changed.');
        }
        if (!$format->isNew()) {
            // If editing an existing text format, pre-select its current permissions.
            $form['roles']['#default_value'] = array_keys(filter_get_roles_by_format($format));
        }
        // Create filter plugin instances for all available filters, including both
        // enabled/configured ones as well as new and not yet configured ones.
        $filters = $format->filters();
        foreach ($filters as $filter_id => $filter) {
            // When a filter is missing, it is replaced by the null filter. Remove it
            // here, so that saving the form will remove the missing filter.
            if ($filter instanceof FilterNull) {
                $this->messenger()
                    ->addWarning($this->t('The %filter filter is missing, and will be removed once this format is saved.', [
                    '%filter' => $filter_id,
                ]));
                $filters->removeInstanceID($filter_id);
            }
        }
        // Filter status.
        $form['filters']['status'] = [
            '#type' => 'item',
            '#title' => $this->t('Enabled filters'),
            '#prefix' => '<div id="filters-status-wrapper">',
            '#suffix' => '</div>',
            // This item is used as a pure wrapping container with heading. Ignore its
            // value, since 'filters' should only contain filter definitions.
            // See https://www.drupal.org/node/1829202.
'#input' => FALSE,
        ];
        // Filter order (tabledrag).
        $form['filters']['order'] = [
            '#type' => 'table',
            // For filter.admin.js
'#attributes' => [
                'id' => 'filter-order',
            ],
            '#title' => $this->t('Filter processing order'),
            '#tabledrag' => [
                [
                    'action' => 'order',
                    'relationship' => 'sibling',
                    'group' => 'filter-order-weight',
                ],
            ],
            '#tree' => FALSE,
            '#input' => FALSE,
            '#theme_wrappers' => [
                'form_element',
            ],
        ];
        // Filter settings.
        $form['filter_settings'] = [
            '#type' => 'vertical_tabs',
            '#title' => $this->t('Filter settings'),
        ];
        foreach ($filters as $name => $filter) {
            $form['filters']['status'][$name] = [
                '#type' => 'checkbox',
                '#title' => $filter->getLabel(),
                '#default_value' => $filter->status,
                '#parents' => [
                    'filters',
                    $name,
                    'status',
                ],
                '#description' => $filter->getDescription(),
                '#weight' => $filter->weight,
            ];
            $form['filters']['order'][$name]['#attributes']['class'][] = 'draggable';
            $form['filters']['order'][$name]['#weight'] = $filter->weight;
            $form['filters']['order'][$name]['filter'] = [
                '#markup' => $filter->getLabel(),
            ];
            $form['filters']['order'][$name]['weight'] = [
                '#type' => 'weight',
                '#title' => $this->t('Weight for @title', [
                    '@title' => $filter->getLabel(),
                ]),
                '#title_display' => 'invisible',
                '#delta' => 50,
                '#default_value' => $filter->weight,
                '#parents' => [
                    'filters',
                    $name,
                    'weight',
                ],
                '#attributes' => [
                    'class' => [
                        'filter-order-weight',
                    ],
                ],
            ];
            // Ensure the resulting FilterFormat complies with `type: filter`.
            // @see core.data_types.schema.yml
            // @see \Drupal\filter\FilterFormatFormBase::submitForm()
            $form['filters']['order'][$name]['id'] = [
                '#type' => 'value',
                '#value' => $filter->getPluginId(),
                '#parents' => [
                    'filters',
                    $name,
                    'id',
                ],
            ];
            $form['filters']['order'][$name]['provider'] = [
                '#type' => 'value',
                '#value' => $filter->provider,
                '#parents' => [
                    'filters',
                    $name,
                    'provider',
                ],
            ];
            // Retrieve the settings form of the filter plugin. The plugin should not be
            // aware of the text format. Therefore, it only receives a set of minimal
            // base properties to allow advanced implementations to work.
            $settings_form = [
                '#parents' => [
                    'filters',
                    $name,
                    'settings',
                ],
                '#tree' => TRUE,
            ];
            $settings_form = $filter->settingsForm($settings_form, $form_state);
            if (!empty($settings_form)) {
                $form['filters']['settings'][$name] = [
                    '#type' => 'details',
                    '#title' => $filter->getLabel(),
                    '#open' => TRUE,
                    '#weight' => $filter->weight,
                    '#parents' => [
                        'filters',
                        $name,
                        'settings',
                    ],
                    '#group' => 'filter_settings',
                ];
                $form['filters']['settings'][$name] += $settings_form;
            }
        }
        return parent::form($form, $form_state);
    }
    
    /**
     * Determines if the format already exists.
     *
     * @param string $format_id
     *   The format ID
     *
     * @return bool
     *   TRUE if the format exists, FALSE otherwise.
     */
    public function exists($format_id) {
        return (bool) $this->entityTypeManager
            ->getStorage('filter_format')
            ->getQuery()
            ->condition('format', $format_id)
            ->execute();
    }
    
    /**
     * {@inheritdoc}
     */
    public function validateForm(array &$form, FormStateInterface $form_state) {
        parent::validateForm($form, $form_state);
        // @todo Move trimming upstream.
        $format_format = trim($form_state->getValue('format'));
        $format_name = trim($form_state->getValue('name'));
        // Ensure that the values to be saved later are exactly the ones validated.
        $form_state->setValueForElement($form['format'], $format_format);
        $form_state->setValueForElement($form['name'], $format_name);
        $format_exists = $this->entityTypeManager
            ->getStorage('filter_format')
            ->getQuery()
            ->condition('format', $format_format, '<>')
            ->condition('name', $format_name)
            ->execute();
        if ($format_exists) {
            $form_state->setErrorByName('name', $this->t('Text format names must be unique. A format named %name already exists.', [
                '%name' => $format_name,
            ]));
        }
    }
    
    /**
     * {@inheritdoc}
     */
    public function submitForm(array &$form, FormStateInterface $form_state) {
        parent::submitForm($form, $form_state);
        // Add the submitted form values to the text format, and save it.
        $format = $this->entity;
        foreach ($form_state->getValues() as $key => $value) {
            if ($key != 'filters') {
                $format->set($key, $value);
            }
            else {
                foreach ($value as $instance_id => $config) {
                    $format->setFilterConfig($instance_id, $config);
                }
            }
        }
        $format->save();
        // Save user permissions.
        if ($permission = $format->getPermissionName()) {
            foreach ($form_state->getValue('roles') as $rid => $enabled) {
                user_role_change_permissions($rid, [
                    $permission => $enabled,
                ]);
            }
        }
        return $this->entity;
    }
    
    /**
     * {@inheritdoc}
     */
    protected function actions(array $form, FormStateInterface $form_state) {
        $actions = parent::actions($form, $form_state);
        $actions['submit']['#value'] = $this->t('Save configuration');
        return $actions;
    }

}

Members

Title Sort descending Modifiers Object type Summary Overriden Title Overrides
DependencySerializationTrait::$_entityStorages protected property
DependencySerializationTrait::$_serviceIds protected property
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
EntityForm::$entity protected property The entity being used by this form. 11
EntityForm::$entityTypeManager protected property The entity type manager. 3
EntityForm::$moduleHandler protected property The module handler service. 2
EntityForm::$operation protected property The name of the current operation.
EntityForm::actionsElement protected function Returns the action form element for the current entity form.
EntityForm::afterBuild public function Form element #after_build callback: Updates the entity with submitted data. 1
EntityForm::buildEntity public function Builds an updated entity object based upon the submitted form values. Overrides EntityFormInterface::buildEntity 5
EntityForm::buildForm public function Form constructor. Overrides FormInterface::buildForm 13
EntityForm::copyFormValuesToEntity protected function Copies top-level form values to entity properties. 11
EntityForm::getBaseFormId public function Returns a string identifying the base form. Overrides BaseFormIdInterface::getBaseFormId 4
EntityForm::getEntity public function Gets the form entity. Overrides EntityFormInterface::getEntity
EntityForm::getEntityFromRouteMatch public function Determines which entity will be used by this form from a RouteMatch object. Overrides EntityFormInterface::getEntityFromRouteMatch 3
EntityForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId 13
EntityForm::getOperation public function Gets the operation identifying the form. Overrides EntityFormInterface::getOperation
EntityForm::init protected function Initialize the form state and the entity before the first form build. 3
EntityForm::prepareEntity protected function Prepares the entity object before the form is built first. 3
EntityForm::prepareInvokeAll protected function Invokes the specified prepare hook variant.
EntityForm::processForm public function Process callback: assigns weights and hides extra fields.
EntityForm::save public function Form submission handler for the &#039;save&#039; action. Overrides EntityFormInterface::save 47
EntityForm::setEntity public function Sets the form entity. Overrides EntityFormInterface::setEntity
EntityForm::setEntityTypeManager public function Sets the entity type manager for this form. Overrides EntityFormInterface::setEntityTypeManager
EntityForm::setModuleHandler public function Sets the module handler for this form. Overrides EntityFormInterface::setModuleHandler
EntityForm::setOperation public function Sets the operation for this form. Overrides EntityFormInterface::setOperation
FilterFormatFormBase::actions protected function Returns an array of supported actions for the current entity form. Overrides EntityForm::actions
FilterFormatFormBase::exists public function Determines if the format already exists.
FilterFormatFormBase::form public function Gets the actual form array to be built. Overrides EntityForm::form 2
FilterFormatFormBase::submitForm public function This is the default entity object builder function. It is called before any
other submit handler to build the new entity object to be used by the
following submit handlers. At this point of the form workflow the entity is
validated and the form state…
Overrides EntityForm::submitForm 2
FilterFormatFormBase::validateForm public function Form validation handler. Overrides FormBase::validateForm
FormBase::$configFactory protected property The config factory. 3
FormBase::$requestStack protected property The request stack. 1
FormBase::$routeMatch protected property The route match.
FormBase::config protected function Retrieves a configuration object.
FormBase::configFactory protected function Gets the config factory for this form. 3
FormBase::container private function Returns the service container.
FormBase::create public static function Instantiates a new instance of this class. Overrides ContainerInjectionInterface::create 111
FormBase::currentUser protected function Gets the current user. 2
FormBase::getRequest protected function Gets the request object.
FormBase::getRouteMatch protected function Gets the route match.
FormBase::logger protected function Gets the logger for a specific channel.
FormBase::redirect protected function Returns a redirect response object for the specified route.
FormBase::resetConfigFactory public function Resets the configuration factory.
FormBase::setConfigFactory public function Sets the config factory for this form.
FormBase::setRequestStack public function Sets the request stack object to use.
LoggerChannelTrait::$loggerFactory protected property The logger channel factory service.
LoggerChannelTrait::getLogger protected function Gets the logger for a specific channel.
LoggerChannelTrait::setLoggerFactory public function Injects the logger channel factory.
MessengerTrait::$messenger protected property The messenger. 16
MessengerTrait::messenger public function Gets the messenger. 16
MessengerTrait::setMessenger public function Sets the messenger.
RedirectDestinationTrait::$redirectDestination protected property The redirect destination service. 2
RedirectDestinationTrait::getDestinationArray protected function Prepares a &#039;destination&#039; URL query parameter for use with \Drupal\Core\Url.
RedirectDestinationTrait::getRedirectDestination protected function Returns the redirect destination service.
RedirectDestinationTrait::setRedirectDestination public function Sets the redirect destination service.
StringTranslationTrait::$stringTranslation protected property The string translation service. 3
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.