You are here

class View in Entity Browser 8

Same name in this branch
  1. 8 src/Plugin/EntityBrowser/Widget/View.php \Drupal\entity_browser\Plugin\EntityBrowser\Widget\View
  2. 8 src/Plugin/EntityBrowser/SelectionDisplay/View.php \Drupal\entity_browser\Plugin\EntityBrowser\SelectionDisplay\View
Same name and namespace in other branches
  1. 8.2 src/Plugin/EntityBrowser/Widget/View.php \Drupal\entity_browser\Plugin\EntityBrowser\Widget\View

Uses a view to provide entity listing in a browser's widget.

Plugin annotation


@EntityBrowserWidget(
  id = "view",
  label = @Translation("View"),
  provider = "views",
  description = @Translation("Uses a view to provide entity listing in a browser's widget."),
  auto_select = TRUE
)

Hierarchy

Expanded class hierarchy of View

File

src/Plugin/EntityBrowser/Widget/View.php, line 31

Namespace

Drupal\entity_browser\Plugin\EntityBrowser\Widget
View source
class View extends WidgetBase implements ContainerFactoryPluginInterface {

  /**
   * The current user.
   *
   * @var \Drupal\Core\Session\AccountInterface
   */
  protected $currentUser;

  /**
   * {@inheritdoc}
   */
  public function defaultConfiguration() {
    return [
      'view' => NULL,
      'view_display' => NULL,
    ] + parent::defaultConfiguration();
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static($configuration, $plugin_id, $plugin_definition, $container
      ->get('event_dispatcher'), $container
      ->get('entity_type.manager'), $container
      ->get('plugin.manager.entity_browser.widget_validation'), $container
      ->get('current_user'));
  }

  /**
   * Constructs a new View object.
   *
   * @param array $configuration
   *   A configuration array containing information about the plugin instance.
   * @param string $plugin_id
   *   The plugin_id for the plugin instance.
   * @param mixed $plugin_definition
   *   The plugin implementation definition.
   * @param \Symfony\Component\EventDispatcher\EventDispatcherInterface $event_dispatcher
   *   Event dispatcher service.
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity type manager.
   * @param \Drupal\entity_browser\WidgetValidationManager $validation_manager
   *   The Widget Validation Manager service.
   * @param \Drupal\Core\Session\AccountInterface $current_user
   *   The current user.
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, EventDispatcherInterface $event_dispatcher, EntityTypeManagerInterface $entity_type_manager, WidgetValidationManager $validation_manager, AccountInterface $current_user) {
    parent::__construct($configuration, $plugin_id, $plugin_definition, $event_dispatcher, $entity_type_manager, $validation_manager);
    $this->currentUser = $current_user;
  }

  /**
   * {@inheritdoc}
   */
  public function getForm(array &$original_form, FormStateInterface $form_state, array $additional_widget_parameters) {
    $form = parent::getForm($original_form, $form_state, $additional_widget_parameters);

    // TODO - do we need better error handling for view and view_display (in
    // case either of those is nonexistent or display not of correct type)?
    $form['#attached']['library'] = [
      'entity_browser/view',
    ];

    /** @var \Drupal\views\ViewExecutable $view */
    $view = $this->entityTypeManager
      ->getStorage('view')
      ->load($this->configuration['view'])
      ->getExecutable();
    if (!empty($this->configuration['arguments'])) {
      if (!empty($additional_widget_parameters['path_parts'])) {
        $arguments = [];

        // Map configuration arguments with original path parts.
        foreach ($this->configuration['arguments'] as $argument) {
          $arguments[] = isset($additional_widget_parameters['path_parts'][$argument]) ? $additional_widget_parameters['path_parts'][$argument] : '';
        }
        $view
          ->setArguments(array_values($arguments));
      }
    }
    $form['view'] = $view
      ->executeDisplay($this->configuration['view_display']);
    if (empty($view->field['entity_browser_select'])) {
      $url = Url::fromRoute('entity.view.edit_form', [
        'view' => $this->configuration['view'],
      ])
        ->toString();
      if ($this->currentUser
        ->hasPermission('administer views')) {
        return [
          '#markup' => $this
            ->t('Entity browser select form field not found on a view. <a href=":link">Go fix it</a>!', [
            ':link' => $url,
          ]),
        ];
      }
      else {
        return [
          '#markup' => $this
            ->t('Entity browser select form field not found on a view. Go fix it!'),
        ];
      }
    }

    // When rebuilding makes no sense to keep checkboxes that were previously
    // selected.
    if (!empty($form['view']['entity_browser_select'])) {
      foreach (Element::children($form['view']['entity_browser_select']) as $child) {
        $form['view']['entity_browser_select'][$child]['#process'][] = [
          '\\Drupal\\entity_browser\\Plugin\\EntityBrowser\\Widget\\View',
          'processCheckbox',
        ];
        $form['view']['entity_browser_select'][$child]['#process'][] = [
          '\\Drupal\\Core\\Render\\Element\\Checkbox',
          'processAjaxForm',
        ];
        $form['view']['entity_browser_select'][$child]['#process'][] = [
          '\\Drupal\\Core\\Render\\Element\\Checkbox',
          'processGroup',
        ];
      }
    }
    $form['view']['view'] = [
      '#markup' => \Drupal::service('renderer')
        ->render($form['view']['view']),
    ];
    return $form;
  }

