class EntityReference

Same name in this branch
  1. 11.x core/modules/field/src/Plugin/migrate/field/d7/EntityReference.php \Drupal\field\Plugin\migrate\field\d7\EntityReference
  2. 11.x core/modules/views/src/Plugin/views/row/EntityReference.php \Drupal\views\Plugin\views\row\EntityReference
  3. 11.x core/modules/views/src/Plugin/views/display/EntityReference.php \Drupal\views\Plugin\views\display\EntityReference
  4. 11.x core/modules/views/src/Plugin/views/style/EntityReference.php \Drupal\views\Plugin\views\style\EntityReference
  5. 11.x core/lib/Drupal/Core/Entity/Plugin/DataType/EntityReference.php \Drupal\Core\Entity\Plugin\DataType\EntityReference
Same name in other branches
  1. 9 core/modules/field/src/Plugin/migrate/field/d7/EntityReference.php \Drupal\field\Plugin\migrate\field\d7\EntityReference
  2. 9 core/modules/views/src/Plugin/views/row/EntityReference.php \Drupal\views\Plugin\views\row\EntityReference
  3. 9 core/modules/views/src/Plugin/views/display/EntityReference.php \Drupal\views\Plugin\views\display\EntityReference
  4. 9 core/modules/views/src/Plugin/views/style/EntityReference.php \Drupal\views\Plugin\views\style\EntityReference
  5. 9 core/lib/Drupal/Core/Entity/Plugin/DataType/EntityReference.php \Drupal\Core\Entity\Plugin\DataType\EntityReference
  6. 8.9.x core/modules/field/src/Plugin/migrate/field/d7/EntityReference.php \Drupal\field\Plugin\migrate\field\d7\EntityReference
  7. 8.9.x core/modules/views/src/Plugin/views/row/EntityReference.php \Drupal\views\Plugin\views\row\EntityReference
  8. 8.9.x core/modules/views/src/Plugin/views/display/EntityReference.php \Drupal\views\Plugin\views\display\EntityReference
  9. 8.9.x core/modules/views/src/Plugin/views/style/EntityReference.php \Drupal\views\Plugin\views\style\EntityReference
  10. 8.9.x core/modules/entity_reference/src/Plugin/views/row/EntityReference.php \Drupal\entity_reference\Plugin\views\row\EntityReference
  11. 8.9.x core/modules/entity_reference/src/Plugin/views/display/EntityReference.php \Drupal\entity_reference\Plugin\views\display\EntityReference
  12. 8.9.x core/modules/entity_reference/src/Plugin/views/style/EntityReference.php \Drupal\entity_reference\Plugin\views\style\EntityReference
  13. 8.9.x core/lib/Drupal/Core/Field/Plugin/migrate/field/d7/EntityReference.php \Drupal\Core\Field\Plugin\migrate\field\d7\EntityReference
  14. 8.9.x core/lib/Drupal/Core/Entity/Plugin/DataType/EntityReference.php \Drupal\Core\Entity\Plugin\DataType\EntityReference
  15. 10 core/modules/field/src/Plugin/migrate/field/d7/EntityReference.php \Drupal\field\Plugin\migrate\field\d7\EntityReference
  16. 10 core/modules/views/src/Plugin/views/row/EntityReference.php \Drupal\views\Plugin\views\row\EntityReference
  17. 10 core/modules/views/src/Plugin/views/display/EntityReference.php \Drupal\views\Plugin\views\display\EntityReference
  18. 10 core/modules/views/src/Plugin/views/style/EntityReference.php \Drupal\views\Plugin\views\style\EntityReference
  19. 10 core/lib/Drupal/Core/Entity/Plugin/DataType/EntityReference.php \Drupal\Core\Entity\Plugin\DataType\EntityReference

Filters a view by entity references.

Hierarchy

Expanded class hierarchy of EntityReference

Related topics

1 file declares its use of EntityReference
FilterEntityReferenceTest.php in core/modules/views/tests/src/Kernel/Handler/FilterEntityReferenceTest.php
4 string references to 'EntityReference'
FieldInstanceSettings::transform in core/modules/field/src/Plugin/migrate/process/d7/FieldInstanceSettings.php
Performs the associated process.
MigrationProvidersExistTest::testFieldProvidersExist in core/modules/migrate/tests/src/Kernel/Plugin/MigrationProvidersExistTest.php
Tests that modules exist for all field plugins.
views.view.test_entity_reference.yml in core/modules/system/tests/modules/entity_reference_test/config/install/views.view.test_entity_reference.yml
core/modules/system/tests/modules/entity_reference_test/config/install/views.view.test_entity_reference.yml
views.view.test_entity_reference_entity_test.yml in core/modules/system/tests/modules/entity_reference_test/config/install/views.view.test_entity_reference_entity_test.yml
core/modules/system/tests/modules/entity_reference_test/config/install/views.view.test_entity_reference_entity_test.yml

File

core/modules/views/src/Plugin/views/filter/EntityReference.php, line 28

Namespace

Drupal\views\Plugin\views\filter
View source
class EntityReference extends ManyToOne {
    use FieldAPIHandlerTrait;
    
    /**
     * Type for the autocomplete filter format.
     */
    const WIDGET_AUTOCOMPLETE = 'autocomplete';
    
    /**
     * Type for the select list filter format.
     */
    const WIDGET_SELECT = 'select';
    
    /**
     * Max number of entities in the select widget.
     */
    const WIDGET_SELECT_LIMIT = 100;
    
    /**
     * The subform prefix.
     */
    const SUBFORM_PREFIX = 'reference_';
    
    /**
     * The all value.
     */
    const ALL_VALUE = 'All';
    
