You are here

class GridWidget in Paragraphs grid 8

Plugin implementation of the 'grid_widget' widget.

Plugin annotation


@FieldWidget(
  id = "grid_widget",
  label = @Translation("Grid widget"),
  field_types = {
    "grid_field_type"
  },
  multiple_values = FALSE,
)

Hierarchy

Expanded class hierarchy of GridWidget

File

src/Plugin/Field/FieldWidget/GridWidget.php, line 31

Namespace

Drupal\paragraphs_grid\Plugin\Field\FieldWidget
View source
class GridWidget extends WidgetBase implements ContainerFactoryPluginInterface {

  /**
   * The paragraphs_grid settings from config form used for the site.
   *
   * @var \Drupal\Core\Config\ImmutableConfig
   */
  protected $moduleConfig;

  /**
   * The grid config entity used for the site.
   *
   * @var \Drupal\Core\Config\ImmutableConfig
   */
  protected $gridConfig;

  /**
   * The current users account proxy.
   *
   * @var \Drupal\Core\Session\AccountProxyInterface
   */
  protected $currentUser;

  /**
   * The entity display repository from drupal.
   *
   * @var \Drupal\Core\Entity\EntityDisplayRepository
   */
  protected $entityDisplayRepository;

  /**
   * Constructs a WidgetBase object.
   *
   * @param string $plugin_id
   *   The plugin_id for the widget.
   * @param mixed $plugin_definition
   *   The plugin implementation definition.
   * @param \Drupal\Core\Field\FieldDefinitionInterface $field_definition
   *   The definition of the field to which the widget is associated.
   * @param array $settings
   *   The widget settings.
   * @param array $third_party_settings
   *   Any third party settings.
   * @param \Drupal\Core\Config\ConfigFactory $config_factory
   *   Drupal config factory.
   * @param \Drupal\Core\Session\AccountProxyInterface $current_user
   *   Current Drupal user.
   * @param \Drupal\Core\Entity\EntityDisplayRepository $entity_display_repository
   *   Entity display repository, to get view modes by bundle.
   */
  public function __construct($plugin_id, $plugin_definition, FieldDefinitionInterface $field_definition, array $settings, array $third_party_settings, ConfigFactory $config_factory, AccountProxyInterface $current_user, EntityDisplayRepository $entity_display_repository) {
    parent::__construct($plugin_id, $plugin_definition, $field_definition, $settings, $third_party_settings);
    $this->moduleConfig = $config_factory
      ->get('paragraphs_grid.settings');
    $this->gridConfig = $config_factory
      ->get($this->moduleConfig
      ->get('gridtype'));
    $this->currentUser = $current_user;
    $this->entityDisplayRepository = $entity_display_repository;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static($plugin_id, $plugin_definition, $configuration['field_definition'], $configuration['settings'], $configuration['third_party_settings'], $container
      ->get('config.factory'), $container
      ->get('current_user'), $container
      ->get('entity_display.repository'));
  }

  /**
   * {@inheritdoc}
   */
  public static function defaultSettings() {
    return [
      'excluded_view_modes' => [
        'preview',
      ],
    ] + parent::defaultSettings();
  }

  /**
   * {@inheritdoc}
   */
  public function settingsForm(array $form, FormStateInterface $form_state) {
    $view_mode_options = $this
      ->getViewModeOptions(FALSE);
    $elements = [
      'excluded_view_modes' => [
        '#type' => 'checkboxes',
        '#title' => $this
          ->t('Excluded view mode'),
        '#default_value' => $this
          ->getSetting('excluded_view_modes'),
        '#options' => $view_mode_options,
        '#description' => $this
          ->t('Checked view modes will NOT be available in the paragraph form.'),
      ],
    ];
    return $elements;
  }

  /**
   * {@inheritdoc}
   */
  public function settingsSummary() {
    $summary = [];
    $all_view_modes = implode(', ', $this
      ->getSetting('excluded_view_modes'));
    $summary[] = $this
      ->t('Excluded view modes: @view_modes', [
      '@view_modes' => $all_view_modes,
    ]);
    return $summary;
  }

  /**
   * Returns module config settings by name.
   *
   * @param string $name
   *   The config key.
   *
   * @return array|mixed|null
   *   The config value from module config.
   */
  protected function getModuleConfig($name = '') {
    return $this->moduleConfig
      ->get($name);
  }

  /**
   * Returns grid config settings by name.
   *
   * @param string $name
   *   The config key.
   *
   * @return array|mixed|null
   *   The config value from grid config.
   */
  protected function getGridConfig($name = '') {
    return $this->gridConfig
      ->get($name);
  }

