class ViewsExposedForm

Same name in this branch
  1. 8.9.x core/modules/views/src/Annotation/ViewsExposedForm.php \Drupal\views\Annotation\ViewsExposedForm
Same name in other branches
  1. 9 core/modules/views/src/Form/ViewsExposedForm.php \Drupal\views\Form\ViewsExposedForm
  2. 9 core/modules/views/src/Annotation/ViewsExposedForm.php \Drupal\views\Annotation\ViewsExposedForm
  3. 10 core/modules/views/src/Form/ViewsExposedForm.php \Drupal\views\Form\ViewsExposedForm
  4. 10 core/modules/views/src/Annotation/ViewsExposedForm.php \Drupal\views\Annotation\ViewsExposedForm
  5. 11.x core/modules/views/src/Form/ViewsExposedForm.php \Drupal\views\Form\ViewsExposedForm
  6. 11.x core/modules/views/src/Annotation/ViewsExposedForm.php \Drupal\views\Annotation\ViewsExposedForm
  7. 11.x core/modules/views/src/Attribute/ViewsExposedForm.php \Drupal\views\Attribute\ViewsExposedForm
  8. 10 core/modules/views/src/Attribute/ViewsExposedForm.php \Drupal\views\Attribute\ViewsExposedForm

Provides the views exposed form.

@internal

Hierarchy

Expanded class hierarchy of ViewsExposedForm

1 file declares its use of ViewsExposedForm
FormOperations.php in core/modules/workspaces/src/FormOperations.php

File

core/modules/views/src/Form/ViewsExposedForm.php, line 19

Namespace

Drupal\views\Form
View source
class ViewsExposedForm extends FormBase {
    
    /**
     * The exposed form cache.
     *
     * @var \Drupal\views\ExposedFormCache
     */
    protected $exposedFormCache;
    
    /**
     * The current path stack.
     *
     * @var \Drupal\Core\Path\CurrentPathStack
     */
    protected $currentPathStack;
    
    /**
     * Constructs a new ViewsExposedForm
     *
     * @param \Drupal\views\ExposedFormCache $exposed_form_cache
     *   The exposed form cache.
     * @param \Drupal\Core\Path\CurrentPathStack $current_path_stack
     *   The current path stack.
     */
    public function __construct(ExposedFormCache $exposed_form_cache, CurrentPathStack $current_path_stack = NULL) {
        $this->exposedFormCache = $exposed_form_cache;
        if ($current_path_stack === NULL) {
            @trigger_error('The path.current service must be passed to ViewsExposedForm::__construct(), it is required before Drupal 9.0.0. See https://www.drupal.org/node/3066604', E_USER_DEPRECATED);
            $current_path_stack = \Drupal::service('path.current');
        }
        $this->currentPathStack = $current_path_stack;
    }
    
    /**
     * {@inheritdoc}
     */
    public static function create(ContainerInterface $container) {
        return new static($container->get('views.exposed_form_cache'), $container->get('path.current'));
    }
    
    /**
     * {@inheritdoc}
     */
    public function getFormId() {
        return 'views_exposed_form';
    }
    
    /**
     * {@inheritdoc}
     */
    public function buildForm(array $form, FormStateInterface $form_state) {
        // Don't show the form when batch operations are in progress.
        if ($batch = batch_get() && isset($batch['current_set'])) {
            return [
                // Set the theme callback to be nothing to avoid errors in template_preprocess_views_exposed_form().
'#theme' => '',
            ];
        }
        // Make sure that we validate because this form might be submitted
        // multiple times per page.
        $form_state->setValidationEnforced();
        
        /** @var \Drupal\views\ViewExecutable $view */
        $view = $form_state->get('view');
        $display =& $form_state->get('display');
        $form_state->setUserInput($view->getExposedInput());
        // Let form plugins know this is for exposed widgets.
        $form_state->set('exposed', TRUE);
        // Check if the form was already created
        if ($cache = $this->exposedFormCache
            ->getForm($view->storage
            ->id(), $view->current_display)) {
            return $cache;
        }
        $form['#info'] = [];
        // Go through each handler and let it generate its exposed widget.
        foreach ($view->display_handler->handlers as $type => $value) {
            
            /** @var \Drupal\views\Plugin\views\ViewsHandlerInterface $handler */
            foreach ($view->{$type} as $id => $handler) {
                if ($handler->canExpose() && $handler->isExposed()) {
                    // Grouped exposed filters have their own forms.
                    // Instead of render the standard exposed form, a new Select or
                    // Radio form field is rendered with the available groups.
                    // When an user chooses an option the selected value is split
                    // into the operator and value that the item represents.
                    if ($handler->isAGroup()) {
                        $handler->groupForm($form, $form_state);
                        $id = $handler->options['group_info']['identifier'];
                    }
                    else {
                        $handler->buildExposedForm($form, $form_state);
                    }
                    if ($info = $handler->exposedInfo()) {
                        $form['#info']["{$type}-{$id}"] = $info;
                    }
                }
            }
        }
        $form['actions'] = [
            '#type' => 'actions',
        ];
        $form['actions']['submit'] = [
            // Prevent from showing up in \Drupal::request()->query.
'#name' => '',
            '#type' => 'submit',
            '#value' => $this->t('Apply'),
            '#id' => Html::getUniqueId('edit-submit-' . $view->storage
                ->id()),
        ];
        if (!$view->hasUrl()) {
            // On any non views.ajax route, use the current route for the form action.
            if ($this->getRouteMatch()
                ->getRouteName() !== 'views.ajax') {
                $form_action = Url::fromRoute('<current>')->toString();
            }
            else {
                // On the views.ajax route, set the action to the page we were on.
                $form_action = Url::fromUserInput($this->currentPathStack
                    ->getPath())
                    ->toString();
            }
        }
        else {
            $form_action = $view->getUrl()
                ->toString();
        }
        $form['#action'] = $form_action;
        $form['#theme'] = $view->buildThemeFunctions('views_exposed_form');
        $form['#id'] = Html::cleanCssIdentifier('views_exposed_form-' . $view->storage
            ->id() . '-' . $display['id']);
        
        /** @var \Drupal\views\Plugin\views\exposed_form\ExposedFormPluginInterface $exposed_form_plugin */
        $exposed_form_plugin = $view->display_handler
            ->getPlugin('exposed_form');
        $exposed_form_plugin->exposedFormAlter($form, $form_state);
        // Save the form.
        $this->exposedFormCache
            ->setForm($view->storage
            ->id(), $view->current_display, $form);
        return $form;
    }
    
