You are here

class ViewsLayoutStyle in Views Layout 8

Style plugin for the timeline view.

Plugin annotation


@ViewsStyle(
  id = "views_layout_style",
  title = @Translation("Views Layout Grid"),
  help = @Translation("Displays content in a grid defined by a layout."),
  theme = "views_layout_style",
  display_types = {"normal"}
)

Hierarchy

Expanded class hierarchy of ViewsLayoutStyle

File

src/Plugin/views/style/ViewsLayoutStyle.php, line 20

Namespace

Drupal\views_layout\Plugin\views\style
View source
class ViewsLayoutStyle extends StylePluginBase {

  /**
   * Does the style plugin allows to use row plugins.
   *
   * @var bool
   */
  protected $usesRowPlugin = TRUE;

  /**
   * Does the style plugin support custom css class for the rows.
   *
   * @var bool
   */
  protected $usesRowClass = TRUE;

  /**
   * Does the style plugin support grouping of rows.
   *
   * @var bool
   */
  protected $usesGrouping = FALSE;

  /**
   * Does the style plugin for itself support to add fields to it's output.
   *
   * This option only makes sense on style plugins without row plugins, like
   * for example table.
   *
   * @var bool
   */
  protected $usesFields = FALSE;

  /**
   * @var \Drupal\Core\Layout\LayoutPluginManagerInterface
   */
  private $layoutPluginManager;

  /**
   * Array of all possible layouts.
   */
  private $layouts;

  /**
   * Array of all possible regions, keyed by layouts.
   */
  private $regions;

  /**
   * {@inheritdoc}
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, LayoutPluginManagerInterface $layout_plugin_manager) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->layoutPluginManager = $layout_plugin_manager;
    $this
      ->setRegions();
  }

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

  /**
   * {@inheritdoc}
   */
  protected function defineOptions() {
    $options = parent::defineOptions();
    $options['layout_name'] = array(
      'default' => '',
    );
    $options['layout_regions'] = array(
      'default' => [],
    );
    $options['skip_processing'] = array(
      'default' => '',
    );
    $options['skip_text'] = array(
      'default' => [],
    );
    $options['callback'] = array(
      'default' => '',
    );
    return $options;
  }
  protected function setRegions() {
    $layouts = [];
    $regions = [];
    $definitions = $this->layoutPluginManager
      ->getDefinitions('layout_builder');
    foreach ($definitions as $plugin_id => $definition) {
      $icon_values = $definition
        ->getIcon(45, 60, 1, 3);
      $icon = \Drupal::service('renderer')
        ->renderPlain($icon_values);
      $layouts[$plugin_id] = [
        'icon' => $icon,
        'name' => $definition
          ->getLabel(),
      ];
      $regions[$plugin_id]['label'] = $this
        ->t(':name', [
        ':name' => $definition
          ->getLabel(),
      ]);
      $regions[$plugin_id]['icon'] = $icon;
      foreach ($definition
        ->getRegionLabels() as $region_id => $label) {
        $regions[$plugin_id]['regions'][$region_id] = $label;
      }
    }
    $this->layouts = $layouts;
    $this->regions = $regions;
  }

