You are here

class ViewsAccordion in Views Accordion 8

Same name and namespace in other branches
  1. 2.0.x src/Plugin/views/style/ViewsAccordion.php \Drupal\views_accordion\Plugin\views\style\ViewsAccordion

Style plugin to render each item in an ordered or unordered list.

Plugin annotation


@ViewsStyle(
  id = "views_accordion",
  title = @Translation("jQuery UI accordion"),
  help = @Translation("Display a JQuery accordion with the results. The first field will be used as the header and trigger."),
  theme = "views_accordion_view",
  display_types = {"normal"}
)

Hierarchy

Expanded class hierarchy of ViewsAccordion

File

src/Plugin/views/style/ViewsAccordion.php, line 21

Namespace

Drupal\views_accordion\Plugin\views\style
View source
class ViewsAccordion extends StylePluginBase {

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

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

  /**
   * Set default options.
   */
  protected function defineOptions() {
    $options = parent::defineOptions();
    $options['use-grouping-header'] = [
      'default' => 0,
    ];
    $options['collapsible'] = [
      'default' => 0,
    ];
    $options['row-start-open'] = [
      'default' => 0,
    ];
    $options['animated'] = [
      'default' => 'slide',
    ];
    $options['animation_time'] = [
      'default' => 300,
    ];
    $options['heightStyle'] = [
      'default' => 'auto',
    ];
    $options['event'] = [
      'default' => 'click',
    ];
    $options['disableifone'] = [
      'default' => 0,
    ];
    $options['use_header_icons'] = [
      'default' => TRUE,
    ];
    $options['icon_header'] = [
      'default' => 'ui-icon-triangle-1-e',
    ];
    $options['icon_active_header'] = [
      'default' => 'ui-icon-triangle-1-s',
    ];
    return $options;
  }