  /**
   * Sets the #checked property when rebuilding form.
   *
   * Every time when we rebuild we want all checkboxes to be unchecked.
   *
   * @see \Drupal\Core\Render\Element\Checkbox::processCheckbox()
   */
  public static function processCheckbox(&$element, FormStateInterface $form_state, &$complete_form) {
    if ($form_state
      ->isRebuilding()) {
      $element['#checked'] = FALSE;
    }
    return $element;
  }

  /**
   * {@inheritdoc}
   */
  public function validate(array &$form, FormStateInterface $form_state) {
    $user_input = $form_state
      ->getUserInput();
    if (isset($user_input['entity_browser_select'])) {
      if (is_array($user_input['entity_browser_select'])) {
        $selected_rows = array_values(array_filter($user_input['entity_browser_select']));
      }
      else {
        $selected_rows = [
          $user_input['entity_browser_select'],
        ];
      }
      $use_field_cardinality = !empty($user_input['entity_browser_select_form_metadata']['use_field_cardinality']);
      if ($use_field_cardinality) {
        $cardinality = !empty($user_input['entity_browser_select_form_metadata']['cardinality']) ? $user_input['entity_browser_select_form_metadata']['cardinality'] : 0;
        if ($cardinality > 0 && count($selected_rows) > $cardinality) {
          $message = $this
            ->formatPlural($cardinality, 'You can only select one item.', 'You can only select up to @number items.', [
            '@number' => $cardinality,
          ]);
          $form_state
            ->setError($form['widget']['view']['entity_browser_select'], $message);
        }
      }
      foreach ($selected_rows as $row) {

        // Verify that the user input is a string and split it.
        // Each $row is in the format entity_type:id.
        if (is_string($row) && ($parts = explode(':', $row, 2))) {

          // Make sure we have a type and id present.
          if (count($parts) == 2) {
            try {
              $storage = $this->entityTypeManager
                ->getStorage($parts[0]);
              if (!$storage
                ->load($parts[1])) {
                $message = $this
                  ->t('The @type Entity @id does not exist.', [
                  '@type' => $parts[0],
                  '@id' => $parts[1],
                ]);
                $form_state
                  ->setError($form['widget']['view']['entity_browser_select'], $message);
              }
            } catch (PluginNotFoundException $e) {
              $message = $this
                ->t('The Entity Type @type does not exist.', [
                '@type' => $parts[0],
              ]);
              $form_state
                ->setError($form['widget']['view']['entity_browser_select'], $message);
            }
          }
        }
      }

      // If there weren't any errors set, run the normal validators.
      if (empty($form_state
        ->getErrors())) {
        parent::validate($form, $form_state);
      }
    }
  }

  /**
   * {@inheritdoc}
   */
  protected function prepareEntities(array $form, FormStateInterface $form_state) {
    if (is_array($form_state
      ->getUserInput()['entity_browser_select'])) {
      $selected_rows = array_values(array_filter($form_state
        ->getUserInput()['entity_browser_select']));
    }
    else {
      $selected_rows = [
        $form_state
          ->getUserInput()['entity_browser_select'],
      ];
    }
    $entities = [];
    foreach ($selected_rows as $row) {
      $item = explode(':', $row);
      if (count($item) == 2) {
        list($type, $id) = $item;
        $storage = $this->entityTypeManager
          ->getStorage($type);
        if ($entity = $storage
          ->load($id)) {
          $entities[] = $entity;
        }
      }
    }
    return $entities;
  }

  /**
   * {@inheritdoc}
   */
  public function submit(array &$element, array &$form, FormStateInterface $form_state) {
    $entities = $this
      ->prepareEntities($form, $form_state);
    $this
      ->selectEntities($entities, $form_state);
  }

  /**
   * {@inheritdoc}
   */
  public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
    $form = parent::buildConfigurationForm($form, $form_state);
    $options = [];

