2

I have a Views with an exposed filter block and put the block on the front page.

I use the following code to add a custom submit handler.

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'views_exposed_form' )
  {
    array_unshift($form['#submit'], 'manage_custom_filters');
  }
}

function manage_custom_filters($form, &$form_state) {
 dpm($form['#id']);  // output views name
}

Here is the question, whenever i load the front page, the manage_custom_filters get called, i suppose it will be called only when i submit the exposed filter form?

I did the same thing for node form submit, it does not behave like the views exposed filter form. manage_custom_filters only get called when i submit the form.

Is this the correct behavior of views exposed filter form?

How do i differentiate the manage_custom_filters is get called by 'on load' or submit action?

2 Answers 2

3

The views exposed form will be submitted every time you view it. If you check the render_exposed_form() you can see they are setting the $form_state['always_process'] => TRUE, this means that the form will be submitted always while processing it. And this is understanable because submitting the exposed form and passing the argument in $GET are the same in view.

1

As stated above, the form is submitted as soon as you load a page. You have a couple of workarounds here:

  1. If you are using Ajax, you could add a custom JavaScript function only fired on submit (so when you load the page it won't occur). Something like this:

    Drupal.behaviors.mymoduleAjaxView = {
      attach: function(context, settings) {
        this.form.submit = customFunction();
        function customFunction() {
            alert('Fired when form is submitted'); 
        }
    }};
    
  2. If you don't wish / have to use JavaScript, you could check for a field in your form that, on page load has no value (is empty) but when submitted by a human has a value. E.g.

    function manage_custom_filters($form, &$form_state) {
        if(!empty($form_state['values']['field_name_here']) {
          // Form was human submitted.
        }
    }
    

Compare $form_state when the page loads and when you submit the form, to spot this. I know that probably this is not the ideal way, but it has worked for me.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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