You are here

class SliderPro in Slider Pro 8

Same name in this branch
  1. 8 src/Entity/SliderPro.php \Drupal\slider_pro\Entity\SliderPro
  2. 8 src/Plugin/views/style/SliderPro.php \Drupal\slider_pro\Plugin\views\style\SliderPro

Plugin annotation


@ViewsStyle(
  id = "slider_pro",
  title = @Translation("Slider Pro"),
  help = @Translation("Displays a view as a Slider Pro, using the Slider Pro jQuery plugin."),
  theme = "slider_pro_views_style",
  theme_file = "slider_pro_views.theme.inc",
  display_types = {"normal"}
)

Hierarchy

Expanded class hierarchy of SliderPro

File

src/Plugin/views/style/SliderPro.php, line 25

Namespace

Drupal\slider_pro\Plugin\views\style
View source
class SliderPro extends StylePluginBase {

  /**
   * {@inheritdoc}
   */
  protected $usesRowPlugin = FALSE;

  /**
   * {@inheritdoc}
   */
  protected $usesFields = TRUE;

  /**
   * {@inheritdoc}
   */
  protected $usesOptions = TRUE;

  /**
   * {@inheritdoc}
   */
  protected $usesGrouping = FALSE;

  /**
   * {@inheritdoc}
   */
  protected $usesRowClass = FALSE;
  protected $sliderProManager;

  /**
   * SliderPro constructor.
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, SliderProManager $slider_pro_manager) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->sliderProManager = $slider_pro_manager;
  }

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

  /**
   * {@inheritdoc}
   */
  public function evenEmpty() {
    return FALSE;
  }

  /**
   * {@inheritdoc}
   */
  protected function defineOptions() {
    $options = parent::defineOptions();
    $options['optionset'] = [
      'default' => 'default',
    ];
    $options['fields'] = [];
    $options['thumbnail_fields'] = [];
    $options['number_of_layers'] = 0;
    $options['layers'] = [];
    return $options;
  }

