Using form builder for "normal" forms
Here at Electric Word plc, we recently needed an email capture form which we wanted to build using the Drupal Forms API. An example of the pre-drupal version can be seen on our pponline.co.uk email collection page. The problem is that the Drupal Forms API prefixes fields into an edit array, for example:
<input type="text" name="edit[foo]" value="bar" />
What happens if you don't want the results to be in the edit array? What do you do if the form you're writing needs to be sent to a 3rd party script which has predefined names for the data that needs to be sent to them?
The prefixing or 'edit' is something that's hard-coded into the core Forms API (it happens quite early on in the form_builder function). So how do we change drupal form names into "normal" form names? Enter Regualr Expressions and preg_replace.
Instead of doing...
<?php
function example_admin_section() {
$form['foo'] = array(
'#type' => 'textfield',
'#default_value' => 'bar',
);
return drupal_get_form('example_admin_section', $form);
}
?>You'd need to first generate the content into a variable and then do a regular expression on that to find and replace content... Like this..
<?php
function example_admin_section() {
$form['foo'] = array(
'#type' => 'textfield',
'#default_value' => 'bar',
);
$content = drupal_get_form('example_admin_section', $form);
$content = preg_replace('|name="edit\[(.+?)\]"|i', 'name="$1"', $content);
return $content;
}
?>That regular expression basically says find anything that looks like name="edit[something]" and replace it with name="something".
The only issue with this is that it will only work properly with non-nested forms... If your form has an element named edit[foo][bar] then the regex wont match and the element will be ignored and left untouched. The regex could be tweaked to allow for this - however the naming could be difficult and it would be much easier to just code your form to use a non-tree structure (ie flat).
I hope this helps someone!
