Upgrade Your Drupal Skills

We trained 1,000+ Drupal Developers over the last decade.

See Advanced Courses NAH, I know Enough

Ways to shoot yourself in the foot: Submit "buttons"

I was writing custom forms that needed a validate handler and a submit handler. So, I followed the standard approach of

  function my_module_menu(){
    $items = array();
    $items['my/module/custom-form'] = array(
      'title' => 'I am a doofus',
      'page callback' => 'drupal_get_form',
      'page arguments' => array('my_module_custom_form'),
      'access callback' => TRUE,
      'type' => MENU_CALLBACK,
    );
    return $items;
  }

Note: My access callback is just to simplify this example.

  function my_module_custom_form($form, &$form_state) {
    $form = array();
    $form['stuff'] = array(
      '#type' => 'item',
      '#markup' => t('I am a doofus'),
    );
    $form['actions'] = array(
      '#type' => 'actions',
    );
    $form['actions']['submit'] = array(
      '#type' => 'button',
      '#value' => t('Just shoot me!'),
    );
    return $form;
  }

Note: This is using Drupal 7 conventions, but the issue is the same in Drupal 6. I have written the code with the error in it. Can you see the error?

  function my_module_custom_form_validate($form, &$form_state) {
    // some validation here
    drupal_set_message(__FUNCTION__);
  }

Note: I had placed the drupal_set_message to help me figure out what was being called and what wasn't. The _validate function was being called.

  function my_module_custom_form_submit($form, &$form_state) {
    drupal_set_message(__FUNCTION__);
    drupal_goto();
  }

Note: I was not seeing the drupal_set_message for the _submit nor was the drupal_goto happening.

As noted above, I was seeing the drupal_set_message for the _validate function when I clicked the submit "button." So why wasn't my _submit handler being called? It's not like this is the first time I have ever used the FAPI. Nor is it the first time I had written _validate and _submit handlers.

Have you figured out what my mistake was, yet?

My problem was that I had used '#type' => 'button' instead of '#type' => 'submit' for my submit "button!"

Author: 
Original Post: 

About Drupal Sun

Drupal Sun is an Evolving Web project. It allows you to:

  • Do full-text search on all the articles in Drupal Planet (thanks to Apache Solr)
  • Facet based on tags, author, or feed
  • Flip through articles quickly (with j/k or arrow keys) to find what you're interested in
  • View the entire article text inline, or in the context of the site where it was created

See the blog post at Evolving Web

Evolving Web