0

I don't know how to make my custom exposed filter work with AJAX:

I have a view that has a contextual filter that filters for Node creation date by year. This filter gets filled via a query parameter like '?year=2021'.

Via the code below I have created a custom exposed filter form element to allow the user to select a year.

This works great unless AJAX is activated. How can I make this work with AJAX enabled?

/**
 * Implements hook_form_FORM_ID_alter().
 */
function mymodule_form_views_exposed_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  if (isset($form['#id']) && $form['#id'] == 'views-exposed-form-news-page-1') {

    $years = ['all' => t('- All -')];
    for ($i = date('Y'); $i >= '1997'; $i--) {
      $years[$i] = $i;
    }

    $form['year'] = [
      '#title' => new TranslatableMarkup('Year'),
      '#type' => 'select',
      '#options' => $years,
      '#size' => NULL,
      '#default_value' => 'all',
    ];

  }
}
0
0

Not sure if this will be helpful in your circumstance, but I was following this tutorial (https://www.flocondetoile.fr/blog/filter-content-year-views-drupal-8) and ran into the same issue that others did - it doesn't work with AJAX.

The solution was to avoid creating a contextual filter, and instead create a regular exposed filter based on (in my case) the node date field via the views admin UI. The same alter hook was used to edit the select values on that filter instead of the contextual filter.

We did have to edit the alter hook code from the tutorial. This:

$options['all'] = new TranslatableMarkup('- All -');

Becomes:

$options[''] = new TranslatableMarkup('- All -');

and this:

  $form['y'] = [ 
    '#title' => new TranslatableMarkup('By year'),
    '#type' => 'select',
    '#options' => $options,
    '#size' => NULL,
    '#default_value' => 'all',
  ];
  $form['#submit'][] = '_plb_di_year_filter_submit_year';

becomes this:

  $default_year = $form_state->getUserInput()['field_year_value'];
  $form['field_year_value'] = [ 
    '#title' => new TranslatableMarkup('By year'),
    '#type' => 'select',
    '#options' => $options,
    '#size' => NULL,
    '#default_value' => '',
    '#value' => $default_year,
  ];

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.