subforms: easy form reusing

Submitted by fago on Tue, 03/06/2007 - 23:56
drupal 5.x allows one to programmatically submit forms. So wouldn't it be neat to reuse whole forms? This is what the subform form-element allows you to do. So you can build forms that reuse existing forms while you extend them with further form items. Note that form reusing means not only reusing the visual representation, but also the validation and submit logic. First I've implemented this for pageroute, as pageroute reuses a lot of existing forms. As it's also useful for other modules, I've created an own project for it. I had already a prototype for 4.7, but it had some drawbacks. The actual code for 5.x is much better, it handles validation and submitting of subforms correctly, so the subform will only be submitted if the main-form has also no validation errors. How to use it? All one needs to do, is to create a form element of the #type 'subform'. It needs the form_id as parameter (#id) and optionally it takes also #arguments, which will be passed to the form function. Then unfortunately one has to define an additional submit handler (subform_element_submit), which cares for submitting the subforms (if the validation was fine). Of course this handler could also be called from an already existing submit handler. ok, let's show a short usage example.
<?php function subform_test_form($node, $page) {
//this will present a full working node edit form
$form['node'] = array(
'#type' =?>
    '#id' =&gt; $node-&gt;type .'_node_form',
    '#arguments' =&gt; array($node),
  //this sets the subform submit handler
  $form['#submit']['subform_element_submit'] = array();

  return $form;
So this will create a fully working node form for you! Note: Now there is an own subform element project and a documentation page in the handbook, which contains another example.

mamsk (not verified)

Tue, 06/05/2007 - 19:20

Hi there! :) I use youre module for drupal named subform_element. And I would like to know if there is a way for delete those ugly buttons "submitt" under each subform?... Anyway, thanks for this usefull module you made! :) it rocks my life! >_O -- "you don't become a failure until you're satisfied with being one"