    /**
     * The selection handlers available for the target entity ID of the filter.
     *
     * @var array|null
     */
    protected ?array $handlerOptions = NULL;
    
    /**
     * Validated exposed input that will be set as the input value.
     *
     * If the select list widget is chosen.
     *
     * @var array
     */
    protected array $validatedExposedInput;
    
    /**
     * {@inheritdoc}
     */
    public function init(ViewExecutable $view, DisplayPluginBase $display, ?array &$options = NULL) : void {
        parent::init($view, $display, $options);
        if (empty($this->definition['field_name'])) {
            $this->definition['field_name'] = $options['field'];
        }
        $this->definition['options callback'] = [
            $this,
            'getValueOptionsCallback',
        ];
        $this->definition['options arguments'] = [
            $this->getSelectionHandler($this->options['sub_handler']),
        ];
    }
    
    /**
     * Constructs an EntityReference object.
     */
    public function __construct(array $configuration, $plugin_id, $plugin_definition, SelectionPluginManagerInterface $selectionPluginManager, EntityTypeManagerInterface $entityTypeManager, MessengerInterface $messenger) {
        parent::__construct($configuration, $plugin_id, $plugin_definition);
        $this->setMessenger($messenger);
        // @todo Unify 'entity field'/'field_name' instead of converting back and
        // forth. https://www.drupal.org/node/2410779
        if (isset($this->definition['entity field'])) {
            $this->definition['field_name'] = $this->definition['entity field'];
        }
    }
    
