class BlockEntitySettingTrayForm

Same name in other branches
  1. 8.9.x core/modules/settings_tray/src/Block/BlockEntitySettingTrayForm.php \Drupal\settings_tray\Block\BlockEntitySettingTrayForm
  2. 10 core/modules/settings_tray/src/Block/BlockEntitySettingTrayForm.php \Drupal\settings_tray\Block\BlockEntitySettingTrayForm
  3. 11.x core/modules/settings_tray/src/Block/BlockEntitySettingTrayForm.php \Drupal\settings_tray\Block\BlockEntitySettingTrayForm

Provides form for block instance forms when used in the off-canvas dialog.

This form removes advanced sections of regular block form such as the visibility settings, machine ID and region.

@internal

Hierarchy

Expanded class hierarchy of BlockEntitySettingTrayForm

1 file declares its use of BlockEntitySettingTrayForm
settings_tray.module in core/modules/settings_tray/settings_tray.module
Allows configuring blocks and other configuration from the site front-end.

File

core/modules/settings_tray/src/Block/BlockEntitySettingTrayForm.php, line 24

Namespace

Drupal\settings_tray\Block
View source
class BlockEntitySettingTrayForm extends BlockForm {
    use AjaxFormHelperTrait;
    
    /**
     * Provides a title callback to get the block's admin label.
     *
     * @param \Drupal\block\BlockInterface $block
     *   The block entity.
     *
     * @return \Drupal\Core\StringTranslation\TranslatableMarkup
     *   The title.
     */
    public function title(BlockInterface $block) {
        // @todo Wrap "Configure " in <span class="visually-hidden"></span> once
        //   https://www.drupal.org/node/2359901 is fixed.
        return $this->t('Configure @block', [
            '@block' => $block->getPlugin()
                ->getPluginDefinition()['admin_label'],
        ]);
    }
    
    /**
     * {@inheritdoc}
     */
    public function form(array $form, FormStateInterface $form_state) {
        $form = parent::form($form, $form_state);
        // Create link to full block form.
        $query = [];
        if ($destination = $this->getRequest()->query
            ->get('destination')) {
            $query['destination'] = $destination;
        }
        $form['advanced_link'] = [
            '#type' => 'link',
            '#title' => $this->t('Advanced block options'),
            '#url' => $this->entity
                ->toUrl('edit-form', [
                'query' => $query,
            ]),
            '#weight' => 1000,
        ];
        // Remove the ID and region elements.
        unset($form['id'], $form['region'], $form['settings']['admin_label']);
        if (isset($form['settings']['label_display']) && isset($form['settings']['label'])) {
            // Only show the label input if the label will be shown on the page.
            $form['settings']['label_display']['#weight'] = -100;
            $form['settings']['label']['#states']['visible'] = [
                ':input[name="settings[label_display]"]' => [
                    'checked' => TRUE,
                ],
            ];
            // Relabel to "Block title" because on the front-end this may be confused
            // with page title.
            $form['settings']['label']['#title'] = $this->t("Block title");
            $form['settings']['label_display']['#title'] = $this->t("Display block title");
        }
        return $form;
    }
    
    /**
     * {@inheritdoc}
     */
    protected function actions(array $form, FormStateInterface $form_state) {
        $actions = parent::actions($form, $form_state);
        $actions['submit']['#value'] = $this->t('Save @block', [
            '@block' => $this->entity
                ->getPlugin()
                ->getPluginDefinition()['admin_label'],
        ]);
        $actions['delete']['#access'] = FALSE;
        return $actions;
    }
    
    /**
     * {@inheritdoc}
     */
    protected function buildVisibilityInterface(array $form, FormStateInterface $form_state) {
        // Do not display the visibility.
        return [];
    }
    
    /**
     * {@inheritdoc}
     */
    protected function validateVisibility(array $form, FormStateInterface $form_state) {
        // Intentionally empty.
    }
    
    /**
     * {@inheritdoc}
     */
    protected function submitVisibility(array $form, FormStateInterface $form_state) {
        // Intentionally empty.
    }
    
    /**
     * {@inheritdoc}
     */
    protected function getPluginForm(BlockPluginInterface $block) {
        if ($block instanceof PluginWithFormsInterface) {
            return $this->pluginFormFactory
                ->createInstance($block, 'settings_tray', 'configure');
        }
        return $block;
    }
    
    /**
     * {@inheritdoc}
     */
    public function buildForm(array $form, FormStateInterface $form_state) {
        $form = parent::buildForm($form, $form_state);
        $form['actions']['submit']['#ajax'] = [
            'callback' => '::ajaxSubmit',
        ];
        $form['#attached']['library'][] = 'core/drupal.dialog.ajax';
        // static::ajaxSubmit() requires data-drupal-selector to be the same between
        // the various Ajax requests. A bug in \Drupal\Core\Form\FormBuilder
        // prevents that from happening unless $form['#id'] is also the same.
        // Normally, #id is set to a unique HTML ID via Html::getUniqueId(), but
        // here we bypass that in order to work around the data-drupal-selector bug.
        // This is okay so long as we assume that this form only ever occurs once on
        // a page.
        // @todo Remove this workaround once https://www.drupal.org/node/2897377 is
        //   fixed.
        $form['#id'] = Html::getId($form_state->getBuildInfo()['form_id']);
        return $form;
    }
    