    /**
     * {@inheritdoc}
     */
    public function validateForm(array &$form, FormStateInterface $form_state) {
        $view = $form_state->get('view');
        foreach ([
            'field',
            'filter',
        ] as $type) {
            
            /** @var \Drupal\views\Plugin\views\ViewsHandlerInterface[] $handlers */
            $handlers =& $view->{$type};
            foreach ($handlers as $key => $handler) {
                $handlers[$key]->validateExposed($form, $form_state);
            }
        }
        
        /** @var \Drupal\views\Plugin\views\exposed_form\ExposedFormPluginInterface $exposed_form_plugin */
        $exposed_form_plugin = $view->display_handler
            ->getPlugin('exposed_form');
        $exposed_form_plugin->exposedFormValidate($form, $form_state);
    }
    
    /**
     * {@inheritdoc}
     */
    public function submitForm(array &$form, FormStateInterface $form_state) {
        // Form input keys that will not be included in $view->exposed_raw_data.
        $exclude = [
            'submit',
            'form_build_id',
            'form_id',
            'form_token',
            'exposed_form_plugin',
            'reset',
        ];
        $values = $form_state->getValues();
        foreach ([
            'field',
            'filter',
        ] as $type) {
            
            /** @var \Drupal\views\Plugin\views\ViewsHandlerInterface[] $handlers */
            $handlers =& $form_state->get('view')->{$type};
            foreach ($handlers as $key => $info) {
                if ($handlers[$key]->acceptExposedInput($values)) {
                    $handlers[$key]->submitExposed($form, $form_state);
                }
                else {
                    // The input from the form did not validate, exclude it from the
                    // stored raw data.
                    $exclude[] = $key;
                }
            }
        }
        $view = $form_state->get('view');
        $view->exposed_data = $values;
        $view->exposed_raw_input = [];
        $exclude = [
            'submit',
            'form_build_id',
            'form_id',
            'form_token',
            'exposed_form_plugin',
            'reset',
        ];
        
        /** @var \Drupal\views\Plugin\views\exposed_form\ExposedFormPluginBase $exposed_form_plugin */
        $exposed_form_plugin = $view->display_handler
            ->getPlugin('exposed_form');
        $exposed_form_plugin->exposedFormSubmit($form, $form_state, $exclude);
        foreach ($values as $key => $value) {
            if (!empty($key) && !in_array($key, $exclude)) {
                if (is_array($value)) {
                    // Handle checkboxes, we only want to include the checked options.
                    // @todo: revisit the need for this when
                    //   https://www.drupal.org/node/342316 is resolved.
                    $checked = Checkboxes::getCheckedCheckboxes($value);
                    foreach ($checked as $option_id) {
                        $view->exposed_raw_input[$key][$option_id] = $value[$option_id];
                    }
                }
                else {
                    $view->exposed_raw_input[$key] = $value;
                }
            }
        }
    }

}

Members

Title Sort descending Deprecated Modifiers Object type Summary Overriden Title Overrides
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
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. Overrides UrlGeneratorTrait::redirect
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.
LinkGeneratorTrait::$linkGenerator protected property The link generator. 1
LinkGeneratorTrait::getLinkGenerator Deprecated protected function Returns the link generator.
LinkGeneratorTrait::l Deprecated protected function Renders a link to a route given a route name and its parameters.
LinkGeneratorTrait::setLinkGenerator Deprecated public function Sets the link generator service.
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.
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.
UrlGeneratorTrait::$urlGenerator protected property The url generator.
UrlGeneratorTrait::getUrlGenerator Deprecated protected function Returns the URL generator service.
UrlGeneratorTrait::setUrlGenerator Deprecated public function Sets the URL generator service.
UrlGeneratorTrait::url Deprecated protected function Generates a URL or path for a specific route based on the given parameters.
ViewsExposedForm::$currentPathStack protected property The current path stack.
ViewsExposedForm::$exposedFormCache protected property The exposed form cache.
ViewsExposedForm::buildForm public function Form constructor. Overrides FormInterface::buildForm
ViewsExposedForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
ViewsExposedForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
ViewsExposedForm::submitForm public function Form submission handler. Overrides FormInterface::submitForm
ViewsExposedForm::validateForm public function Form validation handler. Overrides FormBase::validateForm
ViewsExposedForm::__construct public function Constructs a new ViewsExposedForm

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