  /**
   * Breakoint definition from grid config.
   *
   * @return array|mixed|null
   *   Breakoint definition.
   */
  protected function getBreakpoints() {
    return $this
      ->getGridConfig('breakpoints');
  }

  /**
   * Returns cell property definition (like offset, order ...) from grid config.
   *
   * @param bool|string $key
   *   If set method returns a special property or all if not.
   *
   * @return mixed
   *   Properties definition.
   */
  protected function getCellProperties($key = FALSE) {
    $this
      ->getGridConfig('cell-properties');
    $properties = $this
      ->getGridConfig('cell-properties');
    return $key ? $properties[$key] : $properties;
  }

  /**
   * Returns view modes as options for a select form field.
   *
   * @param bool $filtered
   *   If view modes should be filtered from excluded view modes or not.
   *
   * @return array
   *   View mode options for a select form field.
   */
  public function getViewModeOptions($filtered = TRUE) {
    $type = $this->fieldDefinition
      ->getTargetEntityTypeId();
    $bundle = $this->fieldDefinition
      ->getTargetBundle();
    $view_modes = $filtered ? [
      '' => $this
        ->t('default'),
    ] : [];
    $view_modes += $this->entityDisplayRepository
      ->getViewModeOptionsByBundle($type, $bundle);
    unset($view_modes['default']);
    if ($filtered) {
      foreach ($this
        ->getSetting('excluded_view_modes') as $exclude) {
        unset($view_modes[$exclude]);
      }
    }
    return $view_modes;
  }

  /**
   * Returns options for a select form field.
   *
   * @param string $breakpoint
   *   Current breakpoint.
   * @param int $col_num
   *   Number of columns to generate classes.
   * @param array $definition
   *   Definition of the cell property.
   *
   * @return array
   *   Form select options.
   */
  protected function getGridOptions($breakpoint, $col_num, array $definition) {
    $options = [];
    if ($definition['asc']) {
      for ($count = 0; $count <= $col_num; $count++) {
        $css_class = str_replace([
          '%cols',
          '%bp',
        ], [
          $count,
          $breakpoint,
        ], $definition['formatter']);
        $options[$css_class] = "{$count}";
      }
    }
    else {
      $count = $col_num;
      while ($count >= 1) {
        $css_class = str_replace([
          '%cols',
          '%bp',
        ], [
          $count,
          $breakpoint,
        ], $definition['formatter']);
        $options[$css_class] = "{$count}";
        $count--;
      }
    }
    if (isset($definition['additional'])) {
      foreach ($definition['additional'] as $add_opts) {
        $css_class = str_replace('%bp', $breakpoint, $add_opts['class']);
        $options[$css_class] = $add_opts['name'];
      }
    }
    return $options;
  }

  /**
   * Generate select form field for css classes.
   *
   * @param array $bp_definition
   *   The config definition of the breakpoints.
   * @param array $definition
   *   The grid definition.
   * @param array $defaults
   *   The current field value.
   *
   * @return array
   *   Render array of a select form field for grid classes.
   */
  protected function getGridSelector(array $bp_definition, array $definition, array $defaults = []) {
    $options = $this
      ->getGridOptions($bp_definition['fragment'], $bp_definition['cols'], $definition);
    $default_values = array_intersect($defaults, array_keys($options));
    $select = [
      '#type' => 'select',
      '#title' => $definition['label'],
      '#size' => 1,
      '#default_value' => reset($default_values),
      '#options' => $options,
    ];
    if (!$definition['default']) {
      $select['#empty_value'] = '';
      $select['#empty_option'] = '';
    }
    return $select;
  }

