1

I have a search form in the header that is simply adding a search term to the current URL. If you are on example.com/list-page and submit a search, it just sends you to example.com/list-page?search=my-term-here.

When I submit the form, I've noticed that the full page has to be rendered before the form's submit handler is called. Since the search modifies the current list page's results, it seems redundant when submitting a search for "my-term-here" on example.com/list-page to have to render example.com/list-page again before the submit handler is called and then render the version I actually want: example.com/list-page?search=my-term-here.

I've hacked around this by doing this in my form:

// Set to the current path so we can redirect back there after submit.
$form['submission_path'] = array(
  '#type' => 'hidden',
  '#default_value' => current_path(),
  '#weight' => -100,
);

$form['#action'] = url('search-callback');

The search-callback does nothing:

function mymodule_search_callback() {
  return '';
}

The submit handler then does a redirect like this to get back to example.com/list-page?search=my-term-here.

// Redirect back to the page that submitted the search.
$form_state['redirect'] = array(
  $form_state['values']['submission_path'],
  array(
    'query' => array(
      'search' => urlencode($search-term),
    ),
  ),
);

Is there a better way to handle this? Can the form's submit handler be called before rendering the page the form is posting to?

0

You need to add a submit callback that will handle the redirect:

 $form['#submit'][] = 'mymodule_search_callback'

And in that callback:

function mymodule_search_callback() {
   $form_state['redirect'] = current_path() . and your urlencoded serch term;
}

Messing with $form['#action'] is not the right way to do it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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