diff --git a/src/Plugin/views/filter/ViewsYearFilterDatetime.php b/src/Plugin/views/filter/ViewsYearFilterDatetime.php index f2a39d5be09bfafde625c339cd8bfff25af2d818..0fb1cfb7731e457d33525518d027f18989610248 100644 --- a/src/Plugin/views/filter/ViewsYearFilterDatetime.php +++ b/src/Plugin/views/filter/ViewsYearFilterDatetime.php @@ -20,6 +20,17 @@ class ViewsYearFilterDatetime extends DateTime { use DateViewsTrait; + /** + * {@inheritdoc} + */ + public function defineOptions() { + $options = parent::defineOptions(); + $options['use_select_list'] = ['default' => 0]; + $options['year_options'] = ['default' => '']; + return $options; + } + + /** * {@inheritdoc} */ @@ -29,6 +40,17 @@ class ViewsYearFilterDatetime extends DateTime { $form['value']['type']['#options']['date_year'] = $this->t('A date in CCYY format.'); // Add js to handle year filter state. $form['#attached']['library'][] = 'views_year_filter/year_filter'; + $form['use_select_list'] = [ + '#type' => 'checkbox', + '#title' => $this->t('Use select list'), + '#default_value' => $this->options['use_select_list'] ?? 0, + ]; + $form['year_options'] = [ + '#type' => 'textarea', + '#title' => $this->t('Year options'), + '#description' => $this->t('Enter the years you want to display in the select list. One year per line.'), + '#default_value' => $this->options['year_options'] ?? '', + ]; } } @@ -98,7 +120,12 @@ class ViewsYearFilterDatetime extends DateTime { */ public function buildExposedForm(&$form, FormStateInterface $form_state) { DateTime::buildExposedForm($form, $form_state); - $this->applyDatePopupToForm($form); + if ($this->options['use_select_list']) { + $this->applySelectList($form); + } + else { + $this->applyDatePopupToForm($form); + } } } diff --git a/src/Traits/DateViewsTrait.php b/src/Traits/DateViewsTrait.php index 2220230fb6f83d60e5adfc1ed111353b7baac526..88f766e722492d96c800751dd8b65d66a594cf6c 100644 --- a/src/Traits/DateViewsTrait.php +++ b/src/Traits/DateViewsTrait.php @@ -60,4 +60,34 @@ trait DateViewsTrait { } } + /** + * Apply the select list to the views filter form. + * + * @param array $form + * The form to apply it to. + */ + protected function applySelectList(array &$form) { + $identifier = $this->options['expose']['identifier']; + $element = &$form[$identifier]; + + // Define as a select element. + $element['#type'] = 'select'; + + // Handle year options: remove "\r" and explode by newline. + if (!empty($this->options['year_options'])) { + $options = array_map('trim', explode("\n", $this->options['year_options'])); + } + else { + $options = []; + } + + // Ensure array keys and values are the same. + $element['#options'] = array_combine($options, $options); + + // Set additional select properties. + $element['#empty_option'] = $this->t('- Any -'); + $element['#multiple'] = FALSE; + $element['#size'] = NULL; + } + }