class ViewFormBase

Same name in other branches
  1. 9 core/modules/views_ui/src/ViewFormBase.php \Drupal\views_ui\ViewFormBase
  2. 8.9.x core/modules/views_ui/src/ViewFormBase.php \Drupal\views_ui\ViewFormBase
  3. 10 core/modules/views_ui/src/ViewFormBase.php \Drupal\views_ui\ViewFormBase

Base form for Views forms.

Hierarchy

Expanded class hierarchy of ViewFormBase

File

core/modules/views_ui/src/ViewFormBase.php, line 14

Namespace

Drupal\views_ui
View source
abstract class ViewFormBase extends EntityForm {
    
    /**
     * The name of the display used by the form.
     *
     * @var string
     */
    protected $displayID;
    
    /**
     * {@inheritdoc}
     */
    public function init(FormStateInterface $form_state) {
        parent::init($form_state);
        // @todo Remove the need for this.
        $form_state->loadInclude('views_ui', 'inc', 'admin');
        $form_state->set('view', $this->entity);
    }
    
    /**
     * {@inheritdoc}
     */
    public function buildForm(array $form, FormStateInterface $form_state, $display_id = NULL) {
        if (isset($display_id) && $form_state->has('display_id') && $display_id !== $form_state->get('display_id')) {
            throw new \InvalidArgumentException('Mismatch between $form_state->get(\'display_id\') and $display_id.');
        }
        $this->displayID = $form_state->has('display_id') ? $form_state->get('display_id') : $display_id;
        return parent::buildForm($form, $form_state);
    }
    
    /**
     * {@inheritdoc}
     */
    protected function prepareEntity() {
        // Determine the displays available for editing.
        if ($tabs = $this->getDisplayTabs($this->entity)) {
            if (empty($this->displayID)) {
                // If a display isn't specified, use the first one after sorting by
                // #weight.
                uasort($tabs, 'Drupal\\Component\\Utility\\SortArray::sortByWeightProperty');
                foreach ($tabs as $id => $tab) {
                    if (!isset($tab['#access']) || $tab['#access']) {
                        $this->displayID = $id;
                        break;
                    }
                }
            }
            // If a display is specified, but we don't have access to it, return
            // an access denied page.
            if ($this->displayID && !isset($tabs[$this->displayID])) {
                throw new NotFoundHttpException();
            }
            elseif ($this->displayID && (isset($tabs[$this->displayID]['#access']) && !$tabs[$this->displayID]['#access'])) {
                throw new AccessDeniedHttpException();
            }
        }
        elseif ($this->displayID) {
            throw new NotFoundHttpException();
        }
    }
    
    /**
     * Adds tabs for navigating across Displays when editing a View.
     *
     * This function can be called from hook_menu_local_tasks_alter() to implement
     * these tabs as secondary local tasks, or it can be called from elsewhere if
     * having them as secondary local tasks isn't desired. The caller is responsible
     * for setting the active tab's #active property to TRUE.
     *
     * @param \Drupal\views_ui\ViewUI $view
     *   The ViewUI entity.
     *
     * @return array
     *   An array of tab definitions.
     */
    public function getDisplayTabs(ViewUI $view) {
        $executable = $view->getExecutable();
        $executable->initDisplay();
        $display_id = $this->displayID;
        $tabs = [];
        // Create a tab for each display.
        foreach ($view->get('display') as $id => $display) {
            // Get an instance of the display plugin, to make sure it will work in the
            // UI.
            $display_plugin = $executable->displayHandlers
                ->get($id);
            if (empty($display_plugin)) {
                continue;
            }
            $tabs[$id] = [
                '#theme' => 'menu_local_task',
                '#weight' => $display['position'],
                '#link' => [
                    'title' => $this->getDisplayLabel($view, $id),
                    'localized_options' => [],
                    'url' => $view->toUrl('edit-display-form')
                        ->setRouteParameter('display_id', $id),
                ],
            ];
            if (!empty($display['deleted'])) {
                $tabs[$id]['#link']['localized_options']['attributes']['class'][] = 'views-display-deleted-link';
            }
            if (isset($display['display_options']['enabled']) && !$display['display_options']['enabled']) {
                $tabs[$id]['#link']['localized_options']['attributes']['class'][] = 'views-display-disabled-link';
            }
        }
        // If the default display isn't supposed to be shown, don't display its tab, unless it's the only display.
        if (!$this->isDefaultDisplayShown($view) && $display_id != 'default' && count($tabs) > 1) {
            $tabs['default']['#access'] = FALSE;
        }
        // Mark the display tab as red to show validation errors.
        $errors = $executable->validate();
        foreach ($view->get('display') as $id => $display) {
            if (!empty($errors[$id])) {
                // Always show the tab.
                $tabs[$id]['#access'] = TRUE;
                // Add a class to mark the error and a title to make a hover tip.
                $tabs[$id]['#link']['localized_options']['attributes']['class'][] = 'error';
                $tabs[$id]['#link']['localized_options']['attributes']['title'] = $this->t('This display has one or more validation errors.');
            }
        }
        return $tabs;
    }
    
    /**
     * Controls whether or not the default display should have its own tab on edit.
     */
    public function isDefaultDisplayShown(ViewUI $view) {
        // Always show the default display for advanced users who prefer that mode.
        $advanced_mode = \Drupal::config('views.settings')->get('ui.show.default_display');
        // For other users, show the default display only if there are no others, and
        // hide it if there's at least one "real" display.
        $additional_displays = count($view->getExecutable()->displayHandlers) == 1;
        return $advanced_mode || $additional_displays;
    }
    
    /**
     * Placeholder function for overriding $display['display_title'].
     *
     * @todo Remove this function once editing the display title is possible.
     */
    public function getDisplayLabel(ViewUI $view, $display_id, $check_changed = TRUE) {
        $display = $view->get('display');
        $title = $display_id == 'default' ? $this->t('Default') : $display[$display_id]['display_title'];
        $title = Unicode::truncate($title, 25, FALSE, TRUE);
        if ($check_changed && !empty($view->changed_display[$display_id])) {
            $changed = '*';
            $title = $title . $changed;
        }
        return $title;
    }

}

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::actions protected function Returns an array of supported actions for the current entity form. 36
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::copyFormValuesToEntity protected function Copies top-level form values to entity properties. 11
EntityForm::form public function Gets the actual form array to be built. 36
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::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 'save' 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
EntityForm::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 FormInterface::submitForm 21
FormBase::$configFactory protected property The config factory. 2
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. 2
FormBase::container private function Returns the service container.
FormBase::create public static function Instantiates a new instance of this class. Overrides ContainerInjectionInterface::create 109
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.
FormBase::validateForm public function Form validation handler. Overrides FormInterface::validateForm 57
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 'destination' 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.
ViewFormBase::$displayID protected property The name of the display used by the form.
ViewFormBase::buildForm public function Form constructor. Overrides EntityForm::buildForm
ViewFormBase::getDisplayLabel public function Placeholder function for overriding $display['display_title'].
ViewFormBase::getDisplayTabs public function Adds tabs for navigating across Displays when editing a View.
ViewFormBase::init public function Initialize the form state and the entity before the first form build. Overrides EntityForm::init
ViewFormBase::isDefaultDisplayShown public function Controls whether or not the default display should have its own tab on edit.
ViewFormBase::prepareEntity protected function Prepares the entity object before the form is built first. Overrides EntityForm::prepareEntity 2

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