3 namespace Drupal\views\Plugin\views\argument;
5 use Drupal\Component\Plugin\DependentPluginInterface;
6 use Drupal\Component\Utility\Html;
7 use Drupal\Component\Utility\NestedArray;
8 use Drupal\Core\Cache\Cache;
9 use Drupal\Core\Cache\CacheableDependencyInterface;
10 use Drupal\Core\Form\FormStateInterface;
11 use Drupal\Core\Render\Element;
12 use Drupal\views\Plugin\views\display\DisplayPluginBase;
13 use Drupal\views\ViewExecutable;
14 use Drupal\views\Plugin\views\HandlerBase;
15 use Drupal\views\Views;
18 * @defgroup views_argument_handlers Views argument handlers
20 * Handler plugins for Views contextual filters.
22 * Handler plugins help build the view query object. Views argument handlers
23 * are for contextual filtering.
25 * Views argument handlers extend
26 * \Drupal\views\Plugin\views\argument\ArgumentPluginBase. They must be
27 * annotated with \Drupal\views\Annotation\ViewsArgument annotation, and they
28 * must be in namespace directory Plugin\views\argument.
30 * @ingroup views_plugins
35 * Base class for argument (contextual filter) handler plugins.
37 * The basic argument works for very simple arguments such as nid and uid
39 * Definition terms for this handler:
40 * - name field: The field to use for the name to use in the summary, which is
41 * the displayed output. For example, for the node: nid argument,
42 * the argument itself is the nid, but node.title is displayed.
43 * - name table: The table to use for the name, should it not be in the same
44 * table as the argument.
45 * - empty field name: For arguments that can have no value, such as taxonomy
46 * which can have "no term", this is the string which
47 * will be displayed for this lack of value. Be sure to use
49 * - validate type: A little used string to allow an argument to restrict
50 * which validator is available to just one. Use the
51 * validator ID. This probably should not be used at all,
52 * and may disappear or change.
53 * - numeric: If set to TRUE this field is numeric and will use %d instead of
56 abstract class ArgumentPluginBase extends HandlerBase implements CacheableDependencyInterface {
58 public $validator = NULL;
59 public $argument = NULL;
63 * The table to use for the name, should it not be in the same table as the argument.
69 * The field to use for the name to use in the summary, which is
70 * the displayed output. For example, for the node: nid argument,
71 * the argument itself is the nid, but node.title is displayed.
77 * Overrides Drupal\views\Plugin\views\HandlerBase:init().
79 public function init(ViewExecutable $view, DisplayPluginBase $display, array &$options = NULL) {
80 parent::init($view, $display, $options);
82 if (!empty($this->definition['name field'])) {
83 $this->name_field = $this->definition['name field'];
85 if (!empty($this->definition['name table'])) {
86 $this->name_table = $this->definition['name table'];
90 public function isException($arg = NULL) {
92 $arg = isset($this->argument) ? $this->argument : NULL;
94 return !empty($this->options['exception']['value']) && $this->options['exception']['value'] === $arg;
97 public function exceptionTitle() {
98 // If title overriding is off for the exception, return the normal title.
99 if (empty($this->options['exception']['title_enable'])) {
100 return $this->getTitle();
102 return $this->options['exception']['title'];
106 * Determine if the argument needs a style plugin.
110 public function needsStylePlugin() {
111 $info = $this->defaultActions($this->options['default_action']);
112 $validate_info = $this->defaultActions($this->options['validate']['fail']);
113 return !empty($info['style plugin']) || !empty($validate_info['style plugin']);
116 protected function defineOptions() {
117 $options = parent::defineOptions();
119 $options['default_action'] = ['default' => 'ignore'];
120 $options['exception'] = [
122 'value' => ['default' => 'all'],
123 'title_enable' => ['default' => FALSE],
124 'title' => ['default' => 'All'],
127 $options['title_enable'] = ['default' => FALSE];
128 $options['title'] = ['default' => ''];
129 $options['default_argument_type'] = ['default' => 'fixed'];
130 $options['default_argument_options'] = ['default' => []];
131 $options['default_argument_skip_url'] = ['default' => FALSE];
132 $options['summary_options'] = ['default' => []];
133 $options['summary'] = [
135 'sort_order' => ['default' => 'asc'],
136 'number_of_records' => ['default' => 0],
137 'format' => ['default' => 'default_summary'],
140 $options['specify_validation'] = ['default' => FALSE];
141 $options['validate'] = [
143 'type' => ['default' => 'none'],
144 'fail' => ['default' => 'not found'],
147 $options['validate_options'] = ['default' => []];
152 public function buildOptionsForm(&$form, FormStateInterface $form_state) {
153 parent::buildOptionsForm($form, $form_state);
155 $argument_text = $this->view->display_handler->getArgumentText();
157 $form['#pre_render'][] = [get_class($this), 'preRenderMoveArgumentOptions'];
159 $form['description'] = [
160 '#markup' => $argument_text['description'],
161 '#theme_wrappers' => ['container'],
162 '#attributes' => ['class' => ['description']],
165 $form['no_argument'] = [
166 '#type' => 'details',
167 '#title' => $argument_text['filter value not present'],
170 // Everything in the details is floated, so the last element needs to
171 // clear those floats.
172 $form['no_argument']['clearfix'] = [
174 '#markup' => '<div class="clearfix"></div>',
176 $form['default_action'] = [
177 '#title' => $this->t('Default actions'),
178 '#title_display' => 'invisible',
180 '#process' => [[$this, 'processContainerRadios']],
181 '#default_value' => $this->options['default_action'],
182 '#fieldset' => 'no_argument',
185 $form['exception'] = [
186 '#type' => 'details',
187 '#title' => $this->t('Exceptions'),
188 '#fieldset' => 'no_argument',
190 $form['exception']['value'] = [
191 '#type' => 'textfield',
192 '#title' => $this->t('Exception value'),
194 '#default_value' => $this->options['exception']['value'],
195 '#description' => $this->t('If this value is received, the filter will be ignored; i.e, "all values"'),
197 $form['exception']['title_enable'] = [
198 '#type' => 'checkbox',
199 '#title' => $this->t('Override title'),
200 '#default_value' => $this->options['exception']['title_enable'],
202 $form['exception']['title'] = [
203 '#type' => 'textfield',
204 '#title' => $this->t('Override title'),
205 '#title_display' => 'invisible',
207 '#default_value' => $this->options['exception']['title'],
208 '#description' => $this->t('Override the view and other argument titles. You may use Twig syntax in this field as well as the "arguments" and "raw_arguments" arrays.'),
211 ':input[name="options[exception][title_enable]"]' => ['checked' => TRUE],
217 $defaults = $this->defaultActions();
218 $validate_options = [];
219 foreach ($defaults as $id => $info) {
220 $options[$id] = $info['title'];
221 if (empty($info['default only'])) {
222 $validate_options[$id] = $info['title'];
224 if (!empty($info['form method'])) {
225 $this->{$info['form method']}($form, $form_state);
228 $form['default_action']['#options'] = $options;
230 $form['argument_present'] = [
231 '#type' => 'details',
232 '#title' => $argument_text['filter value present'],
235 $form['title_enable'] = [
236 '#type' => 'checkbox',
237 '#title' => $this->t('Override title'),
238 '#default_value' => $this->options['title_enable'],
239 '#fieldset' => 'argument_present',
242 '#type' => 'textfield',
243 '#title' => $this->t('Provide title'),
244 '#title_display' => 'invisible',
245 '#default_value' => $this->options['title'],
246 '#description' => $this->t('Override the view and other argument titles. You may use Twig syntax in this field.'),
249 ':input[name="options[title_enable]"]' => ['checked' => TRUE],
252 '#fieldset' => 'argument_present',
255 $output = $this->getTokenHelp();
256 $form['token_help'] = [
257 '#type' => 'details',
258 '#title' => $this->t('Replacement patterns'),
263 ':input[name="options[title_enable]"]' => ['checked' => TRUE],
266 ':input[name="options[exception][title_enable]"]' => ['checked' => TRUE],
272 $form['specify_validation'] = [
273 '#type' => 'checkbox',
274 '#title' => $this->t('Specify validation criteria'),
275 '#default_value' => $this->options['specify_validation'],
276 '#fieldset' => 'argument_present',
279 $form['validate'] = [
280 '#type' => 'container',
281 '#fieldset' => 'argument_present',
283 // Validator options include derivatives with :. These are sanitized for js
284 // and reverted on submission.
285 $form['validate']['type'] = [
287 '#title' => $this->t('Validator'),
288 '#default_value' => static::encodeValidatorId($this->options['validate']['type']),
291 ':input[name="options[specify_validation]"]' => ['checked' => TRUE],
296 $plugins = Views::pluginManager('argument_validator')->getDefinitions();
297 foreach ($plugins as $id => $info) {
298 if (!empty($info['no_ui'])) {
303 if (!empty($info['type'])) {
305 if (empty($this->definition['validate type'])) {
308 foreach ((array) $info['type'] as $type) {
309 if ($type == $this->definition['validate type']) {
316 // If we decide this validator is ok, add it to the list.
318 $plugin = $this->getPlugin('argument_validator', $id);
320 if ($plugin->access() || $this->options['validate']['type'] == $id) {
321 // Sanitize ID for js.
322 $sanitized_id = static::encodeValidatorId($id);
323 $form['validate']['options'][$sanitized_id] = [
324 '#prefix' => '<div id="edit-options-validate-options-' . $sanitized_id . '-wrapper">',
325 '#suffix' => '</div>',
327 // Even if the plugin has no options add the key to the form_state.
328 // trick it into checking input to make #process run.
332 ':input[name="options[specify_validation]"]' => ['checked' => TRUE],
333 ':input[name="options[validate][type]"]' => ['value' => $sanitized_id],
336 '#id' => 'edit-options-validate-options-' . $sanitized_id,
337 '#default_value' => [],
339 $plugin->buildOptionsForm($form['validate']['options'][$sanitized_id], $form_state);
340 $validate_types[$sanitized_id] = $info['title'];
346 asort($validate_types);
347 $form['validate']['type']['#options'] = $validate_types;
349 $form['validate']['fail'] = [
351 '#title' => $this->t('Action to take if filter value does not validate'),
352 '#default_value' => $this->options['validate']['fail'],
353 '#options' => $validate_options,
356 ':input[name="options[specify_validation]"]' => ['checked' => TRUE],
359 '#fieldset' => 'argument_present',
364 * Provide token help information for the argument.
369 protected function getTokenHelp() {
372 foreach ($this->view->display_handler->getHandlers('argument') as $arg => $handler) {
373 /** @var \Drupal\views\Plugin\views\argument\ArgumentPluginBase $handler */
374 $options[(string) t('Arguments')]["{{ arguments.$arg }}"] = $this->t('@argument title', ['@argument' => $handler->adminLabel()]);
375 $options[(string) t('Arguments')]["{{ raw_arguments.$arg }}"] = $this->t('@argument input', ['@argument' => $handler->adminLabel()]);
378 // We have some options, so make a list.
379 if (!empty($options)) {
381 '#markup' => '<p>' . $this->t("The following replacement tokens are available for this argument.") . '</p>',
383 foreach (array_keys($options) as $type) {
384 if (!empty($options[$type])) {
386 foreach ($options[$type] as $key => $value) {
387 $items[] = $key . ' == ' . $value;
390 '#theme' => 'item_list',
393 $output[] = $item_list;
402 public function validateOptionsForm(&$form, FormStateInterface $form_state) {
403 $option_values = &$form_state->getValue('options');
404 if (empty($option_values)) {
408 // Let the plugins do validation.
409 $default_id = $option_values['default_argument_type'];
410 $plugin = $this->getPlugin('argument_default', $default_id);
412 $plugin->validateOptionsForm($form['argument_default'][$default_id], $form_state, $option_values['argument_default'][$default_id]);
416 $summary_id = $option_values['summary']['format'];
417 $plugin = $this->getPlugin('style', $summary_id);
419 $plugin->validateOptionsForm($form['summary']['options'][$summary_id], $form_state, $option_values['summary']['options'][$summary_id]);
422 $sanitized_id = $option_values['validate']['type'];
423 // Correct ID for js sanitized version.
424 $validate_id = static::decodeValidatorId($sanitized_id);
425 $plugin = $this->getPlugin('argument_validator', $validate_id);
427 $plugin->validateOptionsForm($form['validate']['options'][$default_id], $form_state, $option_values['validate']['options'][$sanitized_id]);
432 public function submitOptionsForm(&$form, FormStateInterface $form_state) {
433 $option_values = &$form_state->getValue('options');
434 if (empty($option_values)) {
438 // Let the plugins make submit modifications if necessary.
439 $default_id = $option_values['default_argument_type'];
440 $plugin = $this->getPlugin('argument_default', $default_id);
442 $options = &$option_values['argument_default'][$default_id];
443 $plugin->submitOptionsForm($form['argument_default'][$default_id], $form_state, $options);
444 // Copy the now submitted options to their final resting place so they get saved.
445 $option_values['default_argument_options'] = $options;
449 $summary_id = $option_values['summary']['format'];
450 $plugin = $this->getPlugin('style', $summary_id);
452 $options = &$option_values['summary']['options'][$summary_id];
453 $plugin->submitOptionsForm($form['summary']['options'][$summary_id], $form_state, $options);
454 // Copy the now submitted options to their final resting place so they get saved.
455 $option_values['summary_options'] = $options;
458 // If the 'Specify validation criteria' checkbox is not checked, reset the
459 // validation options.
460 if (empty($option_values['specify_validation'])) {
461 $option_values['validate']['type'] = 'none';
462 // We need to keep the empty array of options for the 'None' plugin as
463 // it will be needed later.
464 $option_values['validate']['options'] = ['none' => []];
465 $option_values['validate']['fail'] = 'not found';
468 $sanitized_id = $option_values['validate']['type'];
469 // Correct ID for js sanitized version.
470 $option_values['validate']['type'] = $validate_id = static::decodeValidatorId($sanitized_id);
471 $plugin = $this->getPlugin('argument_validator', $validate_id);
473 $options = &$option_values['validate']['options'][$sanitized_id];
474 $plugin->submitOptionsForm($form['validate']['options'][$sanitized_id], $form_state, $options);
475 // Copy the now submitted options to their final resting place so they get saved.
476 $option_values['validate_options'] = $options;
479 // Clear out the content of title if it's not enabled.
480 if (empty($option_values['title_enable'])) {
481 $option_values['title'] = '';
486 * Provide a list of default behaviors for this argument if the argument
489 * Override this method to provide additional (or fewer) default behaviors.
491 protected function defaultActions($which = NULL) {
494 'title' => $this->t('Display all results for the specified field'),
495 'method' => 'defaultIgnore',
498 'title' => $this->t('Provide default value'),
499 'method' => 'defaultDefault',
500 'form method' => 'defaultArgumentForm',
501 'has default argument' => TRUE,
502 // This can only be used for missing argument, not validation failure.
503 'default only' => TRUE,
506 'title' => $this->t('Hide view'),
507 'method' => 'defaultNotFound',
508 // This is a hard fail condition.
512 'title' => $this->t('Display a summary'),
513 'method' => 'defaultSummary',
514 'form method' => 'defaultSummaryForm',
515 'style plugin' => TRUE,
518 'title' => $this->t('Display contents of "No results found"'),
519 'method' => 'defaultEmpty',
522 'title' => $this->t('Display "Access Denied"'),
523 'method' => 'defaultAccessDenied',
527 if ($this->view->display_handler->hasPath()) {
528 $defaults['not found']['title'] = $this->t('Show "Page not found"');
532 if (!empty($defaults[$which])) {
533 return $defaults[$which];
542 * Provide a form for selecting the default argument when the
543 * default action is set to provide default argument.
545 public function defaultArgumentForm(&$form, FormStateInterface $form_state) {
546 $plugins = Views::pluginManager('argument_default')->getDefinitions();
549 $form['default_argument_skip_url'] = [
550 '#type' => 'checkbox',
551 '#title' => $this->t('Skip default argument for view URL'),
552 '#default_value' => $this->options['default_argument_skip_url'],
553 '#description' => $this->t('Select whether to include this default argument when constructing the URL for this view. Skipping default arguments is useful e.g. in the case of feeds.')
556 $form['default_argument_type'] = [
557 '#prefix' => '<div id="edit-options-default-argument-type-wrapper">',
558 '#suffix' => '</div>',
560 '#id' => 'edit-options-default-argument-type',
561 '#title' => $this->t('Type'),
562 '#default_value' => $this->options['default_argument_type'],
565 ':input[name="options[default_action]"]' => ['value' => 'default'],
568 // Views custom key, moves this element to the appropriate container
569 // under the radio button.
570 '#argument_option' => 'default',
573 foreach ($plugins as $id => $info) {
574 if (!empty($info['no_ui'])) {
577 $plugin = $this->getPlugin('argument_default', $id);
579 if ($plugin->access() || $this->options['default_argument_type'] == $id) {
580 $form['argument_default']['#argument_option'] = 'default';
581 $form['argument_default'][$id] = [
582 '#prefix' => '<div id="edit-options-argument-default-options-' . $id . '-wrapper">',
583 '#suffix' => '</div>',
584 '#id' => 'edit-options-argument-default-options-' . $id,
586 // Even if the plugin has no options add the key to the form_state.
590 ':input[name="options[default_action]"]' => ['value' => 'default'],
591 ':input[name="options[default_argument_type]"]' => ['value' => $id],
594 '#default_value' => [],
596 $options[$id] = $info['title'];
597 $plugin->buildOptionsForm($form['argument_default'][$id], $form_state);
603 $form['default_argument_type']['#options'] = $options;
607 * Provide a form for selecting further summary options when the
608 * default action is set to display one.
610 public function defaultSummaryForm(&$form, FormStateInterface $form_state) {
611 $style_plugins = Views::pluginManager('style')->getDefinitions();
612 $summary_plugins = [];
613 $format_options = [];
614 foreach ($style_plugins as $key => $plugin) {
615 if (isset($plugin['display_types']) && in_array('summary', $plugin['display_types'])) {
616 $summary_plugins[$key] = $plugin;
617 $format_options[$key] = $plugin['title'];
622 // Views custom key, moves this element to the appropriate container
623 // under the radio button.
624 '#argument_option' => 'summary',
626 $form['summary']['sort_order'] = [
628 '#title' => $this->t('Sort order'),
629 '#options' => ['asc' => $this->t('Ascending'), 'desc' => $this->t('Descending')],
630 '#default_value' => $this->options['summary']['sort_order'],
633 ':input[name="options[default_action]"]' => ['value' => 'summary'],
637 $form['summary']['number_of_records'] = [
639 '#title' => $this->t('Sort by'),
640 '#default_value' => $this->options['summary']['number_of_records'],
642 0 => $this->getSortName(),
643 1 => $this->t('Number of records')
647 ':input[name="options[default_action]"]' => ['value' => 'summary'],
652 $form['summary']['format'] = [
654 '#title' => $this->t('Format'),
655 '#options' => $format_options,
656 '#default_value' => $this->options['summary']['format'],
659 ':input[name="options[default_action]"]' => ['value' => 'summary'],
664 foreach ($summary_plugins as $id => $info) {
665 $plugin = $this->getPlugin('style', $id);
666 if (!$plugin->usesOptions()) {
670 $form['summary']['options'][$id] = [
671 '#prefix' => '<div id="edit-options-summary-options-' . $id . '-wrapper">',
672 '#suffix' => '</div>',
673 '#id' => 'edit-options-summary-options-' . $id,
675 // Trick it into checking input to make #process run.
679 ':input[name="options[default_action]"]' => ['value' => 'summary'],
680 ':input[name="options[summary][format]"]' => ['value' => $id],
683 '#default_value' => [],
685 $options[$id] = $info['title'];
686 $plugin->buildOptionsForm($form['summary']['options'][$id], $form_state);
692 * Handle the default action, which means our argument wasn't present.
694 * Override this method only with extreme care.
697 * A boolean value; if TRUE, continue building this view. If FALSE,
698 * building the view will be aborted here.
700 public function defaultAction($info = NULL) {
702 $info = $this->defaultActions($this->options['default_action']);
709 if (!empty($info['method args'])) {
710 return call_user_func_array([&$this, $info['method']], $info['method args']);
713 return $this->{$info['method']}();
718 * How to act if validation fails.
720 public function validateFail() {
721 $info = $this->defaultActions($this->options['validate']['fail']);
722 return $this->defaultAction($info);
725 * Default action: ignore.
727 * If an argument was expected and was not given, in this case, simply
728 * ignore the argument entirely.
730 public function defaultIgnore() {
735 * Default action: not found.
737 * If an argument was expected and was not given, in this case, report
738 * the view as 'not found' or hide it.
740 protected function defaultNotFound() {
741 // Set a failure condition and let the display manager handle it.
742 $this->view->build_info['fail'] = TRUE;
747 * Default action: access denied.
749 * If an argument was expected and was not given, in this case, report
750 * the view as 'access denied'.
752 public function defaultAccessDenied() {
753 $this->view->build_info['denied'] = TRUE;
758 * Default action: empty
760 * If an argument was expected and was not given, in this case, display
761 * the view's empty text
763 public function defaultEmpty() {
764 // We return with no query; this will force the empty text.
765 $this->view->built = TRUE;
766 $this->view->executed = TRUE;
767 $this->view->result = [];
772 * This just returns true. The view argument builder will know where
773 * to find the argument from.
775 protected function defaultDefault() {
780 * Determine if the argument is set to provide a default argument.
782 public function hasDefaultArgument() {
783 $info = $this->defaultActions($this->options['default_action']);
784 return !empty($info['has default argument']);
788 * Get a default argument, if available.
790 public function getDefaultArgument() {
791 $plugin = $this->getPlugin('argument_default');
793 return $plugin->getArgument();
798 * Process the summary arguments for display.
800 * For example, the validation plugin may want to alter an argument for use in
803 public function processSummaryArguments(&$args) {
804 if ($this->options['validate']['type'] != 'none') {
805 if (isset($this->validator) || $this->validator = $this->getPlugin('argument_validator')) {
806 $this->validator->processSummaryArguments($args);
812 * Default action: summary.
814 * If an argument was expected and was not given, in this case, display
817 protected function defaultSummary() {
818 $this->view->build_info['summary'] = TRUE;
819 $this->view->build_info['summary_level'] = $this->options['id'];
821 // Change the display style to the summary style for this
823 $this->view->style_plugin = Views::pluginManager("style")->createInstance($this->options['summary']['format']);
824 $this->view->style_plugin->init($this->view, $this->displayHandler, $this->options['summary_options']);
826 // Clear out the normal primary field and whatever else may have
827 // been added and let the summary do the work.
828 $this->query->clearFields();
829 $this->summaryQuery();
831 $by = $this->options['summary']['number_of_records'] ? 'num_records' : NULL;
832 $this->summarySort($this->options['summary']['sort_order'], $by);
834 // Summaries have their own sorting and fields, so tell the View not
836 $this->view->build_sort = FALSE;
841 * Build the info for the summary query.
844 * - addGroupBy: group on this field in order to create summaries.
845 * - addField: add a 'num_nodes' field for the count. Usually it will
846 * be a count on $view->base_field
847 * - setCountField: Reset the count field so we get the right paging.
850 * The alias used to get the number of records (count) for this entry.
852 protected function summaryQuery() {
853 $this->ensureMyTable();
855 $this->base_alias = $this->query->addField($this->tableAlias, $this->realField);
857 $this->summaryNameField();
858 return $this->summaryBasics();
862 * Add the name field, which is the field displayed in summary queries.
863 * This is often used when the argument is numeric.
865 protected function summaryNameField() {
866 // Add the 'name' field. For example, if this is a uid argument, the
867 // name field would be 'name' (i.e, the username).
869 if (isset($this->name_table)) {
870 // if the alias is different then we're probably added, not ensured,
871 // so look up the join and add it instead.
872 if ($this->tableAlias != $this->name_table) {
873 $j = HandlerBase::getTableJoin($this->name_table, $this->table);
876 $join->leftTable = $this->tableAlias;
877 $this->name_table_alias = $this->query->addTable($this->name_table, $this->relationship, $join);
881 $this->name_table_alias = $this->query->ensureTable($this->name_table, $this->relationship);
885 $this->name_table_alias = $this->tableAlias;
888 if (isset($this->name_field)) {
889 $this->name_alias = $this->query->addField($this->name_table_alias, $this->name_field);
892 $this->name_alias = $this->base_alias;
897 * Some basic summary behavior that doesn't need to be repeated as much as
898 * code that goes into summaryQuery()
900 public function summaryBasics($count_field = TRUE) {
901 // Add the number of nodes counter
902 $distinct = ($this->view->display_handler->getOption('distinct') && empty($this->query->no_distinct));
904 $count_alias = $this->query->addField($this->view->storage->get('base_table'), $this->view->storage->get('base_field'), 'num_records', ['count' => TRUE, 'distinct' => $distinct]);
905 $this->query->addGroupBy($this->name_alias);
908 $this->query->setCountField($this->tableAlias, $this->realField);
911 $this->count_alias = $count_alias;
915 * Sorts the summary based upon the user's selection. The base variant of
916 * this is usually adequate.
919 * The order selected in the UI.
921 public function summarySort($order, $by = NULL) {
922 $this->query->addOrderBy(NULL, NULL, $order, (!empty($by) ? $by : $this->name_alias));
926 * Provide the argument to use to link from the summary to the next level;
927 * this will be called once per row of a summary, and used as part of
931 * The query results for the row.
933 public function summaryArgument($data) {
934 return $data->{$this->base_alias};
938 * Provides the name to use for the summary. By default this is just
942 * The query results for the row.
944 public function summaryName($data) {
945 $value = $data->{$this->name_alias};
946 if (empty($value) && !empty($this->definition['empty field name'])) {
947 $value = $this->definition['empty field name'];
953 * Set up the query for this argument.
955 * The argument sent may be found at $this->argument.
957 public function query($group_by = FALSE) {
958 $this->ensureMyTable();
959 $this->query->addWhere(0, "$this->tableAlias.$this->realField", $this->argument);
963 * Get the title this argument will assign the view, given the argument.
965 * This usually needs to be overridden to provide a proper title.
967 public function title() {
968 return $this->argument;
972 * Called by the view object to get the title. This may be set by a
973 * validator so we don't necessarily call through to title().
975 public function getTitle() {
976 if (isset($this->validated_title)) {
977 return $this->validated_title;
980 return $this->title();
985 * Validate that this argument works. By default, all arguments are valid.
987 public function validateArgument($arg) {
988 // By using % in URLs, arguments could be validated twice; this eases
990 if (isset($this->argument_validated)) {
991 return $this->argument_validated;
994 if ($this->isException($arg)) {
995 return $this->argument_validated = TRUE;
998 $plugin = $this->getPlugin('argument_validator');
999 return $this->argument_validated = $plugin->validateArgument($arg);
1003 * Called by the menu system to validate an argument.
1005 * This checks to see if this is a 'soft fail', which means that if the
1006 * argument fails to validate, but there is an action to take anyway,
1007 * then validation cannot actually fail.
1009 public function validateMenuArgument($arg) {
1010 $validate_info = $this->defaultActions($this->options['validate']['fail']);
1011 if (empty($validate_info['hard fail'])) {
1015 $rc = $this->validateArgument($arg);
1017 // If the validator has changed the validate fail condition to a
1018 // soft fail, deal with that:
1019 $validate_info = $this->defaultActions($this->options['validate']['fail']);
1020 if (empty($validate_info['hard fail'])) {
1028 * Set the input for this argument
1030 * @return TRUE if it successfully validates; FALSE if it does not.
1032 public function setArgument($arg) {
1033 $this->argument = $arg;
1034 return $this->validateArgument($arg);
1038 * Get the value of this argument.
1040 public function getValue() {
1041 // If we already processed this argument, we're done.
1042 if (isset($this->argument)) {
1043 return $this->argument;
1046 // Otherwise, we have to pretend to process ourselves to find the value.
1048 // Find the position of this argument within the view.
1050 foreach ($this->view->argument as $id => $argument) {
1051 if ($id == $this->options['id']) {
1057 $arg = isset($this->view->args[$position]) ? $this->view->args[$position] : NULL;
1058 $this->position = $position;
1060 // Clone ourselves so that we don't break things when we're really
1061 // processing the arguments.
1062 $argument = clone $this;
1063 if (!isset($arg) && $argument->hasDefaultArgument()) {
1064 $arg = $argument->getDefaultArgument();
1066 // remember that this argument was computed, not passed on the URL.
1067 $this->is_default = TRUE;
1069 // Set the argument, which will also validate that the argument can be set.
1070 if ($argument->setArgument($arg)) {
1071 $value = $argument->argument;
1078 * Get the display or row plugin, if it exists.
1080 public function getPlugin($type = 'argument_default', $name = NULL) {
1083 case 'argument_default':
1084 if (!isset($this->options['default_argument_type'])) {
1087 $plugin_name = $this->options['default_argument_type'];
1088 $options_name = 'default_argument_options';
1090 case 'argument_validator':
1091 if (!isset($this->options['validate']['type'])) {
1094 $plugin_name = $this->options['validate']['type'];
1095 $options_name = 'validate_options';
1098 if (!isset($this->options['summary']['format'])) {
1101 $plugin_name = $this->options['summary']['format'];
1102 $options_name = 'summary_options';
1106 $name = $plugin_name;
1109 // we only fetch the options if we're fetching the plugin actually
1111 if ($name == $plugin_name) {
1112 $options = isset($this->options[$options_name]) ? $this->options[$options_name] : [];
1115 $plugin = Views::pluginManager($type)->createInstance($name);
1117 $plugin->init($this->view, $this->displayHandler, $options);
1119 if ($type !== 'style') {
1120 // It's an argument_default/argument_validate plugin, so set the argument.
1121 $plugin->setArgument($this);
1128 * Return a description of how the argument would normally be sorted.
1130 * Subclasses should override this to specify what the default sort order of
1131 * their argument is (e.g. alphabetical, numeric, date).
1133 public function getSortName() {
1134 return $this->t('Default sort', [], ['context' => 'Sort order']);
1138 * Custom form radios process function.
1140 * Roll out a single radios element to a list of radios, using the options
1141 * array as index. While doing that, create a container element underneath
1142 * each option, which contains the settings related to that option.
1144 * @see \Drupal\Core\Render\Element\Radios::processRadios()
1146 public static function processContainerRadios($element) {
1147 if (count($element['#options']) > 0) {
1148 foreach ($element['#options'] as $key => $choice) {
1149 $element += [$key => []];
1150 // Generate the parents as the autogenerator does, so we will have a
1151 // unique id for each radio button.
1152 $parents_for_id = array_merge($element['#parents'], [$key]);
1156 '#title' => $choice,
1157 // The key is sanitized in drupal_attributes() during output from the
1159 '#return_value' => $key,
1160 '#default_value' => isset($element['#default_value']) ? $element['#default_value'] : NULL,
1161 '#attributes' => $element['#attributes'],
1162 '#parents' => $element['#parents'],
1163 '#id' => Html::getUniqueId('edit-' . implode('-', $parents_for_id)),
1164 '#ajax' => isset($element['#ajax']) ? $element['#ajax'] : NULL,
1166 $element[$key . '_options'] = [
1167 '#type' => 'container',
1168 '#attributes' => ['class' => ['views-admin-dependent']],
1176 * Moves argument options into their place.
1178 * When configuring the default argument behavior, almost each of the radio
1179 * buttons has its own fieldset shown below it when the radio button is
1180 * clicked. That fieldset is created through a custom form process callback.
1181 * Each element that has #argument_option defined and pointing to a default
1182 * behavior gets moved to the appropriate fieldset.
1183 * So if #argument_option is specified as 'default', the element is moved
1184 * to the 'default_options' fieldset.
1186 public static function preRenderMoveArgumentOptions($form) {
1187 foreach (Element::children($form) as $key) {
1188 $element = $form[$key];
1189 if (!empty($element['#argument_option'])) {
1190 $container_name = $element['#argument_option'] . '_options';
1191 if (isset($form['no_argument']['default_action'][$container_name])) {
1192 $form['no_argument']['default_action'][$container_name][$key] = $element;
1194 // Remove the original element this duplicates.
1203 * Sanitize validator options including derivatives with : for js.
1205 * Reason and alternative: https://www.drupal.org/node/2035345.
1208 * The identifier to be sanitized.
1211 * The sanitized identifier.
1213 * @see decodeValidatorId()
1215 public static function encodeValidatorId($id) {
1216 return str_replace(':', '---', $id);
1220 * Revert sanitized validator options.
1223 * The sanitized identifier to be reverted.
1226 * The original identifier.
1228 public static function decodeValidatorId($id) {
1229 return str_replace('---', ':', $id);
1233 * Splits an argument into value and operator properties on this instance.
1235 * @param bool $force_int
1236 * Enforce that values should be numeric.
1238 protected function unpackArgumentValue($force_int = FALSE) {
1239 $break = static::breakString($this->argument, $force_int);
1240 $this->value = $break->value;
1241 $this->operator = $break->operator;
1247 public function getCacheMaxAge() {
1248 $max_age = Cache::PERMANENT;
1250 // Asks all subplugins (argument defaults, argument validator and styles).
1251 if (($plugin = $this->getPlugin('argument_default')) && $plugin instanceof CacheableDependencyInterface) {
1252 $max_age = Cache::mergeMaxAges($max_age, $plugin->getCacheMaxAge());
1255 if (($plugin = $this->getPlugin('argument_validator')) && $plugin instanceof CacheableDependencyInterface) {
1256 $max_age = Cache::mergeMaxAges($max_age, $plugin->getCacheMaxAge());
1259 // Summaries use style plugins.
1260 if (($plugin = $this->getPlugin('style')) && $plugin instanceof CacheableDependencyInterface) {
1261 $max_age = Cache::mergeMaxAges($max_age, $plugin->getCacheMaxAge());
1270 public function getCacheContexts() {
1272 // By definition arguments depends on the URL.
1273 // @todo Once contexts are properly injected into block views we could pull
1274 // the information from there.
1275 $contexts[] = 'url';
1277 // Asks all subplugins (argument defaults, argument validator and styles).
1278 if (($plugin = $this->getPlugin('argument_default')) && $plugin instanceof CacheableDependencyInterface) {
1279 $contexts = Cache::mergeContexts($contexts, $plugin->getCacheContexts());
1282 if (($plugin = $this->getPlugin('argument_validator')) && $plugin instanceof CacheableDependencyInterface) {
1283 $contexts = Cache::mergeContexts($contexts, $plugin->getCacheContexts());
1286 if (($plugin = $this->getPlugin('style')) && $plugin instanceof CacheableDependencyInterface) {
1287 $contexts = Cache::mergeContexts($contexts, $plugin->getCacheContexts());
1296 public function getCacheTags() {
1299 // Asks all subplugins (argument defaults, argument validator and styles).
1300 if (($plugin = $this->getPlugin('argument_default')) && $plugin instanceof CacheableDependencyInterface) {
1301 $tags = Cache::mergeTags($tags, $plugin->getCacheTags());
1304 if (($plugin = $this->getPlugin('argument_validator')) && $plugin instanceof CacheableDependencyInterface) {
1305 $tags = Cache::mergeTags($tags, $plugin->getCacheTags());
1308 if (($plugin = $this->getPlugin('style')) && $plugin instanceof CacheableDependencyInterface) {
1309 $tags = Cache::mergeTags($tags, $plugin->getCacheTags());
1318 public function calculateDependencies() {
1320 if (($argument_default = $this->getPlugin('argument_default')) && $argument_default instanceof DependentPluginInterface) {
1321 $dependencies = NestedArray::mergeDeep($dependencies, $argument_default->calculateDependencies());
1323 if (($argument_validator = $this->getPlugin('argument_validator')) && $argument_validator instanceof DependentPluginInterface) {
1324 $dependencies = NestedArray::mergeDeep($dependencies, $argument_validator->calculateDependencies());
1326 if (($style = $this->getPlugin('style')) && $style instanceof DependentPluginInterface) {
1327 $dependencies = NestedArray::mergeDeep($dependencies, $style->calculateDependencies());
1330 return $dependencies;
1334 * Returns a context definition for this argument.
1336 * @return \Drupal\Core\Plugin\Context\ContextDefinitionInterface|null
1337 * A context definition that represents the argument or NULL if that is
1340 public function getContextDefinition() {
1341 return $this->getPlugin('argument_validator')->getContextDefinition();