    /**
     * {@inheritdoc}
     */
    protected function successfulAjaxSubmit(array $form, FormStateInterface $form_state) {
        if ($redirect_url = $this->getRedirectUrl()) {
            $command = new RedirectCommand($redirect_url->setAbsolute()
                ->toString());
        }
        else {
            // Settings Tray always provides a destination.
            throw new \Exception("No destination provided by Settings Tray form");
        }
        $response = new AjaxResponse();
        return $response->addCommand($command);
    }
    
    /**
     * Gets the form's redirect URL from 'destination' provide in the request.
     *
     * @return \Drupal\Core\Url|null
     *   The redirect URL or NULL if dialog should just be closed.
     */
    protected function getRedirectUrl() {
        // \Drupal\Core\Routing\RedirectDestination::get() cannot be used directly
        // because it will use <current> if 'destination' is not in the query
        // string.
        if ($this->getRequest()->query
            ->has('destination') && ($destination = $this->getRedirectDestination()
            ->get())) {
            return Url::fromUserInput('/' . $destination);
        }
    }

}

Members

Title Sort descending Modifiers Object type Summary Overriden Title Overrides
AjaxFormHelperTrait::ajaxSubmit public function Submit form dialog #ajax callback.
AjaxHelperTrait::getRequestWrapperFormat protected function Gets the wrapper format of the current request.
AjaxHelperTrait::isAjax protected function Determines if the current request is via AJAX.
BlockEntitySettingTrayForm::actions protected function Returns an array of supported actions for the current entity form. Overrides BlockForm::actions
BlockEntitySettingTrayForm::buildForm public function Form constructor. Overrides EntityForm::buildForm
BlockEntitySettingTrayForm::buildVisibilityInterface protected function Helper function for building the visibility UI form. Overrides BlockForm::buildVisibilityInterface
BlockEntitySettingTrayForm::form public function Gets the actual form array to be built. Overrides BlockForm::form
BlockEntitySettingTrayForm::getPluginForm protected function Retrieves the plugin form for a given block and operation. Overrides BlockForm::getPluginForm
BlockEntitySettingTrayForm::getRedirectUrl protected function Gets the form&#039;s redirect URL from &#039;destination&#039; provide in the request.
BlockEntitySettingTrayForm::submitVisibility protected function Helper function to independently submit the visibility UI. Overrides BlockForm::submitVisibility
BlockEntitySettingTrayForm::successfulAjaxSubmit protected function Allows the form to respond to a successful AJAX submission. Overrides AjaxFormHelperTrait::successfulAjaxSubmit
BlockEntitySettingTrayForm::title public function Provides a title callback to get the block&#039;s admin label.
BlockEntitySettingTrayForm::validateVisibility protected function Helper function to independently validate the visibility UI. Overrides BlockForm::validateVisibility
BlockForm::$contextRepository protected property The context repository service.
BlockForm::$entity protected property The block entity. Overrides EntityForm::$entity
BlockForm::$language protected property The language manager service.
BlockForm::$manager protected property The condition plugin manager.
BlockForm::$pluginFormFactory protected property The plugin form manager.
BlockForm::$storage protected property The block storage.
BlockForm::$themeHandler protected property The theme handler.
BlockForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
BlockForm::getUniqueMachineName public function Generates a unique machine name for a block.
BlockForm::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
BlockForm::themeSwitch public function Handles switching the available regions based on the selected theme.
BlockForm::validateForm public function Form validation handler. Overrides FormBase::validateForm
BlockForm::__construct public function Constructs a BlockForm object.
DependencySerializationTrait::$_entityStorages protected property
DependencySerializationTrait::$_serviceIds protected property
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
EntityForm::$entityTypeManager protected property The entity type manager. 3
EntityForm::$moduleHandler protected property The module handler service.
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.
EntityForm::buildEntity public function Builds an updated entity object based upon the submitted form values. Overrides EntityFormInterface::buildEntity 3
EntityForm::copyFormValuesToEntity protected function Copies top-level form values to entity properties. 9
EntityForm::getBaseFormId public function Returns a string identifying the base form. Overrides BaseFormIdInterface::getBaseFormId 6
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 12
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
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::currentUser protected function Gets the current user.
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. 17
MessengerTrait::messenger public function Gets the messenger. 17
MessengerTrait::setMessenger public function Sets the messenger.
RedirectDestinationTrait::$redirectDestination protected property The redirect destination service. 1
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.