    // Get only those enabled Views that have entity_browser displays.
    $displays = Views::getApplicableViews('entity_browser_display');
    foreach ($displays as $display) {
      list($view_id, $display_id) = $display;
      $view = $this->entityTypeManager
        ->getStorage('view')
        ->load($view_id);
      $options[$view_id . '.' . $display_id] = $this
        ->t('@view : @display', [
        '@view' => $view
          ->label(),
        '@display' => $view
          ->get('display')[$display_id]['display_title'],
      ]);
    }
    $form['view'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('View : View display'),
      '#default_value' => $this->configuration['view'] . '.' . $this->configuration['view_display'],
      '#options' => $options,
      '#empty_option' => $this
        ->t('- Select a view -'),
      '#required' => TRUE,
    ];
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
    $values = $form_state
      ->getValues()['table'][$this
      ->uuid()]['form'];
    $this->configuration['submit_text'] = $values['submit_text'];
    $this->configuration['auto_select'] = $values['auto_select'];
    if (!empty($values['view'])) {
      list($view_id, $display_id) = explode('.', $values['view']);
      $this->configuration['view'] = $view_id;
      $this->configuration['view_display'] = $display_id;
    }
  }

  /**
   * {@inheritdoc}
   */
  public function calculateDependencies() {
    $dependencies = [];
    if ($this->configuration['view']) {
      $view = ViewEntity::load($this->configuration['view']);
      $dependencies[$view
        ->getConfigDependencyKey()] = [
        $view
          ->getConfigDependencyName(),
      ];
    }
    return $dependencies;
  }

  /**
   * {@inheritdoc}
   */
  public function access() {

    // Mark the widget as not visible if the user has no access to the view.

    /** @var \Drupal\views\ViewExecutable $view */
    $view = $this->entityTypeManager
      ->getStorage('view')
      ->load($this->configuration['view'])
      ->getExecutable();

    // Check if the current user has access to this view.
    return AccessResult::allowedIf($view
      ->access($this->configuration['view_display']));
  }

}

Members

Namesort descending Modifiers Type Description 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
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
PluginBase::$configuration protected property Configuration information passed into the plugin. 1
PluginBase::$pluginDefinition protected property The plugin implementation definition. 1
PluginBase::$pluginId protected property The plugin_id.
PluginBase::DERIVATIVE_SEPARATOR constant A string which is used to separate base plugin IDs from the derivative ID.
PluginBase::getBaseId public function Gets the base_plugin_id of the plugin instance. Overrides DerivativeInspectionInterface::getBaseId
PluginBase::getDerivativeId public function Gets the derivative_id of the plugin instance. Overrides DerivativeInspectionInterface::getDerivativeId
PluginBase::getPluginDefinition public function Gets the definition of the plugin implementation. Overrides PluginInspectionInterface::getPluginDefinition 3
PluginBase::getPluginId public function Gets the plugin_id of the plugin instance. Overrides PluginInspectionInterface::getPluginId
PluginBase::isConfigurable public function Determines if the plugin is configurable.
PluginConfigurationFormTrait::validateConfigurationForm public function Implements PluginFormInterface::validateConfigurationForm(). 2
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
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.
View::$currentUser protected property The current user.
View::access public function Defines if the widget is visible / accessible in a given context. Overrides WidgetBase::access
View::buildConfigurationForm public function Implements PluginFormInterface::buildConfigurationForm(). Overrides WidgetBase::buildConfigurationForm
View::calculateDependencies public function Calculates dependencies for the configured plugin. Overrides WidgetBase::calculateDependencies
View::create public static function Creates an instance of the plugin. Overrides WidgetBase::create
View::defaultConfiguration public function Gets default configuration for this plugin. Overrides WidgetBase::defaultConfiguration
View::getForm public function Returns widget form. Overrides WidgetBase::getForm
View::prepareEntities protected function Prepares the entities without saving them. Overrides WidgetBase::prepareEntities
View::processCheckbox public static function Sets the #checked property when rebuilding form.
View::submit public function Submits form. Overrides WidgetBase::submit
View::submitConfigurationForm public function Implements PluginFormInterface::submitConfigurationForm(). Overrides PluginConfigurationFormTrait::submitConfigurationForm
View::validate public function Validates form. Overrides WidgetBase::validate
View::__construct public function Constructs a new View object. Overrides WidgetBase::__construct
WidgetBase::$entityTypeManager protected property Entity type manager service.
WidgetBase::$eventDispatcher protected property Event dispatcher service.
WidgetBase::$id protected property Plugin id.
WidgetBase::$label protected property Plugin label.
WidgetBase::$uuid protected property Plugin uuid.
WidgetBase::$validationManager protected property The Widget Validation Manager service.
WidgetBase::$weight protected property Plugin weight.
WidgetBase::getConfiguration public function Gets this plugin's configuration. Overrides ConfigurableInterface::getConfiguration
WidgetBase::getWeight public function Returns the widget's weight. Overrides WidgetInterface::getWeight
WidgetBase::handleWidgetContext protected function Allow configuration overrides at runtime based on widget context passed to this widget from the Entity Browser element.
WidgetBase::id public function Returns the widget id. Overrides WidgetInterface::id
WidgetBase::label public function Returns the widget label. Overrides WidgetInterface::label
WidgetBase::requiresJsCommands public function Returns if widget requires JS commands support by selection display. Overrides WidgetInterface::requiresJsCommands
WidgetBase::runWidgetValidators protected function Run widget validators.
WidgetBase::selectEntities protected function Dispatches event that informs all subscribers about new selected entities.
WidgetBase::setConfiguration public function Sets the configuration for this plugin instance. Overrides ConfigurableInterface::setConfiguration
WidgetBase::setLabel public function Sets the widget's label. Overrides WidgetInterface::setLabel
WidgetBase::setWeight public function Sets the widget's weight. Overrides WidgetInterface::setWeight
WidgetBase::uuid public function Returns the widget UUID. Overrides WidgetInterface::uuid