  /**
   * {@inheritdoc}
   */
  public function buildOptionsForm(&$form, FormStateInterface $form_state) {
    parent::buildOptionsForm($form, $form_state);
    $fields = $this
      ->getAvailableFields();
    if (empty($fields)) {
      drupal_set_message($this
        ->t('To configure Slider Pro you have to add at least one field'), 'error');
      return $form;
    }
    $form['general'] = [
      '#type' => 'details',
      '#title' => $this
        ->t('General settings'),
      '#open' => TRUE,
    ];
    $form['general']['optionset'] = [
      '#title' => t('Option set'),
      '#type' => 'select',
      '#options' => $this->sliderProManager
        ->getOptionList(),
      '#default_value' => $this->options['optionset'],
      '#required' => TRUE,
    ];
    $form['general']['fields'] = [
      '#type' => 'checkboxes',
      '#title' => $this
        ->t('Fields on slide'),
      '#options' => $this
        ->getAvailableFields(),
      '#description' => $this
        ->t('Select which fields you want to use on each slide.'),
      '#default_value' => $this->options['fields'],
      '#required' => TRUE,
    ];
    $form['thumbnails'] = [
      '#type' => 'details',
      '#title' => $this
        ->t('Thumbnail settings'),
      '#open' => FALSE,
    ];
    $form['thumbnails']['thumbnail_fields'] = [
      '#type' => 'checkboxes',
      '#title' => $this
        ->t('Fields'),
      '#options' => $this
        ->getAvailableFields(),
      '#description' => $this
        ->t('Select which fields you want to display on the thumbs. This setting will only be applied if the selected optionset defines a thumbnail position'),
      '#default_value' => $this->options['thumbnail_fields'],
    ];
    $form['layers_wrapper'] = [
      '#type' => 'details',
      '#title' => $this
        ->t('Layer settings'),
      '#open' => !empty($this->options['number_of_layers']) ? TRUE : FALSE,
    ];
    $form['layers_wrapper']['number_of_layers'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('Number of layers'),
      '#options' => array_combine([
        0,
        1,
        2,
        3,
        4,
        5,
      ], [
        $this
          ->t('None'),
        1,
        2,
        3,
        4,
        5,
      ]),
      '#default_value' => $this->options['number_of_layers'],
      '#description' => $this
        ->t('Provide the number of layers you want to use. Afterwards save the options and re-open them to start configuring your layers.'),
    ];
    $form['layers_wrapper']['layers'] = [
      '#type' => 'table',
      '#header' => [
        $this
          ->t('Fields'),
        $this
          ->t('Background'),
        $this
          ->t('Position'),
        $this
          ->t('Show transition'),
        $this
          ->t('Hide transition'),
        $this
          ->t('Delay'),
        $this
          ->t('Duration'),
        $this
          ->t('Weight'),
      ],
      '#attributes' => [
        'id' => 'slider-pro-layers',
      ],
      '#tabledrag' => [
        [
          'action' => 'order',
          'relationship' => 'sibling',
          'group' => 'weight',
        ],
      ],
      '#empty' => $this
        ->t('No layers configured yet...'),
    ];
    for ($key = 0; $key < $this->options['number_of_layers']; $key++) {
      $layer = isset($this->options['layers'][$key]) ? $this->options['layers'][$key] : [
        'fields' => [],
        'background' => '',
        'position' => 'topLeft',
        'show_transition' => 'left',
        'hide_transition' => 'right',
        'show_delay' => 0,
        'stay_duration' => 0,
        'weight' => 0,
      ];
      $form['layers_wrapper']['layers'][$key]['#attributes']['class'][] = 'draggable';
      $form['layers_wrapper']['layers'][$key]['#weight'] = $layer['weight'];
      $form['layers_wrapper']['layers'][$key]['fields'] = [
        '#type' => 'checkboxes',
        '#title' => $this
          ->t('Fields'),
        '#title_display' => 'invisible',
        '#options' => $this
          ->getAvailableFields(),
        '#default_value' => $layer['fields'],
        '#description' => $this
          ->t('Select which fields you want to display on this layer.'),
        '#required' => TRUE,
      ];
      $form['layers_wrapper']['layers'][$key]['background'] = [
        '#type' => 'select',
        '#title' => $this
          ->t('Background'),
        '#title_display' => 'invisible',
        '#options' => [
          '' => $this
            ->t('None'),
          'sp-white' => $this
            ->t('White transparant'),
          'sp-black' => $this
            ->t('Black transparant'),
        ],
        '#default_value' => $layer['background'],
      ];
      $form['layers_wrapper']['layers'][$key]['position'] = [
        '#type' => 'select',
        '#title' => $this
          ->t('Position'),
        '#title_display' => 'invisible',
        '#options' => [
          'topLeft' => $this
            ->t('Top left'),
          'topCenter' => $this
            ->t('Top center'),
          'topRight' => $this
            ->t('Top right'),
          'bottomLeft' => $this
            ->t('Bottom left'),
          'bottomCenter' => $this
            ->t('Bottom center'),
          'bottomRight' => $this
            ->t('Bottom right'),
          'centerLeft' => $this
            ->t('Center left'),
          'centerRight' => $this
            ->t('Center right'),
          'centerCenter' => $this
            ->t('Center center'),
        ],
        '#default_value' => $layer['position'],
        '#required' => TRUE,
      ];
      $form['layers_wrapper']['layers'][$key]['show_transition'] = [
        '#type' => 'select',
        '#title' => $this
          ->t('Show transition'),
        '#title_display' => 'invisible',
        '#options' => [
          'left' => $this
            ->t('Left'),
          'right' => $this
            ->t('Right'),
          'up' => $this
            ->t('Up'),
          'down' => $this
            ->t('Down'),
        ],
        '#default_value' => $layer['show_transition'],
        '#required' => TRUE,
      ];
      $form['layers_wrapper']['layers'][$key]['hide_transition'] = [
        '#type' => 'select',
        '#title' => $this
          ->t('Show transition'),
        '#title_display' => 'invisible',
        '#options' => [
          'left' => $this
            ->t('Left'),
          'right' => $this
            ->t('Right'),
          'up' => $this
            ->t('Up'),
          'down' => $this
            ->t('Down'),
        ],
        '#default_value' => $layer['hide_transition'],
        '#required' => TRUE,
      ];
      $form['layers_wrapper']['layers'][$key]['show_delay'] = [
        '#type' => 'number',
        '#title' => $this
          ->t('Show delay'),
        '#title_display' => 'invisible',
        '#size' => 5,
        '#required' => TRUE,
        '#default_value' => $layer['show_delay'],
        '#description' => $this
          ->t('Sets a delay for the show transition. This delay starts from the moment when the transition to the new slide starts.'),
      ];
      $form['layers_wrapper']['layers'][$key]['stay_duration'] = [
        '#type' => 'number',
        '#title' => $this
          ->t('Stay duration'),
        '#title_display' => 'invisible',
        '#size' => 5,
        '#required' => TRUE,
        '#default_value' => $layer['stay_duration'],
        '#description' => $this
          ->t('Sets how much time a layer will stay visible before being hidden automatically.'),
      ];

      // @todo: use this button if figured out how ajax calls in this form work.

      /*$form['layers_wrapper']['layers'][$key]['remove'] = [
          '#type' => 'submit',
          '#value' => $this->t('Remove'),
          '#submit' => [[$this, 'removeLayerSubmit']],
          '#ajax' => [
            'callback' => [
              'Drupal\slider_pro\Plugin\views\style\SliderPro',
              'ajaxRefreshLayers'
            ],
          ],
          '#limit_validation_errors' => [],
        ];*/
      $form['layers_wrapper']['layers'][$key]['weight'] = [
        '#type' => 'weight',
        '#title' => $this
          ->t('Weight'),
        '#title_display' => 'invisible',
        '#default_value' => $layer['weight'],
        '#attributes' => [
          'class' => [
            'weight',
          ],
        ],
      ];
    }

    //Sort by weight.
    uasort($form['layers_wrapper']['layers'], [
      '\\Drupal\\Component\\Utility\\SortArray',
      'sortByWeightProperty',
    ]);

    // @todo: use this button if figured out how ajax calls in this form work.

    /*$form['layers_wrapper']['add_layer'] = [
        '#type' => 'submit',
        '#value' => $this->t('Add layer'),
        '#submit' => [[$this, 'addNewLayerSubmit']],
        '#ajax' => [
          'callback' => [
            'Drupal\slider_pro\Plugin\views\style\SliderPro',
            'ajaxRefreshLayers'
          ],
        ],
        '#limit_validation_errors' => [],
      ];*/
  }