  /**
   * {@inheritdoc}
   */
  public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {

    // The grid widget toggle button.
    $element['open_button'] = [
      '#theme' => 'pg_button',
      '#icon' => 'view_quilt',
      '#label' => $this
        ->t('Grid'),
      '#attributes' => new Attribute([
        'data-toggle' => 'pg-widget-container',
        'class' => [
          'btn-toggle-widget',
        ],
      ]),
    ];
    $element['opener'] = [
      '#type' => 'hidden',
      '#default_value' => $form_state
        ->get('opener'),
    ];

    // The grid widget container.
    $element['subform_container'] = [
      '#type' => 'container',
      '#attributes' => [
        'class' => [
          'pg-widget-container',
        ],
      ],
    ];
    $defaults = explode(' ', $items[$delta]->value);
    $cell_properties = $this
      ->getCellProperties();
    $view_properties = array_values($this
      ->getFieldSetting('optional'));
    foreach ($this
      ->getBreakpoints() as $breakpoint => $bp_definition) {
      $element['subform_container'][$breakpoint] = [
        '#type' => 'container',
        '#attributes' => [
          'class' => [
            'pg-widget-bpoint',
            'bp-' . $breakpoint,
          ],
        ],
        'header' => [
          '#theme' => 'pg_bpoint_col_header',
          '#name' => $bp_definition['name'],
          '#size' => $bp_definition['bpoint'],
          '#attributes' => new Attribute([
            'class' => [
              'pg-bp-header',
            ],
          ]),
          '#icon_attributes' => new Attribute([
            'class' => [
              'pg-icon',
              $bp_definition['icon'],
            ],
          ]),
        ],
      ];
      $name = 'col_' . $bp_definition['cols'];
      foreach ($cell_properties as $option => $definition) {
        if ($definition['optional'] === FALSE || in_array($option, $view_properties, TRUE)) {
          $element['subform_container'][$breakpoint][$name . "_{$option}"] = $this
            ->getGridSelector($bp_definition, $definition, $defaults);
        }
      }
    }

    // Conditions to display view mode selector.
    $view_modes_enabled = $this->fieldDefinition
      ->getFieldStorageDefinition()
      ->getSetting('view_modes_enabled');

    // Display view mode selector if conditions full filled.
    if ($view_modes_enabled) {

      // Link to create new view modes.
      $vm_link = '';
      if ($this->currentUser
        ->hasPermission('administer display modes')) {
        $vm_link = new Link($this
          ->t('Add view mode'), new Url('entity.entity_view_mode.add_form', [
          'entity_type_id' => 'paragraph',
        ]));
      }
      $view_mode_options = $this
        ->getViewModeOptions();

      // Display view mode selector.
      $element['subform_container']['view_mode_wrap'] = [
        '#type' => 'container',
        '#attributes' => [
          'class' => [
            'pg-widget-view-mode',
          ],
        ],
      ];
      if (count($view_mode_options) > 1) {
        $full_value = $items[$delta]
          ->getValue();
        $element['subform_container']['view_mode_wrap']['view_mode'] = [
          '#type' => 'select',
          '#title' => $this
            ->t('View mode'),
          '#size' => 1,
          '#default_value' => isset($full_value['view_mode']) ? $full_value['view_mode'] : NULL,
          '#options' => $view_mode_options,
          '#description' => $this
            ->t('Select the view mode for this paragraph. @link', [
            '@link' => $vm_link ? $vm_link
              ->toString() : '',
          ]),
        ];
      }
      else {
        $element['subform_container']['view_mode_wrap']['view_mode_remark'] = [
          '#markup' => new TranslatableMarkup('<p>No view modes to select found (except "default") for paragraph type %type. @link</p>', [
            '%type' => $this->fieldDefinition
              ->getTargetBundle(),
            '@link' => $vm_link ? $vm_link
              ->toString() : '',
          ]),
        ];
      }
    }
    return $element;
  }