  /**
   * Builds the configuration form.
   */
  public function buildOptionsForm(&$form, FormStateInterface $form_state) {
    parent::buildOptionsForm($form, $form_state);
    $header = [
      'icon' => $this
        ->t('Icon'),
      'name' => $this
        ->t('Name'),
    ];
    $form['layout_name'] = [
      '#type' => 'tableselect',
      '#header' => $header,
      '#options' => $this->layouts,
      '#default_value' => $this->options['layout_name'],
      '#multiple' => FALSE,
    ];
    foreach ($this->regions as $plugin_id => $region) {
      $default_values = $this->options['layout_name'] == $plugin_id ? $this->options['layout_regions'][$plugin_id] : [];
      $form['layout_regions'][$plugin_id] = [
        '#type' => 'checkboxes',
        '#options' => $region['regions'],
        '#title' => $this
          ->t(':name Regions', [
          ':name' => $region['label'],
        ]),
        '#description' => $this
          ->t("Check the regions in this layout that should be populated with Views results. Uncheck any regions that should be skipped. Skipped regions will not contain any results."),
        '#default_value' => !empty($this->options['layout_regions'][$plugin_id]) ? $this->options['layout_regions'][$plugin_id] : '',
        '#multiple' => TRUE,
        '#states' => [
          'visible' => [
            ':input[name="style_options[layout_name]"]' => [
              'value' => $plugin_id,
            ],
          ],
        ],
      ];
    }
    $form['skip_processing'] = [
      '#type' => 'select',
      '#options' => [
        '' => $this
          ->t('Skip'),
        'text' => $this
          ->t('Text'),
        'callback' => $this
          ->t('Callback'),
      ],
      '#description' => $this
        ->t('Choose processing for unchecked regions: skip (do not render), generate text, or execute a callback.'),
      '#title' => $this
        ->t('What to do with skipped regions?'),
      '#default_value' => $this->options['skip_processing'],
    ];
    $form['skip_text'] = [
      '#type' => 'text_format',
      '#description' => $this
        ->t('Text to render in skipped regions.'),
      '#title' => $this
        ->t('Skipped regions text'),
      '#default_value' => $this->options['skip_text']['value'],
      '#format' => $this->options['skip_text']['format'],
      '#states' => [
        'visible' => [
          ':input[name="style_options[skip_processing]"]' => [
            'value' => 'text',
          ],
        ],
      ],
    ];
    $form['callback'] = [
      '#type' => 'textfield',
      '#description' => $this
        ->t('Callback for skipped regions. Callback arguments are the layout plugin id, the current region, and the view.'),
      '#title' => $this
        ->t('Skipped regions callback'),
      '#default_value' => $this->options['callback'],
      '#states' => [
        'visible' => [
          ':input[name="style_options[skip_processing]"]' => [
            'value' => 'callback',
          ],
        ],
      ],
    ];
    $form['#element_validate'] = [
      [
        $this,
        'validateRegions',
      ],
    ];
  }

  /**
   * Form element validation handler for buildOptionsForm().
   */
  public function validateRegions($element, FormStateInterface $form_state) {
    $plugin_id = $element['layout_name']['#value'];
    if (empty($plugin_id)) {
      $form_state
        ->setError($element['layout_name'], $this
        ->t('A layout must be selected.'));
    }
    elseif (empty($element['layout_regions'][$plugin_id]['#value'])) {
      $form_state
        ->setError($element['layout_regions'][$plugin_id], $this
        ->t('At least one region must be selected.'));
    }
  }