  /**
   * {@inheritdoc}
   */
  public function validateOptionsForm(&$form, FormStateInterface $form_state) {
    parent::validateOptionsForm($form, $form_state);
    $style_options = $form_state
      ->getValue('style_options');

    // Flatten style options array.
    $nested_options = [
      'layers' => !empty($style_options['layers_wrapper']['layers']) ? $style_options['layers_wrapper']['layers'] : [],
      'fields' => $style_options['general']['fields'],
      'thumbnail_fields' => $style_options['thumbnails']['thumbnail_fields'],
    ];
    unset($style_options['layers_wrapper']['layers']);
    unset($style_options['general']['fields']);
    unset($style_options['thumbnails']['thumbnail_fields']);
    $form_state
      ->setValue(array(
      'style_options',
    ), array_merge($nested_options, SliderProManager::flattenArray($style_options)));

    // Unset nested values.
    $form_state
      ->unsetValue(array(
      'style_options',
      'general',
    ));
    $form_state
      ->unsetValue(array(
      'style_options',
      'thumbnails',
    ));
    $form_state
      ->unsetValue(array(
      'style_options',
      'layers_wrapper',
    ));

    // Validation.
    $optionset = \Drupal\slider_pro\Entity\SliderPro::load($form_state
      ->getValue([
      'style_options',
      'optionset',
    ]));
    $thumbnail_fields = $form_state
      ->getValue([
      'style_options',
      'thumbnail_fields',
    ]);
    if ($optionset
      ->hasThumbnails() && empty(array_filter($thumbnail_fields))) {
      $form_state
        ->setErrorByName('thumbnails][thumbnail_fields][title', $this
        ->t('The "Thumbnails fields" field is required as the optionset has a position for thumbnails configured.'));
    }
  }

