April 23, 2014

April 23, 2014
In this article, we are going to discuss about How to override the Exposed views filters with hook_form_alter function. Override the 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.

Hope this helps.


Post a Comment