Overriding Exposed Views Filters with hook_form_alter

Customizing your exposed filters is easy and a good way of customizing what users can select. A common example I've found is when you want users to choose from a select list but views only provides you with a textfield.  Using hook_form_alter, you can easily change the #type attirbute of the exposed filter form however, one simple mistake can result in the HUGELY annoying, "Illegal choice detected. Please contact your administrator".

As I mentioned, if you are looking to override exposed filters, you can do so with:

hook_form_alter ($form, &$form_state, $form_id) {

//add some kind of if statment here to check the form_id otherwise you'll affect all your forms

if ($form['#id'] == 'views-exposed-form-[VIEW-NAME]-[WHICHEVER VIEW NUMBER]') {
        $form['EXPOSED FILTER FIELD'] = array(
            '#type' => 'select',
            '#default_value' => '',
            '#options' => array(
                "" => t("- Select -"), //be sure to add the t() function around the first value
                "1"  => "VALUE 1",
                "2"=> "VALUE 2",
            ),
        );

}

**additionally, you can use hook_form_FORM_ID_alter to specify the form you are altering, avoiding the initial if statment all together.

The common illegal choice detected error comes up if you don't add t() around your first option. This is because this value would be passed through views using the t() function.  As a result, Drupal checks all forms during rendering to make sure nothing modified without permission. If you don't use the t() function, Drupal will see your changes as unauthorized and potential hacking -- This is a good thing.

So, the moral of the story is, make sure you are passing back values in the way that Drupal is expecting them when using hook_form_alter. Thanks Manu at http://drupal.org/node/463990#comment-4258378.

Hope this helps,
pete

Comments

I've been ripping my hair out over this nasty error. Turns out it's that t() function.