  /**
   * {@inheritdoc}
   */
  public function buildOptionsForm(&$form, FormStateInterface $form_state) {
    parent::buildOptionsForm($form, $form_state);

    // Find out how many items the display is currently configured to show
    // (row-start-open).
    $maxitems = $this->displayHandler
      ->getOption('items_per_page');

    // If items_per_page is set to unlimitted (0), 10 rows will be what the user
    // gets to choose from.
    $maxitems = $maxitems == 0 ? 10 : $maxitems;

    // Setup our array of options for choosing which row should start opened
    // (row-start-open).
    $rsopen_options = [];
    for ($i = 1; $i <= $maxitems; $i++) {
      $rsopen_options[] = $this
        ->t('Row @number', [
        '@number' => $i,
      ]);
    }
    $rsopen_options['none'] = $this
      ->t('None');
    $rsopen_options['random'] = $this
      ->t('Random');

    /*
     * See /core/core.libraries.yml and http://api.jqueryui.com/1.10/easings/
     * We've used all the easing effects form ui effects core.
     */
    $animated_options = [
      'none' => $this
        ->t('None'),
      'linear' => $this
        ->t('Linear'),
      'swing' => $this
        ->t('Swing'),
      'easeInQuart' => $this
        ->t('easeInQuart'),
      'easeOutQuart' => $this
        ->t('easeOutQuart'),
      'easeInOutQuart' => $this
        ->t('easeInOutQuart'),
      'easeInExpo' => $this
        ->t('easeInExpo'),
      'easeOutExpo' => $this
        ->t('easeOutExpo'),
      'easeInOutExpo' => $this
        ->t('easeInOutExpo'),
      'easeInBack' => $this
        ->t('easeInBack'),
      'easeOutBack' => $this
        ->t('easeOutBack'),
      'easeInOutBack' => $this
        ->t('easeInOutBack'),
      'easeInQuad' => $this
        ->t('easeInQuad'),
      'easeOutQuad' => $this
        ->t('easeOutQuad'),
      'easeInOutQuad' => $this
        ->t('easeInOutQuad'),
      'easeInQuint' => $this
        ->t('easeInQuint'),
      'easeOutQuint' => $this
        ->t('easeOutQuint'),
      'easeInOutQuint' => $this
        ->t('easeInOutQuint'),
      'easeInCirc' => $this
        ->t('easeInCirc'),
      'easeOutCirc' => $this
        ->t('easeOutCirc'),
      'easeInOutCirc' => $this
        ->t('easeInOutCirc'),
      'easeInBounce' => $this
        ->t('easeInBounce'),
      'easeOutBounce' => $this
        ->t('easeOutBounce'),
      'easeInOutBounce' => $this
        ->t('easeInOutBounce'),
      'easeInCubic' => $this
        ->t('easeInCubic'),
      'easeOutCubic' => $this
        ->t('easeOutCubic'),
      'easeInOutCubic' => $this
        ->t('easeInOutCubic'),
      'easeInSine' => $this
        ->t('easeInSine'),
      'easeOutSine' => $this
        ->t('easeOutSine'),
      'easeInOutSine' => $this
        ->t('easeInOutSine'),
      'easeInElastic' => $this
        ->t('easeInElastic'),
      'easeOutElastic' => $this
        ->t('easeOutElastic'),
      'easeInOutElastic' => $this
        ->t('easeInOutElastic'),
    ];
    $c = count($this->options['grouping']);

    // Add a form use group header field for every grouping, plus one.
    for ($i = 0; $i <= $c; $i++) {
      $grouping = !empty($this->options['grouping'][$i]) ? $this->options['grouping'][$i] : [];
      $grouping += [
        'use-grouping-header' => 0,
      ];
      $form['grouping'][$i]['use-grouping-header'] = [
        '#type' => 'checkbox',
        '#title' => $this
          ->t('Use the group header as the Accordion header'),
        '#default_value' => $grouping['use-grouping-header'],
        '#description' => $this
          ->t("If checked, the Group's header will be used to open/close the accordion."),
        '#states' => [
          'invisible' => [
            ':input[name="style_options[grouping][' . $i . '][field]"]' => [
              'value' => '',
            ],
          ],
        ],
      ];
    }
    $form['grouping']['#prefix'] = '<div class="form-item">' . $this
      ->t('<strong>IMPORTANT:</strong> The <em>first field</em> in order of appearance <em>will</em> be the one used as the "header" or "trigger" of the accordion action.') . '</div>';
    $form['disableifone'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Disable if only one result'),
      '#default_value' => $this->options['disableifone'],
      '#description' => $this
        ->t("If set, the accordion will not be shown when there are less than 2 results."),
    ];
    $form['row-start-open'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('Row to display opened on start'),
      '#default_value' => $this->options['row-start-open'],
      '#description' => $this
        ->t('Choose which row should start opened when the accordion first loads. If you want all to start closed, choose "None", and make sure to have "Allow for all rows to be closed" on below.'),
      '#options' => $rsopen_options,
    ];
    $form['collapsible'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Collapsible'),
      '#default_value' => $this->options['collapsible'],
      '#description' => $this
        ->t('Whether all the sections can be closed at once. Allows collapsing the active section.'),
    ];
    $form['animated'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('Animation effect'),
      '#default_value' => $this->options['animated'],
      '#description' => $this
        ->t('Choose what animation effect you would like to see, or "None" to disable it.'),
      '#options' => $animated_options,
    ];
    $form['animation_time'] = [
      '#type' => 'number',
      '#title' => $this
        ->t('Animation time'),
      '#default_value' => $this->options['animation_time'],
      '#min' => 0,
      '#step' => 1,
      '#description' => $this
        ->t('The animation duration in milliseconds'),
    ];
    $form['heightStyle'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('heightStyle'),
      '#default_value' => $this->options['heightStyle'],
      '#description' => $this
        ->t('Controls the height of the accordion and each panel.'),
      '#options' => [
        'auto' => 'auto',
        'fill' => 'fill',
        'content' => 'content',
      ],
    ];
    $form['event'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('Event'),
      '#default_value' => $this->options['event'],
      '#description' => $this
        ->t('The event on which to trigger the accordion.'),
      '#options' => [
        'click' => $this
          ->t('Click'),
        'mouseover' => $this
          ->t('Mouseover'),
      ],
    ];
    $form['use_header_icons'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Use header icons'),
      '#default_value' => $this->options['use_header_icons'],
      '#description' => $this
        ->t('Icons to use for headers, matching an icon provided by the <a href="http://api.jqueryui.com/theming/icons/" target="_false">jQuery UI CSS Framework</a>. Uncheck to have no icons displayed.'),
    ];
    $show_if_use_header_icons = [
      'visible' => [
        ':input[name="style_options[use_header_icons]"]' => [
          'checked' => TRUE,
        ],
      ],
    ];
    $form['icon_header'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Closed row header icon'),
      '#default_value' => $this->options['icon_header'],
      '#states' => $show_if_use_header_icons,
    ];
    $form['icon_active_header'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Opened row header icon'),
      '#default_value' => $this->options['icon_active_header'],
      '#states' => $show_if_use_header_icons,
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function preRender($result) {

    // No need do anything if we we have only one result and disableifone is
    // active.
    if ($this->options['disableifone'] == '1') {
      if (count($result) < 2) {
        return;
      }
    }
    $view_settings = [];
    $header_class = 'views-accordion-header';

    // This is used for triggering the creation of the accordions.
    // We append the dom_id so that multiple nested views with accordions work.
    $accordion_header_class = 'js-' . $header_class . '-' . $this->view->dom_id;
    $view_settings['usegroupheader'] = FALSE;
    foreach ($this->options['grouping'] as $group) {
      $view_settings['usegroupheader'] = $group['use-grouping-header'] == 1;

      // @TODO handle multiple grouping.
      break;
    }

    // Find out about the header field options.
    $fields = array_values($this->displayHandler
      ->getOption('fields'));

    // Add header class to first not-excluded field.
    foreach ($fields as $field) {
      if (!isset($field['exclude']) || $field['exclude'] == 0) {

        // Make sure we are using a div for markup at least.
        if (empty($field['element_wrapper_type'])) {
          $this->view->field[$field['id']]->options['element_wrapper_type'] = 'div';
        }

        // Setup our wrapper class if not using group header.
        if (!$view_settings['usegroupheader']) {
          $header_wrapper_class = $header_class . ' ' . $accordion_header_class;

          // If the user configured its own class, set that up with our own
          // class.
          if (!empty($field['element_wrapper_class'])) {
            $header_wrapper_class = $field['element_wrapper_class'] . ' ' . $header_wrapper_class;
          }

          // Setup the view to use our processed wrapper class.
          $this->view->field[$field['id']]->options['element_wrapper_class'] = $header_wrapper_class;
        }
        break;
      }
    }
    $this->view->element['#attached']['library'][] = 'views_accordion/views_accordion.accordion';

    // Add the appropiate effect library if necessary.
    $effect = $this->options['animated'];
    if ($effect !== 'none' && $effect !== 'swing' && $effect !== 'linear') {

      // jquery.ui.effects.core provides the easing effects.
      // It would be possible to integrate and load any other libraries here.
      $this->view->element['#attached']['library'][] = 'core/jquery.ui.effects.core';
    }

    // Prepare the JS settings.
    // We do it here so we don't have it run once every group.
    $view_settings['collapsible'] = $this->options['collapsible'];
    if ($this->options['row-start-open'] == 'random') {
      $view_settings['rowstartopen'] = 'random';
    }
    else {
      $view_settings['rowstartopen'] = $this->options['row-start-open'] == 'none' ? FALSE : (int) $this->options['row-start-open'];
    }
    $view_settings['animated'] = $this->options['animated'] == 'none' ? FALSE : $this->options['animated'];
    $view_settings['duration'] = $this->options['animated'] == 'none' ? FALSE : $this->options['animation_time'];
    $view_settings['heightStyle'] = $this->options['heightStyle'];
    $view_settings['event'] = $this->options['event'];
    $view_settings['useHeaderIcons'] = $this->options['use_header_icons'];
    if ($this->options['use_header_icons']) {
      $view_settings['iconHeader'] = $this->options['icon_header'];
      $view_settings['iconActiveHeader'] = $this->options['icon_active_header'];
    }

    // The view display selector.
    // Set in stable & classy themes.
    $view_settings['display'] = '.js-view-dom-id-' . $this->view->dom_id;

    // The accordion header selector.
    $view_settings['header'] = '.' . $accordion_header_class;
    if ($view_settings['usegroupheader']) {

      // @TODO we cannot set a class for the grouping h3 apparently...
      $view_settings['header'] = '.js-views-accordion-group-header';
    }
    $this->view->element['#attached']['drupalSettings']['views_accordion'] = [
      $this->view->dom_id => $view_settings,
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function render() {
    $rows = parent::render();
    $output = [
      '#theme' => $this
        ->themeFunctions(),
      '#view' => $this->view,
      '#options' => $this->options,
      '#rows' => $rows,
    ];
    return $output;
  }

  /**
   * {@inheritdoc}
   */
  public function validate() {
    $errors = parent::validate();
    if (!$this
      ->usesFields()) {
      $errors[] = $this
        ->t('Views accordion requires Fields as row style');
    }
    foreach ($this->options['grouping'] as $group) {
      if (!$group['rendered'] && $group['use-grouping-header']) {
        $errors[] = $this
          ->t('Views accordion requires "Use rendered output to group rows" enabled in order to use the group header as the Accordion header.');
      }

      // @TODO handle multiple grouping.
      break;
    }
    if ($this->options['collapsible'] !== 1 && $this->options['row-start-open'] === 'none') {
      $errors[] = $this
        ->t('Setting "Row to display opened on start" to "None" requires "Collapsible" to be enabled.');
    }
    return $errors;
  }

}

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::create public static function Creates an instance of the plugin. Overrides ContainerFactoryPluginInterface::create 62
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.
PluginBase::__construct public function Constructs a PluginBase object. 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::$usesFields protected property Does the style plugin for itself support to add fields to its output. 3
StylePluginBase::$usesGrouping protected property Does the style plugin support grouping of rows. 3
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::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::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.
ViewsAccordion::$usesRowClass protected property Does the style plugin support custom css class for the rows. Overrides StylePluginBase::$usesRowClass
ViewsAccordion::$usesRowPlugin protected property Whether or not this style uses a row plugin. Overrides StylePluginBase::$usesRowPlugin
ViewsAccordion::buildOptionsForm public function Provide a form to edit options for this plugin. Overrides StylePluginBase::buildOptionsForm
ViewsAccordion::defineOptions protected function Set default options. Overrides StylePluginBase::defineOptions
ViewsAccordion::preRender public function Allow the style to do stuff before each row is rendered. Overrides StylePluginBase::preRender
ViewsAccordion::render public function Render the display in this style. Overrides StylePluginBase::render
ViewsAccordion::validate public function Validate that the plugin is correct and can be saved. Overrides StylePluginBase::validate