  /**
   * {@inheritdoc}
   */
  public function render() {
    if (empty($this->view->rowPlugin)) {
      debug('Drupal\\views\\Plugin\\views\\style\\ViewsLayout: Something is wrong, this plugin is missing.');
      return;
    }
    $options = $this->options;
    $layoutName = $options['layout_name'];
    if (empty($layoutName)) {
      debug('Drupal\\views\\Plugin\\views\\style\\ViewsLayout: No layout was selected for this view.');
      return;
    }
    $layoutRegions = !empty($options['layout_regions'][$layoutName]) ? array_values(array_filter($options['layout_regions'][$layoutName])) : [];
    if (empty($layoutRegions)) {
      debug('Drupal\\views\\Plugin\\views\\style\\ViewsLayout: No regions were selected for this layout.');
      return;
    }
    $definitions = $this->layoutPluginManager
      ->getDefinitions('layout_builder');
    $definition = $definitions[$layoutName];
    $allRegions = array_keys($definition
      ->getRegionLabels());
    $skippedRegions = array_diff($allRegions, $layoutRegions);
    $skipProcessing = $options['skip_processing'];
    $skipText = $options['skip_text'];
    $skipCallback = $options['callback'];

    // Set up layout iterator to keep track of layout position.
    $layoutIterator = new \ArrayIterator($allRegions);

    // Create a layout instance.
    $configuration = [];
    $layoutInstance = $this->layoutPluginManager
      ->createInstance($layoutName, $configuration);

    // Iterate through the views rows and construct as many layout render arrays
    // as the rows allow.
    $newRows = [];
    $layoutRenderArray = [];
    foreach ($this->view->result as $key => $row) {

      // Process skipped regions.
      while (in_array($layoutIterator
        ->current(), $skippedRegions)) {
        if ($skipProcessing == 'text') {
          $renderedRow = [
            '#type' => 'processed_text',
            '#text' => $skipText['value'],
            '#format' => $skipText['format'],
          ];
          $layoutRenderArray[$layoutIterator
            ->current()] = [
            $renderedRow,
          ];
        }
        elseif ($skipProcessing == 'callback' && function_exists($skipCallback)) {
          $renderedRow = $skipCallback($layoutName, $layoutIterator
            ->current(), $this->view);
          $layoutRenderArray[$layoutIterator
            ->current()] = [
            $renderedRow,
          ];
        }
        $layoutIterator
          ->next();
      }

      // Add the the current row to the build.
      // Check for end of array in case a skipped region is the last region.
      if ($layoutIterator
        ->valid()) {
        $renderedRow = $this->view->rowPlugin
          ->render($row);
        $layoutRenderArray[$layoutIterator
          ->current()] = [
          $renderedRow,
        ];
        $layoutIterator
          ->next();
      }

      // When we hit the end of all regions in a layout, stop and build a
      // Views row. We might not be done with all the results yet so we
      // can't break out of our foreach loop.
      if (!$layoutIterator
        ->valid()) {
        $newRows[] = $layoutInstance
          ->build($layoutRenderArray);
        $layoutRenderArray = [];
        $layoutIterator
          ->rewind();
      }
    }

    // If we hit the end of the view results before we hit the end of the
    // layout, and we're not skipping the results, we need to process the
    // remaining regions in the layout.
    if ($layoutIterator
      ->valid() && !empty($skipProcessing)) {
      do {
        if ($skipProcessing == 'text') {
          $renderedRow = [
            '#type' => 'processed_text',
            '#text' => $skipText['value'],
            '#format' => $skipText['format'],
          ];
          $layoutRenderArray[$layoutIterator
            ->current()] = [
            $renderedRow,
          ];
        }
        elseif ($skipProcessing == 'callback' && function_exists($skipCallback)) {
          $renderedRow = $skipCallback($layoutName, $layoutIterator
            ->current(), $this->view);
          $layoutRenderArray[$layoutIterator
            ->current()] = [
            $renderedRow,
          ];
        }
        $layoutIterator
          ->next();
      } while ($layoutIterator
        ->valid());
    }

    // We might have an unrendered layout left. Be sure to pick it up.
    if (!empty($layoutRenderArray)) {
      $newRows[] = $layoutInstance
        ->build($layoutRenderArray);
    }

    // Return the render array.
    $build = array(
      '#theme' => $this
        ->themeFunctions(),
      '#view' => $this->view,
      '#options' => $this->options,
      '#rows' => $newRows,
    );
    return $build;
  }

}

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::$definition public property Plugins's 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::$pluginDefinition protected property The plugin implementation definition. 1
PluginBase::$pluginId protected property The plugin_id.
PluginBase::$renderer protected property Stores the render API renderer. 3
PluginBase::$view public property The top object of a view. 1
PluginBase::calculateDependencies public function Calculates dependencies for the configured plugin. Overrides DependentPluginInterface::calculateDependencies 14
PluginBase::DERIVATIVE_SEPARATOR constant A string which is used to separate base plugin IDs from the derivative ID.
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::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::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::isConfigurable public function Determines if the plugin is configurable.
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::submitOptionsForm public function Handle any special handling on the validate form. Overrides ViewsPluginInterface::submitOptionsForm 16
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 Unpack options over our existing defaults, drilling down into arrays so that defaults don't get totally blown away. 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. The resulting string will be sanitized with Xss::filterAdmin. 1
PluginBase::VIEWS_QUERY_LANGUAGE_SITE_DEFAULT constant Query string to indicate the site default language.
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.
StylePluginBase::$defaultFieldLabels protected property Should field labels be enabled by default. 1
StylePluginBase::$groupingTheme protected property The theme function used to render the grouping set.
StylePluginBase::$rendered_fields protected property Stores the rendered field values, keyed by the row index and field name.
StylePluginBase::$rowTokens protected property Store all available tokens row rows.
StylePluginBase::$usesOptions protected property Denotes whether the plugin has an additional options form. Overrides PluginBase::$usesOptions
StylePluginBase::buildSort public function Called by the view builder to see if this style handler wants to interfere with the sorts. If so it should build; if it returns any non-TRUE value, normal sorting will NOT be added to the query. 1
StylePluginBase::buildSortPost public function Called by the view builder to let the style build a second set of sorts that will come after any other sorts in the view. 1
StylePluginBase::defaultFieldLabels public function Return TRUE if this style enables field labels by default. 1
StylePluginBase::destroy public function Clears a plugin. Overrides PluginBase::destroy
StylePluginBase::elementPreRenderRow public function #pre_render callback for view row field rendering.
StylePluginBase::evenEmpty public function Should the output of the style plugin be rendered even if it's a empty view. 2
StylePluginBase::getField public function Gets a rendered field.
StylePluginBase::getFieldValue public function Get the raw field value.
StylePluginBase::getRowClass public function Return the token replaced row class for the specified row.
StylePluginBase::init public function Overrides \Drupal\views\Plugin\views\PluginBase::init(). Overrides PluginBase::init
StylePluginBase::preRender public function Allow the style to do stuff before each row is rendered.
StylePluginBase::query public function Add anything to the query that we might need to. Overrides PluginBase::query 1
StylePluginBase::renderFields protected function Renders all of the fields for a given style and store them on the object.
StylePluginBase::renderGrouping public function Group records as needed for rendering.
StylePluginBase::renderGroupingSets public function Render the grouping sets.
StylePluginBase::renderRowGroup protected function Renders a group of rows of the grouped view.
StylePluginBase::tokenizeValue public function Take a value and apply token replacement logic to it.
StylePluginBase::trustedCallbacks public static function Lists the trusted callbacks provided by the implementing class. Overrides PluginBase::trustedCallbacks
StylePluginBase::usesFields public function Return TRUE if this style also uses fields. 3
StylePluginBase::usesGrouping public function Returns the usesGrouping property. 3
StylePluginBase::usesRowClass public function Returns the usesRowClass property. 3
StylePluginBase::usesRowPlugin public function Returns the usesRowPlugin property. 10
StylePluginBase::usesTokens public function Return TRUE if this style uses tokens.
StylePluginBase::validate public function Validate that the plugin is correct and can be saved. Overrides PluginBase::validate
StylePluginBase::validateOptionsForm public function Validate the options form. Overrides PluginBase::validateOptionsForm
StylePluginBase::wizardForm public function Provide a form in the views wizard if this style is selected.
StylePluginBase::wizardSubmit public function Alter the options of a display before they are added to the view. 1
TrustedCallbackInterface::THROW_EXCEPTION constant Untrusted callbacks throw exceptions.
TrustedCallbackInterface::TRIGGER_SILENCED_DEPRECATION constant Untrusted callbacks trigger silenced E_USER_DEPRECATION errors.
TrustedCallbackInterface::TRIGGER_WARNING constant Untrusted callbacks trigger E_USER_WARNING errors.
ViewsLayoutStyle::$layoutPluginManager private property
ViewsLayoutStyle::$layouts private property Array of all possible layouts.
ViewsLayoutStyle::$regions private property Array of all possible regions, keyed by layouts.
ViewsLayoutStyle::$usesFields protected property Does the style plugin for itself support to add fields to it's output. Overrides StylePluginBase::$usesFields
ViewsLayoutStyle::$usesGrouping protected property Does the style plugin support grouping of rows. Overrides StylePluginBase::$usesGrouping
ViewsLayoutStyle::$usesRowClass protected property Does the style plugin support custom css class for the rows. Overrides StylePluginBase::$usesRowClass
ViewsLayoutStyle::$usesRowPlugin protected property Does the style plugin allows to use row plugins. Overrides StylePluginBase::$usesRowPlugin
ViewsLayoutStyle::buildOptionsForm public function Builds the configuration form. Overrides StylePluginBase::buildOptionsForm
ViewsLayoutStyle::create public static function Creates an instance of the plugin. Overrides PluginBase::create
ViewsLayoutStyle::defineOptions protected function Information about options for all kinds of purposes will be held here. Overrides StylePluginBase::defineOptions
ViewsLayoutStyle::render public function Render the display in this style. Overrides StylePluginBase::render
ViewsLayoutStyle::setRegions protected function
ViewsLayoutStyle::validateRegions public function Form element validation handler for buildOptionsForm().
ViewsLayoutStyle::__construct public function Constructs a PluginBase object. Overrides PluginBase::__construct