Skip to main content
4 of 5
added 632 characters in body
Dominic Woodman
  • 2.2k
  • 4
  • 36
  • 60

Altering views exposed form - Adding select list separator causes error

Problem

I want to break the select list on my exposed form into chunks using select list dividers.

enter image description here

However this breaks my search.

Any attempt to search with values from that select list removes all results and attempts to navigate to the next page display the following error:

"An illegal choice has been detected. Please contact the site administrator"

What is going on?

Set-Up

I have an exposed view form. It has a select list field as one of the filter options.

There are a lot of options in the select list, so I've reordered it (away from alphabetical) to leave the five most popular at the top. This seems a little random so I then altered the form to add in un-selectable dividers. (see top picture)

How to add separator option in Form API 'select' element? (this is for creating forms, I put it into a form alter)

function mymodule_form_alter(&$form, $form_state, $form_id) {
    if ($form_id === 'views_exposed_form') {
      'Most Popular' => array (
          1 => 'China',
          2 => 'Thailand',
          3 => 'Japan',
          4 => 'Spain',
          5 => 'Saudi Arabia',
      ),
      
      'Countries' => array (
          6 => 'Afghanistan',
          7 => 'Aland Islands',
          8 => 'Albania',
          9 => 'Algeria',
          10 => 'American Samoa',
          ..
       );
    }

Is it somehow appending "Most Popular" or "Countries" onto the select list data value, invalidating the select list and throwing errors?

Allowed values in my select list looks like:

China|China
Thailand|Thailand
Japan|Japan
Saudi Arabia|Saudi Arabia
Spain|Spain
Afghanistan|Afghanistan
Aland Islands|Aland Islands
Albania|Albania

EDIT --

Alfred-Armstrong's answer has fixed the first problem. I now get search results. But the form alter is still breaking my ability to change pages.

This does however depend on what I search for. If I choose a country it works otherwise it breaks on a blank search.

Any more insight would be fantastic.

EDIT--2

Thanks again to Alfred I figured out what the other problem was. I was getting slightly different paths in my views with and without hook_alter_form.

The reason is I have two exposed forms for the same view. This means I have two views with the same path and both have exposed forms. One is on the home page the other on the search page.

The exposed forms have the same $form_id, so I when I alter one using hook_form_alter I alter the other. However I'd altered one exposed form in the views UI and not the other and because they have the same $form_id Drupal tries to pass data between them but can't.

Dominic Woodman
  • 2.2k
  • 4
  • 36
  • 60