    /**
     * {@inheritdoc}
     */
    public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) : EntityReference {
        return new static($configuration, $plugin_id, $plugin_definition, $container->get('plugin.manager.entity_reference_selection'), $container->get('entity_type.manager'), $container->get('messenger'));
    }
    
    /**
     * Gets the entity reference selection handler.
     *
     * @param string|null $sub_handler
     *   The sub handler to get an instance of or NULL for the current selection.
     *
     * @return \Drupal\Core\Entity\EntityReferenceSelection\SelectionInterface
     *   The selection handler plugin instance.
     */
    protected function getSelectionHandler(?string $sub_handler = NULL) : SelectionInterface {
        // Default values for the handler.
        $handler_settings = $this->options['sub_handler_settings'] ?? [];
        $handler_settings['handler'] = $sub_handler;
        $handler_settings['target_type'] = $this->getReferencedEntityType()
            ->id();
        
        /** @var \Drupal\Core\Entity\EntityReferenceSelection\SelectionInterface */
        return $this->selectionPluginManager
            ->getInstance($handler_settings);
    }
    
    /**
     * {@inheritdoc}
     */
    protected function defineOptions() : array {
        $options = parent::defineOptions();
        $options['sub_handler'] = [
            'default' => 'default:' . $this->getReferencedEntityType()
                ->id(),
        ];
        $options['sub_handler_settings'] = [
            'default' => [],
        ];
        $options['widget'] = [
            'default' => static::WIDGET_AUTOCOMPLETE,
        ];
        return $options;
    }
    
    /**
     * {@inheritdoc}
     */
    public function hasExtraOptions() : bool {
        return TRUE;
    }
    
    /**
     * Get all selection plugins for this entity type.
     *
     * @return string[]
     *   The selection handlers available for the target entity ID of the filter.
     */
    protected function getSubHandlerOptions() : array {
        if ($this->handlerOptions) {
            return $this->handlerOptions;
        }
        $entity_type = $this->getReferencedEntityType();
        $selection_plugins = $this->selectionPluginManager
            ->getSelectionGroups($entity_type->id());
        $this->handlerOptions = [];
        foreach (array_keys($selection_plugins) as $selection_group_id) {
            // We only display base plugins (e.g. 'default', 'views', ...).
            if (array_key_exists($selection_group_id, $selection_plugins[$selection_group_id])) {
                $this->handlerOptions[$selection_group_id] = (string) $selection_plugins[$selection_group_id][$selection_group_id]['label'];
            }
            elseif (array_key_exists($selection_group_id . ':' . $entity_type->id(), $selection_plugins[$selection_group_id])) {
                $selection_group_plugin = $selection_group_id . ':' . $entity_type->id();
                $this->handlerOptions[$selection_group_plugin] = (string) $selection_plugins[$selection_group_id][$selection_group_plugin]['base_plugin_label'];
            }
        }
        return $this->handlerOptions;
    }
    
    /**
     * {@inheritdoc}
     */
    public function buildExtraOptionsForm(&$form, FormStateInterface $form_state) : void {
        $form['sub_handler'] = [
            '#type' => 'select',
            '#title' => $this->t('Reference method'),
            '#options' => $this->getSubHandlerOptions(),
            '#default_value' => $this->options['sub_handler'],
            '#required' => TRUE,
        ];
        // We store the settings from any sub handler in sub_handler_settings, but
        // in this form, we have multiple sub handlers conditionally displayed.
        // Copy the active sub_handler_settings into the handler specific settings
        // to set the defaults to match the saved options on build.
        if (!empty($this->options['sub_handler']) && !empty($this->options['sub_handler_settings'])) {
            $this->options[static::SUBFORM_PREFIX . $this->options['sub_handler']] = $this->options['sub_handler_settings'];
        }
        foreach ($this->getSubHandlerOptions() as $sub_handler => $sub_handler_label) {
            $subform_key = static::SUBFORM_PREFIX . $sub_handler;
            $subform = [
                '#type' => 'fieldset',
                '#title' => $this->t('Reference type "@type"', [
                    '@type' => $sub_handler_label,
                ]),
                '#tree' => TRUE,
                '#parents' => [
                    'options',
                    $subform_key,
                ],
                // Make the sub handler settings conditional on the selected selection
                // handler.
'#states' => [
                    'visible' => [
                        'select[name="options[sub_handler]"]' => [
                            'value' => $sub_handler,
                        ],
                    ],
                ],
            ];
            // Build the sub form and sub for state.
            $selection_handler = $this->getSelectionHandler($sub_handler);
            if (!empty($this->options[$subform_key])) {
                $selection_config = $selection_handler->getConfiguration();
                $selection_config = NestedArray::mergeDeepArray([
                    $selection_config,
                    $this->options[$subform_key],
                ], TRUE);
                $selection_handler->setConfiguration($selection_config);
            }
            $subform_state = SubformState::createForSubform($subform, $form, $form_state);
            $sub_handler_settings = $selection_handler->buildConfigurationForm($subform, $subform_state);
            if ($selection_handler instanceof ViewsSelection) {
                if (isset($sub_handler_settings['view']['no_view_help'])) {
                    // If there are no views with entity reference displays,
                    // ViewsSelection still validates the view.
                    // This will prevent form config extra form submission,
                    // so we remove it here.
                    unset($sub_handler_settings['view']['#element_validate']);
                }
            }
            else {
                // Remove unnecessary and inappropriate handler settings from the
                // filter config form.
                $sub_handler_settings['target_bundles_update']['#access'] = FALSE;
                $sub_handler_settings['auto_create']['#access'] = FALSE;
                $sub_handler_settings['auto_create_bundle']['#access'] = FALSE;
            }
            $subform = NestedArray::mergeDeepArray([
                $subform,
                $sub_handler_settings,
            ], TRUE);
            $form[$subform_key] = $subform;
            $this->cleanUpSubformChildren($form[$subform_key]);
        }
        $form['widget'] = [
            '#type' => 'radios',
            '#title' => $this->t('Selection type'),
            '#default_value' => $this->options['widget'],
            '#options' => [
                static::WIDGET_SELECT => $this->t('Select list'),
                static::WIDGET_AUTOCOMPLETE => $this->t('Autocomplete'),
            ],
            '#description' => $this->t('For performance and UX reasons, the maximum count of selectable entities for the "Select list" selection type is limited to @count. If more is expected, select "Autocomplete" instead.', [
                '@count' => static::WIDGET_SELECT_LIMIT,
            ]),
        ];
    }
    
    /**
     * Clean up subform children for properties that could cause problems.
     *
     * Views modal forms do not work with required or ajax elements.
     *
     * @param array $element
     *   The form element.
     */
    protected function cleanUpSubformChildren(array &$element) : void {
        // Remove the required property to prevent focus errors.
        if (isset($element['#required']) && $element['#required']) {
            $element['#required'] = FALSE;
            $element['#element_validate'][] = [
                static::class,
                'validateRequired',
            ];
        }
        // Remove the ajax property as it does not work.
        if (!empty($element['#ajax'])) {
            unset($element['#ajax']);
        }
        // Recursively apply to nested fields within the handler sub form.
        foreach (Element::children($element) as $delta) {
            $this->cleanUpSubformChildren($element[$delta]);
        }
    }
    
    /**
     * Validates that a required field for a sub handler has a value.
     *
     * @param array $element
     *   The cardinality form render array.
     * @param \Drupal\Core\Form\FormStateInterface $form_state
     *   The form state.
     */
    public static function validateRequired(array &$element, FormStateInterface $form_state) : void {
        if (!empty($element['value'])) {
            return;
        }
        // Config extra handler does not output validation messages and
        // closes the modal with no feedback to the user.
        // @todo https://www.drupal.org/project/drupal/issues/3163740.
    }
    
    /**
     * {@inheritdoc}
     */
    public function validateExtraOptionsForm($form, FormStateInterface $form_state) : void {
        $options = $form_state->getValue('options');
        $sub_handler = $options['sub_handler'];
        $subform = $form[static::SUBFORM_PREFIX . $sub_handler];
        $subform_state = SubformState::createForSubform($subform, $form, $form_state);
        // Copy handler_settings from options to settings to be compatible with
        // selection plugins.
        $subform_options = $form_state->getValue([
            'options',
            static::SUBFORM_PREFIX . $sub_handler,
        ]);
        $subform_state->setValue([
            'settings',
        ], $subform_options);
        $this->getSelectionHandler($sub_handler)
            ->validateConfigurationForm($subform, $subform_state);
        // Store the sub handler options in sub_handler_settings.
        $form_state->setValue([
            'options',
            'sub_handler_settings',
        ], $subform_options);
        // Remove options that are not from the selected sub_handler.
        foreach (array_keys($this->getSubHandlerOptions()) as $sub_handler_option) {
            if (isset($options[static::SUBFORM_PREFIX . $sub_handler_option])) {
                $form_state->unsetValue([
                    'options',
                    static::SUBFORM_PREFIX . $sub_handler_option,
                ]);
            }
        }
        parent::validateExtraOptionsForm($form, $form_state);
    }
    
    /**
     * {@inheritdoc}
     */
    public function submitExtraOptionsForm($form, FormStateInterface $form_state) : void {
        $sub_handler = $form_state->getValue('options')['sub_handler'];
        // Ensure that only the select sub handler option is saved.
        foreach (array_keys($this->getSubHandlerOptions()) as $sub_handler_option) {
            if ($sub_handler_option == $sub_handler) {
                $this->options['sub_handler_settings'] = $this->options[static::SUBFORM_PREFIX . $sub_handler_option];
            }
            if (isset($this->options[static::SUBFORM_PREFIX . $sub_handler_option])) {
                unset($this->options[static::SUBFORM_PREFIX . $sub_handler_option]);
            }
        }
    }
    
    /**
     * Normalize values for widget switching.
     *
     * The saved values can differ in live preview if switching back and forth
     * between the select and autocomplete widgets. This normalizes the values to
     * avoid errors when making the switch.
     *
     * @param array $form
     *   Associative array containing the structure of the form, passed by
     *   reference.
     * @param \Drupal\Core\Form\FormStateInterface $form_state
     *   The current state of the form.
     */
    protected function alternateWidgetsDefaultNormalize(array &$form, FormStateInterface $form_state) : void {
        $field_id = '_' . $this->getFieldDefinition()
            ->getName() . '-widget';
        $form[$field_id] = [
            '#type' => 'hidden',
            '#value' => $this->options['widget'],
        ];
        $previous_widget = $form_state->getUserInput()[$field_id] ?? NULL;
        if ($previous_widget && $previous_widget !== $this->options['widget']) {
            $form['value']['#value_callback'] = function ($element) {
                return $element['#default_value'] ?? '';
            };
        }
    }
    
    /**
     * {@inheritdoc}
     */
    protected function valueForm(&$form, FormStateInterface $form_state) {
        if (!isset($this->options['sub_handler'])) {
            return;
        }
        switch ($this->options['widget']) {
            case static::WIDGET_SELECT:
                $this->valueFormAddSelect($form, $form_state);
                break;
            case static::WIDGET_AUTOCOMPLETE:
                $this->valueFormAddAutocomplete($form, $form_state);
                break;
        }
        if (!empty($this->view->live_preview)) {
            $this->alternateWidgetsDefaultNormalize($form, $form_state);
        }
        // Show or hide the value field depending on the operator field.
        $is_exposed = $this->options['exposed'];
        $visible = [];
        if ($is_exposed) {
            $operator_field = $this->options['expose']['use_operator'] && $this->options['expose']['operator_id'] ? $this->options['expose']['operator_id'] : NULL;
        }
        else {
            $operator_field = 'options[operator]';
            $visible[] = [
                ':input[name="options[expose_button][checkbox][checkbox]"]' => [
                    'checked' => TRUE,
                ],
                ':input[name="options[expose][use_operator]"]' => [
                    'checked' => TRUE,
                ],
                ':input[name="options[expose][operator_id]"]' => [
                    'empty' => FALSE,
                ],
            ];
        }
        if ($operator_field) {
            foreach ($this->operatorValues(1) as $operator) {
                $visible[] = [
                    ':input[name="' . $operator_field . '"]' => [
                        'value' => $operator,
                    ],
                ];
            }
            $form['value']['#states'] = [
                'visible' => $visible,
            ];
        }
        if (!$is_exposed) {
            // Retain the helper option.
            $this->helper
                ->buildOptionsForm($form, $form_state);
            // Show help text if not exposed to end users.
            $form['value']['#description'] = $this->t('Leave blank for all. Otherwise, the first selected item will be the default instead of "Any".');
        }
    }
    
    /**
     * Adds an autocomplete element to the form.
     *
     * @param array $form
     *   Associative array containing the structure of the form, passed by
     *   reference.
     * @param \Drupal\Core\Form\FormStateInterface $form_state
     *   The current state of the form.
     */
    protected function valueFormAddAutocomplete(array &$form, FormStateInterface $form_state) : void {
        $referenced_type = $this->getReferencedEntityType();
        $form['value'] = [
            '#title' => $this->t('Select %entity_types', [
                '%entity_types' => $referenced_type->getPluralLabel(),
            ]),
            '#type' => 'entity_autocomplete',
            '#default_value' => EntityAutocomplete::getEntityLabels($this->getDefaultSelectedEntities()),
            '#tags' => TRUE,
            '#process_default_value' => FALSE,
            '#target_type' => $referenced_type->id(),
            '#selection_handler' => $this->options['sub_handler'],
            '#selection_settings' => $this->options['sub_handler_settings'],
            // Validation is done by validateExposed().
'#validate_reference' => FALSE,
        ];
    }
    
    /**
     * Adds a select element to the form.
     *
     * @param array $form
     *   Associative array containing the structure of the form, passed by
     *   reference.
     * @param \Drupal\Core\Form\FormStateInterface $form_state
     *   The current state of the form.
     */
    protected function valueFormAddSelect(array &$form, FormStateInterface $form_state) : void {
        $is_exposed = $form_state->get('exposed');
        $options = $this->getValueOptions();
        $default_value = (array) $this->value;
        if ($is_exposed) {
            $identifier = $this->options['expose']['identifier'];
            if (!empty($this->options['expose']['reduce'])) {
                $options = $this->reduceValueOptions($options);
                if (!empty($this->options['expose']['multiple']) && empty($this->options['expose']['required'])) {
                    $default_value = [];
                }
            }
            if (empty($this->options['expose']['multiple'])) {
                if (empty($this->options['expose']['required']) && (empty($default_value) || !empty($this->options['expose']['reduce']))) {
                    $default_value = static::ALL_VALUE;
                }
                elseif (empty($default_value)) {
                    $keys = array_keys($options);
                    $default_value = array_shift($keys);
                }
                else {
                    // Set the default value to be the first element of the array.
                    $default_value = reset($default_value);
                }
            }
        }
        $referenced_type = $this->getReferencedEntityType();
        $form['value'] = [
            '#type' => 'select',
            '#title' => $this->t('Select @entity_types', [
                '@entity_types' => $referenced_type->getPluralLabel(),
            ]),
            '#multiple' => TRUE,
            '#options' => $options,
            // Set a minimum size to facilitate easier selection of entities.
'#size' => min(8, count($options)),
            '#default_value' => $default_value,
        ];
        $user_input = $form_state->getUserInput();
        if ($is_exposed && isset($identifier) && !isset($user_input[$identifier])) {
            $user_input[$identifier] = $default_value;
            $form_state->setUserInput($user_input);
        }
    }
    
    /**
     * Gets all entities selected by default.
     *
     * @return \Drupal\Core\Entity\EntityInterface[]
     *   All entities selected by default, or an empty array, if none.
     */
    protected function getDefaultSelectedEntities() : array {
        $referenced_type_id = $this->getReferencedEntityType()
            ->id();
        $entity_storage = $this->entityTypeManager
            ->getStorage($referenced_type_id);
        return !empty($this->value) && !isset($this->value[static::ALL_VALUE]) ? $entity_storage->loadMultiple($this->value) : [];
    }
    
    /**
     * Returns the value options for a select widget.
     *
     * @param \Drupal\Core\Entity\EntityReferenceSelection\SelectionInterface $selection_handler
     *   The selection handler.
     *
     * @return string[]
     *   The options.
     *
     * @see \Drupal\views\Plugin\views\filter\InOperator::getValueOptions()
     */
    protected function getValueOptionsCallback(SelectionInterface $selection_handler) : array {
        $entity_data = [];
        if ($this->options['widget'] === static::WIDGET_SELECT) {
            $entity_data = $selection_handler->getReferenceableEntities(NULL, 'CONTAINS', static::WIDGET_SELECT_LIMIT);
        }
        $options = [];
        foreach ($entity_data as $bundle) {
            foreach ($bundle as $id => $entity_label) {
                $options[$id] = $entity_label;
            }
        }
        return $options;
    }
    
    /**
     * {@inheritdoc}
     */
    public function validate() : array {
        // InOperator validation logic is not appropriate for entity reference
        // autocomplete or select, so prevent parent class validation from
        // occurring.
        return [];
    }
    
    /**
     * {@inheritdoc}
     */
    public function acceptExposedInput($input) : bool {
        if (empty($this->options['exposed'])) {
            return TRUE;
        }
        // We need to know the operator, which is normally set in
        // \Drupal\views\Plugin\views\filter\FilterPluginBase::acceptExposedInput(),
        // before we actually call the parent version of ourselves.
        if (!empty($this->options['expose']['use_operator']) && !empty($this->options['expose']['operator_id']) && isset($input[$this->options['expose']['operator_id']])) {
            $this->operator = $input[$this->options['expose']['operator_id']];
        }
        // If view is an attachment and is inheriting exposed filters, then assume
        // exposed input has already been validated.
        if (!empty($this->view->is_attachment) && $this->view->display_handler
            ->usesExposed()) {
            $this->validatedExposedInput = (array) $this->view->exposed_raw_input[$this->options['expose']['identifier']];
        }
        // If we're checking for EMPTY or NOT, we don't need any input, and we can
        // say that our input conditions are met by just having the right operator.
        if ($this->operator == 'empty' || $this->operator == 'not empty') {
            return TRUE;
        }
        // If it's non-required and there's no value don't bother filtering.
        if (!$this->options['expose']['required'] && empty($this->validatedExposedInput)) {
            return FALSE;
        }
        $accept_exposed_input = parent::acceptExposedInput($input);
        if ($accept_exposed_input) {
            // If we have previously validated input, override.
            if (isset($this->validatedExposedInput)) {
                $this->value = $this->validatedExposedInput;
            }
        }
        return $accept_exposed_input;
    }
    
    /**
     * {@inheritdoc}
     */
    public function validateExposed(&$form, FormStateInterface $form_state) : void {
        if (empty($this->options['exposed'])) {
            return;
        }
        $identifier = $this->options['expose']['identifier'];
        // Set the validated exposed input from the select list when not the all
        // value option.
        if ($this->options['widget'] == static::WIDGET_SELECT) {
            if ($form_state->getValue($identifier) != static::ALL_VALUE) {
                $this->validatedExposedInput = (array) $form_state->getValue($identifier);
            }
            return;
        }
        if (empty($identifier)) {
            return;
        }
        $values = $form_state->getValue($identifier);
        if (!is_array($values)) {
            return;
        }
        foreach ($values as $value) {
            $this->validatedExposedInput[] = $value['target_id'];
        }
    }
    
    /**
     * {@inheritdoc}
     */
    protected function valueSubmit($form, FormStateInterface $form_state) : void {
        // Prevent the parent class InOperator from altering the array.
        // @see \Drupal\views\Plugin\views\filter\InOperator::valueSubmit().
    }
    
    /**
     * Gets the target entity type referenced by this field.
     *
     * @return \Drupal\Core\Entity\EntityTypeInterface
     *   The entity type definition.
     */
    protected function getReferencedEntityType() : EntityTypeInterface {
        $field_def = $this->getFieldDefinition();
        $entity_type_id = $field_def->getItemDefinition()
            ->getSetting('target_type');
        return $this->entityTypeManager
            ->getDefinition($entity_type_id);
    }
    
    /**
     * {@inheritdoc}
     */
    public function calculateDependencies() : array {
        $dependencies = parent::calculateDependencies();
        $sub_handler = $this->options['sub_handler'];
        $selection_handler = $this->getSelectionHandler($sub_handler);
        if ($selection_handler instanceof DependentPluginInterface) {
            $dependencies += $selection_handler->calculateDependencies();
        }
        foreach ($this->getDefaultSelectedEntities() as $entity) {
            $dependencies[$entity->getConfigDependencyKey()][] = $entity->getConfigDependencyName();
        }
        return $dependencies;
    }

}