  /**
   * {@inheritdoc}
   */
  public function render() {
    $rows = [];
    $fields = array_keys($this
      ->getAvailableFields());
    for ($i = 0; $i < count($this->view->result); $i++) {
      $rows[$i]['layers'] = [];
      for ($j = 0; $j < count($fields); $j++) {
        $field = $fields[$j];
        $rendered_field = $this->view->style_plugin
          ->getField($i, $field);
        if (in_array($field, array_filter($this->options['fields']))) {
          $rows[$i]['slide'][$fields[$j]] = $rendered_field;
        }
        if (in_array($field, array_filter($this->options['thumbnail_fields']))) {
          $rows[$i]['thumb'][$fields[$j]] = $rendered_field;
        }
        $layers = array_slice($this->options['layers'], 0, $this->options['number_of_layers']);
        foreach ($layers as $key => $layer) {
          if (!isset($rows[$i]['layers'][$key])) {
            $rows[$i]['layers'][$key] = $layer;
          }
          if (in_array($field, array_filter($layer['fields']))) {
            $rows[$i]['layers'][$key]['content'][$fields[$j]] = $rendered_field;
          }
        }
      }
    }

    // Unset fields from all layers. Don't need it while rendering.
    foreach ($rows as &$row) {
      foreach ($row['layers'] as &$layer) {
        unset($layer['fields']);
        unset($layer['weight']);
        unset($layer['remove']);
      }
    }
    $build = array(
      '#theme' => $this
        ->themeFunctions(),
      '#view' => $this->view,
      '#options' => $this->options,
      '#rows' => $rows,
    );
    return $build;
  }

  /**
   * Ajax callback to refresh layers.
   * @param $form
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   * @return \Drupal\Core\Ajax\AjaxResponse
   */
  public static function ajaxRefreshLayers($form, FormStateInterface $form_state) {
    $response = new AjaxResponse();
    $response
      ->addCommand(new ReplaceCommand('#slider-pro-layers', $form['options']['style_options']['layers_wrapper']['layers']));
    return $response;
  }

  /**
   * Submit callback to add new layer.
   * @param $form
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   */
  public function addNewLayerSubmit($form, FormStateInterface $form_state) {
    $form_state
      ->setRebuild(TRUE);
  }

  /**
   * Submit callback to remove a layer.
   * @param $form
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   */
  public function removeLayerSubmit($form, FormStateInterface $form_state) {
    $form_state
      ->setRebuild(TRUE);
  }

  /**
   * Returns option list of fields available on view.
   */
  protected function getAvailableFields() {
    $view = $this->view;
    return $view->display_handler
      ->getFieldLabels();
  }

}

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.
SliderPro::$sliderProManager protected property
SliderPro::$usesFields protected property Does the style plugin for itself support to add fields to its output. Overrides StylePluginBase::$usesFields
SliderPro::$usesGrouping protected property Does the style plugin support grouping of rows. Overrides StylePluginBase::$usesGrouping
SliderPro::$usesOptions protected property Denotes whether the plugin has an additional options form. Overrides StylePluginBase::$usesOptions
SliderPro::$usesRowClass protected property Does the style plugin support custom css class for the rows. Overrides StylePluginBase::$usesRowClass
SliderPro::$usesRowPlugin protected property Whether or not this style uses a row plugin. Overrides StylePluginBase::$usesRowPlugin
SliderPro::addNewLayerSubmit public function Submit callback to add new layer.
SliderPro::ajaxRefreshLayers public static function Ajax callback to refresh layers.
SliderPro::buildOptionsForm public function Provide a form to edit options for this plugin. Overrides StylePluginBase::buildOptionsForm
SliderPro::create public static function Creates an instance of the plugin. Overrides PluginBase::create
SliderPro::defineOptions protected function Information about options for all kinds of purposes will be held here. Overrides StylePluginBase::defineOptions
SliderPro::evenEmpty public function Should the output of the style plugin be rendered even if it's a empty view. Overrides StylePluginBase::evenEmpty
SliderPro::getAvailableFields protected function Returns option list of fields available on view.
SliderPro::removeLayerSubmit public function Submit callback to remove a layer.
SliderPro::render public function Render the display in this style. Overrides StylePluginBase::render
SliderPro::validateOptionsForm public function Validate the options form. Overrides StylePluginBase::validateOptionsForm
SliderPro::__construct public function SliderPro constructor. Overrides PluginBase::__construct
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::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::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::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.