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 '#input' => TRUE, // trick it into checking input to make #process run
331 ':input[name="options[specify_validation]"]' => ['checked' => TRUE],
332 ':input[name="options[validate][type]"]' => ['value' => $sanitized_id],
335 '#id' => 'edit-options-validate-options-' . $sanitized_id,
336 '#default_value' => [],
338 $plugin->buildOptionsForm($form['validate']['options'][$sanitized_id], $form_state);
339 $validate_types[$sanitized_id] = $info['title'];
345 asort($validate_types);
346 $form['validate']['type']['#options'] = $validate_types;
348 $form['validate']['fail'] = [
350 '#title' => $this->t('Action to take if filter value does not validate'),
351 '#default_value' => $this->options['validate']['fail'],
352 '#options' => $validate_options,
355 ':input[name="options[specify_validation]"]' => ['checked' => TRUE],
358 '#fieldset' => 'argument_present',
363 * Provide token help information for the argument.
368 protected function getTokenHelp() {
371 foreach ($this->view->display_handler->getHandlers('argument') as $arg => $handler) {
372 /** @var \Drupal\views\Plugin\views\argument\ArgumentPluginBase $handler */
373 $options[(string) t('Arguments')]["{{ arguments.$arg }}"] = $this->t('@argument title', ['@argument' => $handler->adminLabel()]);
374 $options[(string) t('Arguments')]["{{ raw_arguments.$arg }}"] = $this->t('@argument input', ['@argument' => $handler->adminLabel()]);
377 // We have some options, so make a list.
378 if (!empty($options)) {
380 '#markup' => '<p>' . $this->t("The following replacement tokens are available for this argument.") . '</p>',
382 foreach (array_keys($options) as $type) {
383 if (!empty($options[$type])) {
385 foreach ($options[$type] as $key => $value) {
386 $items[] = $key . ' == ' . $value;
389 '#theme' => 'item_list',
392 $output[] = $item_list;
401 public function validateOptionsForm(&$form, FormStateInterface $form_state) {
402 $option_values = &$form_state->getValue('options');
403 if (empty($option_values)) {
407 // Let the plugins do validation.
408 $default_id = $option_values['default_argument_type'];
409 $plugin = $this->getPlugin('argument_default', $default_id);
411 $plugin->validateOptionsForm($form['argument_default'][$default_id], $form_state, $option_values['argument_default'][$default_id]);
415 $summary_id = $option_values['summary']['format'];
416 $plugin = $this->getPlugin('style', $summary_id);
418 $plugin->validateOptionsForm($form['summary']['options'][$summary_id], $form_state, $option_values['summary']['options'][$summary_id]);
421 $sanitized_id = $option_values['validate']['type'];
422 // Correct ID for js sanitized version.
423 $validate_id = static::decodeValidatorId($sanitized_id);
424 $plugin = $this->getPlugin('argument_validator', $validate_id);
426 $plugin->validateOptionsForm($form['validate']['options'][$default_id], $form_state, $option_values['validate']['options'][$sanitized_id]);
431 public function submitOptionsForm(&$form, FormStateInterface $form_state) {
432 $option_values = &$form_state->getValue('options');
433 if (empty($option_values)) {
437 // Let the plugins make submit modifications if necessary.
438 $default_id = $option_values['default_argument_type'];
439 $plugin = $this->getPlugin('argument_default', $default_id);
441 $options = &$option_values['argument_default'][$default_id];
442 $plugin->submitOptionsForm($form['argument_default'][$default_id], $form_state, $options);
443 // Copy the now submitted options to their final resting place so they get saved.
444 $option_values['default_argument_options'] = $options;
448 $summary_id = $option_values['summary']['format'];
449 $plugin = $this->getPlugin('style', $summary_id);
451 $options = &$option_values['summary']['options'][$summary_id];
452 $plugin->submitOptionsForm($form['summary']['options'][$summary_id], $form_state, $options);
453 // Copy the now submitted options to their final resting place so they get saved.
454 $option_values['summary_options'] = $options;
457 // If the 'Specify validation criteria' checkbox is not checked, reset the
458 // validation options.
459 if (empty($option_values['specify_validation'])) {
460 $option_values['validate']['type'] = 'none';
461 // We need to keep the empty array of options for the 'None' plugin as
462 // it will be needed later.
463 $option_values['validate']['options'] = ['none' => []];
464 $option_values['validate']['fail'] = 'not found';
467 $sanitized_id = $option_values['validate']['type'];
468 // Correct ID for js sanitized version.
469 $option_values['validate']['type'] = $validate_id = static::decodeValidatorId($sanitized_id);
470 $plugin = $this->getPlugin('argument_validator', $validate_id);
472 $options = &$option_values['validate']['options'][$sanitized_id];
473 $plugin->submitOptionsForm($form['validate']['options'][$sanitized_id], $form_state, $options);
474 // Copy the now submitted options to their final resting place so they get saved.
475 $option_values['validate_options'] = $options;
478 // Clear out the content of title if it's not enabled.
479 if (empty($option_values['title_enable'])) {
480 $option_values['title'] = '';
485 * Provide a list of default behaviors for this argument if the argument
488 * Override this method to provide additional (or fewer) default behaviors.
490 protected function defaultActions($which = NULL) {
493 'title' => $this->t('Display all results for the specified field'),
494 'method' => 'defaultIgnore',
497 'title' => $this->t('Provide default value'),
498 'method' => 'defaultDefault',
499 'form method' => 'defaultArgumentForm',
500 'has default argument' => TRUE,
501 'default only' => TRUE, // this can only be used for missing argument, not validation failure
504 'title' => $this->t('Hide view'),
505 'method' => 'defaultNotFound',
506 'hard fail' => TRUE, // This is a hard fail condition
509 'title' => $this->t('Display a summary'),
510 'method' => 'defaultSummary',
511 'form method' => 'defaultSummaryForm',
512 'style plugin' => TRUE,
515 'title' => $this->t('Display contents of "No results found"'),
516 'method' => 'defaultEmpty',
519 'title' => $this->t('Display "Access Denied"'),
520 'method' => 'defaultAccessDenied',
524 if ($this->view->display_handler->hasPath()) {
525 $defaults['not found']['title'] = $this->t('Show "Page not found"');
529 if (!empty($defaults[$which])) {
530 return $defaults[$which];
539 * Provide a form for selecting the default argument when the
540 * default action is set to provide default argument.
542 public function defaultArgumentForm(&$form, FormStateInterface $form_state) {
543 $plugins = Views::pluginManager('argument_default')->getDefinitions();
546 $form['default_argument_skip_url'] = [
547 '#type' => 'checkbox',
548 '#title' => $this->t('Skip default argument for view URL'),
549 '#default_value' => $this->options['default_argument_skip_url'],
550 '#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.')
553 $form['default_argument_type'] = [
554 '#prefix' => '<div id="edit-options-default-argument-type-wrapper">',
555 '#suffix' => '</div>',
557 '#id' => 'edit-options-default-argument-type',
558 '#title' => $this->t('Type'),
559 '#default_value' => $this->options['default_argument_type'],
562 ':input[name="options[default_action]"]' => ['value' => 'default'],
565 // Views custom key, moves this element to the appropriate container
566 // under the radio button.
567 '#argument_option' => 'default',
570 foreach ($plugins as $id => $info) {
571 if (!empty($info['no_ui'])) {
574 $plugin = $this->getPlugin('argument_default', $id);
576 if ($plugin->access() || $this->options['default_argument_type'] == $id) {
577 $form['argument_default']['#argument_option'] = 'default';
578 $form['argument_default'][$id] = [
579 '#prefix' => '<div id="edit-options-argument-default-options-' . $id . '-wrapper">',
580 '#suffix' => '</div>',
581 '#id' => 'edit-options-argument-default-options-' . $id,
583 // Even if the plugin has no options add the key to the form_state.
587 ':input[name="options[default_action]"]' => ['value' => 'default'],
588 ':input[name="options[default_argument_type]"]' => ['value' => $id],
591 '#default_value' => [],
593 $options[$id] = $info['title'];
594 $plugin->buildOptionsForm($form['argument_default'][$id], $form_state);
600 $form['default_argument_type']['#options'] = $options;
604 * Provide a form for selecting further summary options when the
605 * default action is set to display one.
607 public function defaultSummaryForm(&$form, FormStateInterface $form_state) {
608 $style_plugins = Views::pluginManager('style')->getDefinitions();
609 $summary_plugins = [];
610 $format_options = [];
611 foreach ($style_plugins as $key => $plugin) {
612 if (isset($plugin['display_types']) && in_array('summary', $plugin['display_types'])) {
613 $summary_plugins[$key] = $plugin;
614 $format_options[$key] = $plugin['title'];
619 // Views custom key, moves this element to the appropriate container
620 // under the radio button.
621 '#argument_option' => 'summary',
623 $form['summary']['sort_order'] = [
625 '#title' => $this->t('Sort order'),
626 '#options' => ['asc' => $this->t('Ascending'), 'desc' => $this->t('Descending')],
627 '#default_value' => $this->options['summary']['sort_order'],
630 ':input[name="options[default_action]"]' => ['value' => 'summary'],
634 $form['summary']['number_of_records'] = [
636 '#title' => $this->t('Sort by'),
637 '#default_value' => $this->options['summary']['number_of_records'],
639 0 => $this->getSortName(),
640 1 => $this->t('Number of records')
644 ':input[name="options[default_action]"]' => ['value' => 'summary'],
649 $form['summary']['format'] = [
651 '#title' => $this->t('Format'),
652 '#options' => $format_options,
653 '#default_value' => $this->options['summary']['format'],
656 ':input[name="options[default_action]"]' => ['value' => 'summary'],
661 foreach ($summary_plugins as $id => $info) {
662 $plugin = $this->getPlugin('style', $id);
663 if (!$plugin->usesOptions()) {
667 $form['summary']['options'][$id] = [
668 '#prefix' => '<div id="edit-options-summary-options-' . $id . '-wrapper">',
669 '#suffix' => '</div>',
670 '#id' => 'edit-options-summary-options-' . $id,
672 '#input' => TRUE, // trick it into checking input to make #process run
675 ':input[name="options[default_action]"]' => ['value' => 'summary'],
676 ':input[name="options[summary][format]"]' => ['value' => $id],
679 '#default_value' => [],
681 $options[$id] = $info['title'];
682 $plugin->buildOptionsForm($form['summary']['options'][$id], $form_state);
688 * Handle the default action, which means our argument wasn't present.
690 * Override this method only with extreme care.
693 * A boolean value; if TRUE, continue building this view. If FALSE,
694 * building the view will be aborted here.
696 public function defaultAction($info = NULL) {
698 $info = $this->defaultActions($this->options['default_action']);
705 if (!empty($info['method args'])) {
706 return call_user_func_array([&$this, $info['method']], $info['method args']);
709 return $this->{$info['method']}();
714 * How to act if validation fails.
716 public function validateFail() {
717 $info = $this->defaultActions($this->options['validate']['fail']);
718 return $this->defaultAction($info);
721 * Default action: ignore.
723 * If an argument was expected and was not given, in this case, simply
724 * ignore the argument entirely.
726 public function defaultIgnore() {
731 * Default action: not found.
733 * If an argument was expected and was not given, in this case, report
734 * the view as 'not found' or hide it.
736 protected function defaultNotFound() {
737 // Set a failure condition and let the display manager handle it.
738 $this->view->build_info['fail'] = TRUE;
743 * Default action: access denied.
745 * If an argument was expected and was not given, in this case, report
746 * the view as 'access denied'.
748 public function defaultAccessDenied() {
749 $this->view->build_info['denied'] = TRUE;
754 * Default action: empty
756 * If an argument was expected and was not given, in this case, display
757 * the view's empty text
759 public function defaultEmpty() {
760 // We return with no query; this will force the empty text.
761 $this->view->built = TRUE;
762 $this->view->executed = TRUE;
763 $this->view->result = [];
768 * This just returns true. The view argument builder will know where
769 * to find the argument from.
771 protected function defaultDefault() {
776 * Determine if the argument is set to provide a default argument.
778 public function hasDefaultArgument() {
779 $info = $this->defaultActions($this->options['default_action']);
780 return !empty($info['has default argument']);
784 * Get a default argument, if available.
786 public function getDefaultArgument() {
787 $plugin = $this->getPlugin('argument_default');
789 return $plugin->getArgument();
794 * Process the summary arguments for display.
796 * For example, the validation plugin may want to alter an argument for use in
799 public function processSummaryArguments(&$args) {
800 if ($this->options['validate']['type'] != 'none') {
801 if (isset($this->validator) || $this->validator = $this->getPlugin('argument_validator')) {
802 $this->validator->processSummaryArguments($args);
808 * Default action: summary.
810 * If an argument was expected and was not given, in this case, display
813 protected function defaultSummary() {
814 $this->view->build_info['summary'] = TRUE;
815 $this->view->build_info['summary_level'] = $this->options['id'];
817 // Change the display style to the summary style for this
819 $this->view->style_plugin = Views::pluginManager("style")->createInstance($this->options['summary']['format']);
820 $this->view->style_plugin->init($this->view, $this->displayHandler, $this->options['summary_options']);
822 // Clear out the normal primary field and whatever else may have
823 // been added and let the summary do the work.
824 $this->query->clearFields();
825 $this->summaryQuery();
827 $by = $this->options['summary']['number_of_records'] ? 'num_records' : NULL;
828 $this->summarySort($this->options['summary']['sort_order'], $by);
830 // Summaries have their own sorting and fields, so tell the View not
832 $this->view->build_sort = FALSE;
837 * Build the info for the summary query.
840 * - addGroupBy: group on this field in order to create summaries.
841 * - addField: add a 'num_nodes' field for the count. Usually it will
842 * be a count on $view->base_field
843 * - setCountField: Reset the count field so we get the right paging.
846 * The alias used to get the number of records (count) for this entry.
848 protected function summaryQuery() {
849 $this->ensureMyTable();
851 $this->base_alias = $this->query->addField($this->tableAlias, $this->realField);
853 $this->summaryNameField();
854 return $this->summaryBasics();
858 * Add the name field, which is the field displayed in summary queries.
859 * This is often used when the argument is numeric.
861 protected function summaryNameField() {
862 // Add the 'name' field. For example, if this is a uid argument, the
863 // name field would be 'name' (i.e, the username).
865 if (isset($this->name_table)) {
866 // if the alias is different then we're probably added, not ensured,
867 // so look up the join and add it instead.
868 if ($this->tableAlias != $this->name_table) {
869 $j = HandlerBase::getTableJoin($this->name_table, $this->table);
872 $join->leftTable = $this->tableAlias;
873 $this->name_table_alias = $this->query->addTable($this->name_table, $this->relationship, $join);
877 $this->name_table_alias = $this->query->ensureTable($this->name_table, $this->relationship);
881 $this->name_table_alias = $this->tableAlias;
884 if (isset($this->name_field)) {
885 $this->name_alias = $this->query->addField($this->name_table_alias, $this->name_field);
888 $this->name_alias = $this->base_alias;
893 * Some basic summary behavior that doesn't need to be repeated as much as
894 * code that goes into summaryQuery()
896 public function summaryBasics($count_field = TRUE) {
897 // Add the number of nodes counter
898 $distinct = ($this->view->display_handler->getOption('distinct') && empty($this->query->no_distinct));
900 $count_alias = $this->query->addField($this->view->storage->get('base_table'), $this->view->storage->get('base_field'), 'num_records', ['count' => TRUE, 'distinct' => $distinct]);
901 $this->query->addGroupBy($this->name_alias);
904 $this->query->setCountField($this->tableAlias, $this->realField);
907 $this->count_alias = $count_alias;
911 * Sorts the summary based upon the user's selection. The base variant of
912 * this is usually adequate.
915 * The order selected in the UI.
917 public function summarySort($order, $by = NULL) {
918 $this->query->addOrderBy(NULL, NULL, $order, (!empty($by) ? $by : $this->name_alias));
922 * Provide the argument to use to link from the summary to the next level;
923 * this will be called once per row of a summary, and used as part of
927 * The query results for the row.
929 public function summaryArgument($data) {
930 return $data->{$this->base_alias};
934 * Provides the name to use for the summary. By default this is just
938 * The query results for the row.
940 public function summaryName($data) {
941 $value = $data->{$this->name_alias};
942 if (empty($value) && !empty($this->definition['empty field name'])) {
943 $value = $this->definition['empty field name'];
949 * Set up the query for this argument.
951 * The argument sent may be found at $this->argument.
953 public function query($group_by = FALSE) {
954 $this->ensureMyTable();
955 $this->query->addWhere(0, "$this->tableAlias.$this->realField", $this->argument);
959 * Get the title this argument will assign the view, given the argument.
961 * This usually needs to be overridden to provide a proper title.
963 public function title() {
964 return $this->argument;
968 * Called by the view object to get the title. This may be set by a
969 * validator so we don't necessarily call through to title().
971 public function getTitle() {
972 if (isset($this->validated_title)) {
973 return $this->validated_title;
976 return $this->title();
981 * Validate that this argument works. By default, all arguments are valid.
983 public function validateArgument($arg) {
984 // By using % in URLs, arguments could be validated twice; this eases
986 if (isset($this->argument_validated)) {
987 return $this->argument_validated;
990 if ($this->isException($arg)) {
991 return $this->argument_validated = TRUE;
994 $plugin = $this->getPlugin('argument_validator');
995 return $this->argument_validated = $plugin->validateArgument($arg);
999 * Called by the menu system to validate an argument.
1001 * This checks to see if this is a 'soft fail', which means that if the
1002 * argument fails to validate, but there is an action to take anyway,
1003 * then validation cannot actually fail.
1005 public function validateMenuArgument($arg) {
1006 $validate_info = $this->defaultActions($this->options['validate']['fail']);
1007 if (empty($validate_info['hard fail'])) {
1011 $rc = $this->validateArgument($arg);
1013 // If the validator has changed the validate fail condition to a
1014 // soft fail, deal with that:
1015 $validate_info = $this->defaultActions($this->options['validate']['fail']);
1016 if (empty($validate_info['hard fail'])) {
1024 * Set the input for this argument
1026 * @return TRUE if it successfully validates; FALSE if it does not.
1028 public function setArgument($arg) {
1029 $this->argument = $arg;
1030 return $this->validateArgument($arg);
1034 * Get the value of this argument.
1036 public function getValue() {
1037 // If we already processed this argument, we're done.
1038 if (isset($this->argument)) {
1039 return $this->argument;
1042 // Otherwise, we have to pretend to process ourselves to find the value.
1044 // Find the position of this argument within the view.
1046 foreach ($this->view->argument as $id => $argument) {
1047 if ($id == $this->options['id']) {
1053 $arg = isset($this->view->args[$position]) ? $this->view->args[$position] : NULL;
1054 $this->position = $position;
1056 // Clone ourselves so that we don't break things when we're really
1057 // processing the arguments.
1058 $argument = clone $this;
1059 if (!isset($arg) && $argument->hasDefaultArgument()) {
1060 $arg = $argument->getDefaultArgument();
1062 // remember that this argument was computed, not passed on the URL.
1063 $this->is_default = TRUE;
1065 // Set the argument, which will also validate that the argument can be set.
1066 if ($argument->setArgument($arg)) {
1067 $value = $argument->argument;
1074 * Get the display or row plugin, if it exists.
1076 public function getPlugin($type = 'argument_default', $name = NULL) {
1079 case 'argument_default':
1080 if (!isset($this->options['default_argument_type'])) {
1083 $plugin_name = $this->options['default_argument_type'];
1084 $options_name = 'default_argument_options';
1086 case 'argument_validator':
1087 if (!isset($this->options['validate']['type'])) {
1090 $plugin_name = $this->options['validate']['type'];
1091 $options_name = 'validate_options';
1094 if (!isset($this->options['summary']['format'])) {
1097 $plugin_name = $this->options['summary']['format'];
1098 $options_name = 'summary_options';
1102 $name = $plugin_name;
1105 // we only fetch the options if we're fetching the plugin actually
1107 if ($name == $plugin_name) {
1108 $options = isset($this->options[$options_name]) ? $this->options[$options_name] : [];
1111 $plugin = Views::pluginManager($type)->createInstance($name);
1113 $plugin->init($this->view, $this->displayHandler, $options);
1115 if ($type !== 'style') {
1116 // It's an argument_default/argument_validate plugin, so set the argument.
1117 $plugin->setArgument($this);
1124 * Return a description of how the argument would normally be sorted.
1126 * Subclasses should override this to specify what the default sort order of
1127 * their argument is (e.g. alphabetical, numeric, date).
1129 public function getSortName() {
1130 return $this->t('Default sort', [], ['context' => 'Sort order']);
1134 * Custom form radios process function.
1136 * Roll out a single radios element to a list of radios, using the options
1137 * array as index. While doing that, create a container element underneath
1138 * each option, which contains the settings related to that option.
1140 * @see \Drupal\Core\Render\Element\Radios::processRadios()
1142 public static function processContainerRadios($element) {
1143 if (count($element['#options']) > 0) {
1144 foreach ($element['#options'] as $key => $choice) {
1145 $element += [$key => []];
1146 // Generate the parents as the autogenerator does, so we will have a
1147 // unique id for each radio button.
1148 $parents_for_id = array_merge($element['#parents'], [$key]);
1152 '#title' => $choice,
1153 // The key is sanitized in drupal_attributes() during output from the
1155 '#return_value' => $key,
1156 '#default_value' => isset($element['#default_value']) ? $element['#default_value'] : NULL,
1157 '#attributes' => $element['#attributes'],
1158 '#parents' => $element['#parents'],
1159 '#id' => Html::getUniqueId('edit-' . implode('-', $parents_for_id)),
1160 '#ajax' => isset($element['#ajax']) ? $element['#ajax'] : NULL,
1162 $element[$key . '_options'] = [
1163 '#type' => 'container',
1164 '#attributes' => ['class' => ['views-admin-dependent']],
1172 * Moves argument options into their place.
1174 * When configuring the default argument behavior, almost each of the radio
1175 * buttons has its own fieldset shown below it when the radio button is
1176 * clicked. That fieldset is created through a custom form process callback.
1177 * Each element that has #argument_option defined and pointing to a default
1178 * behavior gets moved to the appropriate fieldset.
1179 * So if #argument_option is specified as 'default', the element is moved
1180 * to the 'default_options' fieldset.
1182 public static function preRenderMoveArgumentOptions($form) {
1183 foreach (Element::children($form) as $key) {
1184 $element = $form[$key];
1185 if (!empty($element['#argument_option'])) {
1186 $container_name = $element['#argument_option'] . '_options';
1187 if (isset($form['no_argument']['default_action'][$container_name])) {
1188 $form['no_argument']['default_action'][$container_name][$key] = $element;
1190 // Remove the original element this duplicates.
1199 * Sanitize validator options including derivatives with : for js.
1201 * Reason and alternative: https://www.drupal.org/node/2035345.
1204 * The identifier to be sanitized.
1207 * The sanitized identifier.
1209 * @see decodeValidatorId()
1211 public static function encodeValidatorId($id) {
1212 return str_replace(':', '---', $id);
1216 * Revert sanitized validator options.
1219 * The sanitized identifier to be reverted.
1222 * The original identifier.
1224 public static function decodeValidatorId($id) {
1225 return str_replace('---', ':', $id);
1229 * Splits an argument into value and operator properties on this instance.
1231 * @param bool $force_int
1232 * Enforce that values should be numeric.
1234 protected function unpackArgumentValue($force_int = FALSE) {
1235 $break = static::breakString($this->argument, $force_int);
1236 $this->value = $break->value;
1237 $this->operator = $break->operator;
1243 public function getCacheMaxAge() {
1244 $max_age = Cache::PERMANENT;
1246 // Asks all subplugins (argument defaults, argument validator and styles).
1247 if (($plugin = $this->getPlugin('argument_default')) && $plugin instanceof CacheableDependencyInterface) {
1248 $max_age = Cache::mergeMaxAges($max_age, $plugin->getCacheMaxAge());
1251 if (($plugin = $this->getPlugin('argument_validator')) && $plugin instanceof CacheableDependencyInterface) {
1252 $max_age = Cache::mergeMaxAges($max_age, $plugin->getCacheMaxAge());
1255 // Summaries use style plugins.
1256 if (($plugin = $this->getPlugin('style')) && $plugin instanceof CacheableDependencyInterface) {
1257 $max_age = Cache::mergeMaxAges($max_age, $plugin->getCacheMaxAge());
1266 public function getCacheContexts() {
1268 // By definition arguments depends on the URL.
1269 // @todo Once contexts are properly injected into block views we could pull
1270 // the information from there.
1271 $contexts[] = 'url';
1273 // Asks all subplugins (argument defaults, argument validator and styles).
1274 if (($plugin = $this->getPlugin('argument_default')) && $plugin instanceof CacheableDependencyInterface) {
1275 $contexts = Cache::mergeContexts($contexts, $plugin->getCacheContexts());
1278 if (($plugin = $this->getPlugin('argument_validator')) && $plugin instanceof CacheableDependencyInterface) {
1279 $contexts = Cache::mergeContexts($contexts, $plugin->getCacheContexts());
1282 if (($plugin = $this->getPlugin('style')) && $plugin instanceof CacheableDependencyInterface) {
1283 $contexts = Cache::mergeContexts($contexts, $plugin->getCacheContexts());
1292 public function getCacheTags() {
1295 // Asks all subplugins (argument defaults, argument validator and styles).
1296 if (($plugin = $this->getPlugin('argument_default')) && $plugin instanceof CacheableDependencyInterface) {
1297 $tags = Cache::mergeTags($tags, $plugin->getCacheTags());
1300 if (($plugin = $this->getPlugin('argument_validator')) && $plugin instanceof CacheableDependencyInterface) {
1301 $tags = Cache::mergeTags($tags, $plugin->getCacheTags());
1304 if (($plugin = $this->getPlugin('style')) && $plugin instanceof CacheableDependencyInterface) {
1305 $tags = Cache::mergeTags($tags, $plugin->getCacheTags());
1314 public function calculateDependencies() {
1316 if (($argument_default = $this->getPlugin('argument_default')) && $argument_default instanceof DependentPluginInterface) {
1317 $dependencies = NestedArray::mergeDeep($dependencies, $argument_default->calculateDependencies());
1319 if (($argument_validator = $this->getPlugin('argument_validator')) && $argument_validator instanceof DependentPluginInterface) {
1320 $dependencies = NestedArray::mergeDeep($dependencies, $argument_validator->calculateDependencies());
1322 if (($style = $this->getPlugin('style')) && $style instanceof DependentPluginInterface) {
1323 $dependencies = NestedArray::mergeDeep($dependencies, $style->calculateDependencies());
1326 return $dependencies;
1330 * Returns a context definition for this argument.
1332 * @return \Drupal\Core\Plugin\Context\ContextDefinitionInterface|null
1333 * A context definition that represents the argument or NULL if that is
1336 public function getContextDefinition() {
1337 return $this->getPlugin('argument_validator')->getContextDefinition();