Members

Title Sort descending Modifiers Object type Summary Overriden Title Overrides
DerivativeInspectionInterface::getBaseId public function Gets the base_plugin_id of the plugin instance. 1
DerivativeInspectionInterface::getDerivativeId public function Gets the derivative_id of the plugin instance. 1
EntityReference::$handlerOptions protected property The selection handlers available for the target entity ID of the filter.
EntityReference::$validatedExposedInput protected property Validated exposed input that will be set as the input value.
EntityReference::acceptExposedInput public function Determines if the input from a filter should change the generated query. Overrides InOperator::acceptExposedInput
EntityReference::ALL_VALUE constant The all value.
EntityReference::alternateWidgetsDefaultNormalize protected function Normalize values for widget switching.
EntityReference::buildExtraOptionsForm public function Provide a form for setting options. Overrides HandlerBase::buildExtraOptionsForm
EntityReference::calculateDependencies public function Calculates dependencies for the configured plugin. Overrides HandlerBase::calculateDependencies
EntityReference::cleanUpSubformChildren protected function Clean up subform children for properties that could cause problems.
EntityReference::create public static function Creates an instance of the plugin. Overrides PluginBase::create
EntityReference::defineOptions protected function Information about options for all kinds of purposes will be held here. Overrides ManyToOne::defineOptions
EntityReference::getDefaultSelectedEntities protected function Gets all entities selected by default.
EntityReference::getReferencedEntityType protected function Gets the target entity type referenced by this field.
EntityReference::getSelectionHandler protected function Gets the entity reference selection handler.
EntityReference::getSubHandlerOptions protected function Get all selection plugins for this entity type.
EntityReference::getValueOptionsCallback protected function Returns the value options for a select widget.
EntityReference::hasExtraOptions public function Determines if the handler has extra options. Overrides HandlerBase::hasExtraOptions
EntityReference::init public function Overrides \Drupal\views\Plugin\views\HandlerBase::init(). Overrides ManyToOne::init
EntityReference::SUBFORM_PREFIX constant The subform prefix.
EntityReference::submitExtraOptionsForm public function Perform any necessary changes to the form values prior to storage. Overrides HandlerBase::submitExtraOptionsForm
EntityReference::validate public function Validate that the plugin is correct and can be saved. Overrides InOperator::validate
EntityReference::validateExposed public function Validate the exposed handler form. Overrides HandlerBase::validateExposed
EntityReference::validateExtraOptionsForm public function Validate the options form. Overrides HandlerBase::validateExtraOptionsForm
EntityReference::validateRequired public static function Validates that a required field for a sub handler has a value.
EntityReference::valueForm protected function Options form subform for setting options. Overrides ManyToOne::valueForm
EntityReference::valueFormAddAutocomplete protected function Adds an autocomplete element to the form.
EntityReference::valueFormAddSelect protected function Adds a select element to the form.
EntityReference::valueSubmit protected function Perform any necessary changes to the form values prior to storage. Overrides InOperator::valueSubmit
EntityReference::WIDGET_AUTOCOMPLETE constant Type for the autocomplete filter format.
EntityReference::WIDGET_SELECT constant Type for the select list filter format.
EntityReference::WIDGET_SELECT_LIMIT constant Max number of entities in the select widget.
EntityReference::__construct public function Constructs an EntityReference object. Overrides HandlerBase::__construct
FieldAPIHandlerTrait::$entityFieldManager protected property The entity field manager.
FieldAPIHandlerTrait::$fieldDefinition protected property The field definition.
FieldAPIHandlerTrait::$fieldStorageDefinition protected property The field storage definition.
FieldAPIHandlerTrait::getEntityFieldManager protected function Returns the entity field manager.
FieldAPIHandlerTrait::getFieldDefinition protected function Gets the field definition.
FieldAPIHandlerTrait::getFieldStorageDefinition protected function Gets the field storage configuration. 1
FilterPluginBase::$alwaysMultiple protected property Disable the possibility to force a single value. 6
FilterPluginBase::$always_required public property
FilterPluginBase::$group_info public property
FilterPluginBase::$no_operator public property 1
FilterPluginBase::$operator public property Contains the operator which is used on the query.
FilterPluginBase::$tableAliases public property Keyed array by alias of table relations.
FilterPluginBase::$value public property The value.
FilterPluginBase::addGroupForm public function Add a new group to the exposed filter groups.
FilterPluginBase::arrayFilterZero protected static function Filter by no empty values, though allow the use of (string) "0".
FilterPluginBase::buildExposedFiltersGroupForm protected function Build the form to let users create the group of exposed filters.
FilterPluginBase::buildExposedForm public function Render our chunk of the exposed filter form when selecting. Overrides HandlerBase::buildExposedForm
FilterPluginBase::buildGroupForm public function Displays the Build Group form.
FilterPluginBase::buildGroupOptions protected function Provide default options for exposed filters.
FilterPluginBase::buildGroupSubmit protected function Save new group items, re-enumerates and remove groups marked to delete.
FilterPluginBase::buildGroupValidate protected function Validate the build group options form.
FilterPluginBase::buildOptionsForm public function Provide the basic form which calls through to subforms. Overrides HandlerBase::buildOptionsForm 2
FilterPluginBase::buildValueWrapper protected function Builds wrapper for value and operator forms.
FilterPluginBase::canBuildGroup protected function Determine if a filter can be converted into a group.
FilterPluginBase::canExpose public function Determine if a filter can be exposed. Overrides HandlerBase::canExpose 5
FilterPluginBase::canGroup public function Can this filter be used in OR groups? 1
FilterPluginBase::convertExposedInput public function Transform the input from a grouped filter into a standard filter.
FilterPluginBase::exposedInfo public function Tell the renderer about our exposed form. Overrides HandlerBase::exposedInfo
FilterPluginBase::exposedTranslate protected function Make some translations to a form item to make it more suitable to exposing.
FilterPluginBase::getCacheContexts public function The cache contexts associated with this object. Overrides CacheableDependencyInterface::getCacheContexts 6
FilterPluginBase::getCacheMaxAge public function The maximum age for which this object may be cached. Overrides CacheableDependencyInterface::getCacheMaxAge
FilterPluginBase::getCacheTags public function The cache tags associated with this object. Overrides CacheableDependencyInterface::getCacheTags 1
FilterPluginBase::groupForm public function Builds a group form.
FilterPluginBase::groupMultipleExposedInput public function Group multiple exposed input.
FilterPluginBase::hasValidGroupedValue protected function Determines if the given grouped filter entry has a valid value. 1
FilterPluginBase::isAGroup public function Returns TRUE if the exposed filter works like a grouped filter. Overrides HandlerBase::isAGroup
FilterPluginBase::multipleExposedInput public function Multiple exposed input. Overrides HandlerBase::multipleExposedInput
FilterPluginBase::operatorForm protected function Options form subform for setting the operator. 6
FilterPluginBase::operatorSubmit public function Perform any necessary changes to the form values prior to storage.
FilterPluginBase::operatorValidate protected function Validate the operator form.
FilterPluginBase::prepareFilterSelectOptions protected function Sanitizes the HTML select element's options.
FilterPluginBase::RESTRICTED_IDENTIFIERS constant A list of restricted identifiers.
FilterPluginBase::showBuildGroupButton protected function Shortcut to display the build_group/hide button.
FilterPluginBase::showBuildGroupForm public function Shortcut to display the exposed options form.
FilterPluginBase::showExposeButton public function Shortcut to display the expose/hide button. Overrides HandlerBase::showExposeButton
FilterPluginBase::showOperatorForm public function Shortcut to display the operator form.
FilterPluginBase::showValueForm protected function Shortcut to display the value form.
FilterPluginBase::storeExposedInput public function If set to remember exposed input in the session, store it there. Overrides HandlerBase::storeExposedInput
FilterPluginBase::storeGroupInput public function If set to remember exposed input in the session, store it there.
FilterPluginBase::submitOptionsForm public function Simple submit handler. Overrides PluginBase::submitOptionsForm
FilterPluginBase::trustedCallbacks public static function Lists the trusted callbacks provided by the implementing class. Overrides PluginBase::trustedCallbacks
FilterPluginBase::validateExposeForm public function Validate the options form. Overrides HandlerBase::validateExposeForm
FilterPluginBase::validateIdentifier protected function Validates a filter identifier.
FilterPluginBase::validateOptionsForm public function Simple validate handler. Overrides PluginBase::validateOptionsForm 1
FilterPluginBase::valueValidate protected function Validate the options form. 3
HandlerBase::$field public property With field you can override the realField if the real field is not set.
HandlerBase::$is_handler public property
HandlerBase::$moduleHandler protected property The module handler. 2
HandlerBase::$query public property Where the $query object will reside. 7
HandlerBase::$realField public property The real field.
HandlerBase::$relationship public property The relationship used for this field.
HandlerBase::$table public property The table this handler is attached to.
HandlerBase::$tableAlias public property The alias of the table of this handler which is used in the query.
HandlerBase::$viewsData protected property The views data service.
HandlerBase::access public function Check whether given user has access to this handler. Overrides ViewsHandlerInterface::access 5
HandlerBase::adminLabel public function Return a string representing this handler's name in the UI. Overrides ViewsHandlerInterface::adminLabel 4
HandlerBase::breakString public static function Breaks x,y,z and x+y+z into an array. Overrides ViewsHandlerInterface::breakString
HandlerBase::broken public function Determines if the handler is considered 'broken'. Overrides ViewsHandlerInterface::broken
HandlerBase::buildGroupByForm public function Provide a form for aggregation settings. 1
HandlerBase::caseTransform protected function Transform a string by a certain method.
HandlerBase::defineExtraOptions public function Provide defaults for the handler.
HandlerBase::displayExposedForm public function Displays the Expose form.
HandlerBase::getDateField public function Creates cross-database SQL dates. 2
HandlerBase::getDateFormat public function Creates cross-database SQL date formatting. 2
HandlerBase::getEntityType public function Determines the entity type used by this handler. Overrides ViewsHandlerInterface::getEntityType
HandlerBase::getField public function Shortcut to get a handler's raw field value. Overrides ViewsHandlerInterface::getField
HandlerBase::getJoin public function Get the join object that should be used for this handler. Overrides ViewsHandlerInterface::getJoin
HandlerBase::getModuleHandler protected function Gets the module handler.
HandlerBase::getTableJoin public static function Fetches a handler to join one table to a primary table from the data cache. Overrides ViewsHandlerInterface::getTableJoin
HandlerBase::getViewsData protected function Gets views data service.
HandlerBase::isExposed public function Determine if this item is 'exposed'.
HandlerBase::placeholder protected function Provides a unique placeholders for handlers.
HandlerBase::postExecute public function Run after the view is executed, before the result is cached. Overrides ViewsHandlerInterface::postExecute
HandlerBase::preQuery public function Run before the view is built. Overrides ViewsHandlerInterface::preQuery 2
HandlerBase::sanitizeValue public function Sanitize the value for output. Overrides ViewsHandlerInterface::sanitizeValue
HandlerBase::setModuleHandler public function Sets the module handler.
HandlerBase::setRelationship public function Sets up any needed relationship. Overrides ViewsHandlerInterface::setRelationship
HandlerBase::setViewsData public function
HandlerBase::showExposeForm public function Shortcut to display the exposed options form. Overrides ViewsHandlerInterface::showExposeForm
HandlerBase::submitExposed public function Submit the exposed handler form.
HandlerBase::submitExposeForm public function Perform any necessary changes to the form exposes prior to storage.
HandlerBase::submitFormCalculateOptions public function Calculates options stored on the handler. 1
HandlerBase::submitGroupByForm public function Perform any necessary changes to the form values prior to storage. 1
HandlerBase::submitTemporaryForm public function Submits a temporary form.
HandlerBase::usesGroupBy public function Provides the handler some groupby. 13
InOperator::$valueOptions protected property Stores all operations which are available on the form.
InOperator::$valueTitle protected property The filter title.
InOperator::adminSummary public function Display the filter on the administrative summary. Overrides FilterPluginBase::adminSummary 2
InOperator::buildExposeForm public function Options form subform for exposed filter options. Overrides FilterPluginBase::buildExposeForm 1
InOperator::defaultExposeOptions public function Provide default options for exposed filters. Overrides FilterPluginBase::defaultExposeOptions
InOperator::getValueOptions public function Gets the value options. 10
InOperator::opEmpty protected function
InOperator::operatorOptions public function Build strings from the operators() for 'select' options. Overrides FilterPluginBase::operatorOptions 1
InOperator::operatorValues protected function
InOperator::opSimple protected function 1
InOperator::query public function Add this filter to the query. Overrides FilterPluginBase::query 6
InOperator::reduceValueOptions public function When using exposed filters, we may be required to reduce the set.
ManyToOne::$helper public property Stores the Helper object which handles the many_to_one complexity.
ManyToOne::$valueFormType protected property Overrides InOperator::$valueFormType
ManyToOne::ensureMyTable public function Ensures that the main table for this handler is in the query. Overrides HandlerBase::ensureMyTable
ManyToOne::operators public function Returns an array of operator information, keyed by operator ID. Overrides InOperator::operators 1
ManyToOne::opHelper protected function
PluginBase::$definition public property Plugins' definition.
PluginBase::$displayHandler public property The display object this plugin is for.
PluginBase::$options public property Options for this plugin will be held here.
PluginBase::$position public property The handler position.
PluginBase::$renderer protected property Stores the render API renderer. 3
PluginBase::$usesOptions protected property Denotes whether the plugin has an additional options form. 8
PluginBase::$view public property The top object of a view. 1
PluginBase::destroy public function Clears a plugin. Overrides ViewsPluginInterface::destroy 2
PluginBase::doFilterByDefinedOptions protected function Do the work to filter out stored options depending on the defined options.
PluginBase::filterByDefinedOptions public function Filter out stored options depending on the defined options. Overrides ViewsPluginInterface::filterByDefinedOptions
PluginBase::getAvailableGlobalTokens public function Returns an array of available token replacements. Overrides ViewsPluginInterface::getAvailableGlobalTokens
PluginBase::getProvider public function Returns the plugin provider. Overrides ViewsPluginInterface::getProvider
PluginBase::getRenderer protected function Returns the render API renderer. 1
PluginBase::globalTokenForm public function Adds elements for available core tokens to a form. Overrides ViewsPluginInterface::globalTokenForm
PluginBase::globalTokenReplace public function Returns a string with any core tokens replaced. Overrides ViewsPluginInterface::globalTokenReplace
PluginBase::INCLUDE_ENTITY constant Include entity row languages when listing languages.
PluginBase::INCLUDE_NEGOTIATED constant Include negotiated languages when listing languages.
PluginBase::listLanguages protected function Makes an array of languages, optionally including special languages.
PluginBase::pluginTitle public function Return the human readable name of the display. Overrides ViewsPluginInterface::pluginTitle
PluginBase::preRenderAddFieldsetMarkup public static function Moves form elements into fieldsets for presentation purposes. Overrides ViewsPluginInterface::preRenderAddFieldsetMarkup
PluginBase::preRenderFlattenData public static function Flattens the structure of form elements. Overrides ViewsPluginInterface::preRenderFlattenData
PluginBase::queryLanguageSubstitutions public static function Returns substitutions for Views queries for languages.
PluginBase::setOptionDefaults protected function Fills up the options of the plugin with defaults.
PluginBase::summaryTitle public function Returns the summary of the settings in the display. Overrides ViewsPluginInterface::summaryTitle 6
PluginBase::themeFunctions public function Provide a full list of possible theme templates used by this style. Overrides ViewsPluginInterface::themeFunctions 1
PluginBase::unpackOptions public function Unpacks options over our existing defaults. Overrides ViewsPluginInterface::unpackOptions
PluginBase::usesOptions public function Returns the usesOptions property. Overrides ViewsPluginInterface::usesOptions 8
PluginBase::viewsTokenReplace protected function Replaces Views' tokens in a given string. 1
PluginBase::VIEWS_QUERY_LANGUAGE_SITE_DEFAULT constant Query string to indicate the site default language.
PluginInspectionInterface::getPluginDefinition public function Gets the definition of the plugin implementation. 6
PluginInspectionInterface::getPluginId public function Gets the plugin ID of the plugin instance. 2
TrustedCallbackInterface::THROW_EXCEPTION constant Untrusted callbacks throw exceptions.
TrustedCallbackInterface::TRIGGER_SILENCED_DEPRECATION constant Untrusted callbacks trigger silenced E_USER_DEPRECATION errors.

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