  /**
   * {@inheritdoc}
   */
  public function massageFormValues(array $values, array $form, FormStateInterface $form_state) {
    $result = [];
    $collector = [];
    foreach ($values as $key => $value) {
      foreach ($value['subform_container'] as $breakpoint => $cols) {
        if ($breakpoint == 'view_mode_wrap') {
          $result[$key]['view_mode'] = $cols['view_mode'] ?: NULL;
          continue;
        }
        $collector = array_merge($collector, array_values(array_filter($cols)));
      }
      $result[$key]['value'] = implode(' ', $collector);
    }
    return $result;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
AllowedTagsXssTrait::allowedTags public function Returns a list of tags allowed by AllowedTagsXssTrait::fieldFilterXss().
AllowedTagsXssTrait::displayAllowedTags public function Returns a human-readable list of allowed tags for display in help texts.
AllowedTagsXssTrait::fieldFilterXss public function Filters an HTML string to prevent XSS vulnerabilities.
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
GridWidget::$currentUser protected property The current users account proxy.
GridWidget::$entityDisplayRepository protected property The entity display repository from drupal.
GridWidget::$gridConfig protected property The grid config entity used for the site.
GridWidget::$moduleConfig protected property The paragraphs_grid settings from config form used for the site.
GridWidget::create public static function Creates an instance of the plugin. Overrides WidgetBase::create
GridWidget::defaultSettings public static function Defines the default settings for this plugin. Overrides PluginSettingsBase::defaultSettings
GridWidget::formElement public function Returns the form for a single field widget. Overrides WidgetInterface::formElement
GridWidget::getBreakpoints protected function Breakoint definition from grid config.
GridWidget::getCellProperties protected function Returns cell property definition (like offset, order ...) from grid config.
GridWidget::getGridConfig protected function Returns grid config settings by name.
GridWidget::getGridOptions protected function Returns options for a select form field.
GridWidget::getGridSelector protected function Generate select form field for css classes.
GridWidget::getModuleConfig protected function Returns module config settings by name.
GridWidget::getViewModeOptions public function Returns view modes as options for a select form field.
GridWidget::massageFormValues public function Massages the form values into the format expected for field values. Overrides WidgetBase::massageFormValues
GridWidget::settingsForm public function Returns a form to configure settings for the widget. Overrides WidgetBase::settingsForm
GridWidget::settingsSummary public function Returns a short summary for the current widget settings. Overrides WidgetBase::settingsSummary
GridWidget::__construct public function Constructs a WidgetBase object. Overrides WidgetBase::__construct
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.
PluginSettingsBase::$defaultSettingsMerged protected property Whether default settings have been merged into the current $settings.
PluginSettingsBase::$thirdPartySettings protected property The plugin settings injected by third party modules.
PluginSettingsBase::calculateDependencies public function Calculates dependencies for the configured plugin. Overrides DependentPluginInterface::calculateDependencies 6
PluginSettingsBase::getSetting public function Returns the value of a setting, or its default value if absent. Overrides PluginSettingsInterface::getSetting
PluginSettingsBase::getSettings public function Returns the array of settings, including defaults for missing settings. Overrides PluginSettingsInterface::getSettings
PluginSettingsBase::getThirdPartyProviders public function Gets the list of third parties that store information. Overrides ThirdPartySettingsInterface::getThirdPartyProviders
PluginSettingsBase::getThirdPartySetting public function Gets the value of a third-party setting. Overrides ThirdPartySettingsInterface::getThirdPartySetting
PluginSettingsBase::getThirdPartySettings public function Gets all third-party settings of a given module. Overrides ThirdPartySettingsInterface::getThirdPartySettings
PluginSettingsBase::mergeDefaults protected function Merges default settings values into $settings.
PluginSettingsBase::onDependencyRemoval public function Informs the plugin that some configuration it depends on will be deleted. Overrides PluginSettingsInterface::onDependencyRemoval 3
PluginSettingsBase::setSetting public function Sets the value of a setting for the plugin. Overrides PluginSettingsInterface::setSetting
PluginSettingsBase::setSettings public function Sets the settings for the plugin. Overrides PluginSettingsInterface::setSettings
PluginSettingsBase::setThirdPartySetting public function Sets the value of a third-party setting. Overrides ThirdPartySettingsInterface::setThirdPartySetting
PluginSettingsBase::unsetThirdPartySetting public function Unsets a third-party setting. Overrides ThirdPartySettingsInterface::unsetThirdPartySetting
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.
WidgetBase::$fieldDefinition protected property The field definition.
WidgetBase::$settings protected property The widget settings. Overrides PluginSettingsBase::$settings
WidgetBase::addMoreAjax public static function Ajax callback for the "Add another item" button.
WidgetBase::addMoreSubmit public static function Submission handler for the "Add another item" button.
WidgetBase::afterBuild public static function After-build handler for field elements in a form.
WidgetBase::errorElement public function Assigns a field-level validation error to the right widget sub-element. Overrides WidgetInterface::errorElement 8
WidgetBase::extractFormValues public function Extracts field values from submitted form values. Overrides WidgetBaseInterface::extractFormValues 2
WidgetBase::flagErrors public function Reports field-level validation errors against actual form elements. Overrides WidgetBaseInterface::flagErrors 2
WidgetBase::form public function Creates a form element for a field. Overrides WidgetBaseInterface::form 3
WidgetBase::formMultipleElements protected function Special handling to create form elements for multiple values. 1
WidgetBase::formSingleElement protected function Generates the form element for a single copy of the widget.
WidgetBase::getFieldSetting protected function Returns the value of a field setting.
WidgetBase::getFieldSettings protected function Returns the array of field settings.
WidgetBase::getFilteredDescription protected function Returns the filtered field description.
WidgetBase::getWidgetState public static function Retrieves processing information about the widget from $form_state. Overrides WidgetBaseInterface::getWidgetState
WidgetBase::getWidgetStateParents protected static function Returns the location of processing information within $form_state.
WidgetBase::handlesMultipleValues protected function Returns whether the widget handles multiple values.
WidgetBase::isApplicable public static function Returns if the widget can be used for the provided field. Overrides WidgetInterface::isApplicable 4
WidgetBase::isDefaultValueWidget protected function Returns whether the widget used for default value form.
WidgetBase::setWidgetState public static function Stores processing information about the widget in $form_state. Overrides WidgetBaseInterface::setWidgetState