Tell me more ×
Drupal Answers is a question and answer site for Drupal developers and administrators. It's 100% free, no registration required.

I'm currently getting used to Drupal 7 after previously working solely on D6. I'm having some trouble using hook_form_alter with views 3 and Drupal 7.

I'm unable to add an if statement to uniquely identify a view, whatever I put in, the if statement is never found to be true. However, I can easily use the form_id using the following so I'm not sure where I am going wrong!

if ($form_id == 'views_exposed_form') {
}

I'd be really grateful for any pointers.

share|improve this question

2 Answers

What i would do is take it a step back and see if you're even registering this hook. Often $form_id's change.

Debugging process:

  • Turn on devel
  • Insert dsm($form_id) inside your hook as you used to with D6
  • Clear your cache

Example code (inside mymodule.module or template.php file) from drupal.org:

<?php
/**
 * Implementation of hook_form_alter()
 */
function mymodule_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'form_views_exposed_form') {
    drupal_set_message("Form ID is : " . $form_id);
  }
}
?>

You'll see a bunch of form id's printed out then select your views exposed form hook and work from there.

Also, with drupal 7 you're able to target specific forms by ID directly.

Example:

<?php
/**
 * Implementation of hook_form_alter()
 */
function mymodule_form_views_exposed_form_alter(&$form, $form_state, $form_id) {
  drupal_set_message("Form ID is : " . $form_id);
}
?>

Finally, if that doesn't work i would recommend reviewing this issue queue: How to alter filter in exposed filters form trough form_alter hook

share|improve this answer

You can get access to the view object within hook_form_alter by accessing $form_state['view']. That allows you to identify a specific view:

function mymodule_form_alter(&$form, &$form_state, $form_id) {
    if ($form_id == 'views_exposed_form') {
        $view = $form_state['view'];
        if ($view->name == 'my_view_machine_name' && $view->current_display == 'display_name') {
            // alter your exposed form here
        }
    }
}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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