formapi

How to add one or more custom submit handlers to a Drupal form

02 MAR 2008 / joeri poesen

The information in this post relates to Drupal 5.x.

In Drupal 5 it's possible, and easy, to play with a form's submit handlers: you can replace an existing handler with your own and you can even add multple handlers if you want.

In human terms, this means that you can change the function that is called when a certain form is submitted and has passed the validation handler (the function responsible for validating the form input).

Why would you want to do this?

keywords:

how to display a form in a block

02 OCT 2007 / joeri poesen

For a recent project, I created a simple content type and I needed to be able to display a node entry form in a block. It took me ages to get it working, and I only succeeded thanks to the suberb help of dmtrig0 and his Drupal Dojo lesson.

First attempt
My first guess was to work with _drupal_get_form($form_id)_. The first hurdle here was to figure out where to find the drupal form id for any given form. In my case, I just had to browse to /node/add/my-content-type, view the source and search for _form_id_ – it’s a hidden field buried deep down in html.

Now, printing _drupal_get_form(‘my_form_id’)_ leads to a form that’s only partly displayed and is totally useless. I still haven’t figured out what happened there, but I’m guessing the generic part of any node entry form is displayed there – but without the node specific fields.

Second through seventeenth attempt
Lots of head scratching, coffee drinking, swearing, googling.

Final solution
Make a block and throw in this php snippet:

<?php print node_add('your-content-type'); ?>

This one line of code is all it takes to render the form in all its glory. However, it will also change your page’s title to “Add your-content-type “. To avoid this, use:

<?php 
  $ot = drupal_get_title(); 
  print node_add('your-content-type'); 
  drupal_set_title($ot); 
?>

I’ve been discussing this with a few colleagues and I still find these function names very confusing. Intuitively _drupal_get_form()_ and _drupal_render_form()_ should do exactly that: print a chunk of html, while I would assume that _node_add()_ would be used to add nodes manually.

There’s probably a very good explanation for all this, and I’ll no doubt return to this issue once I’m more familiar with the inner workings of Drupal.

keywords:
Syndicate content