how to display a form in a block

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.