Often I find myself needing to add a field or fields to a form, where I'd like to put the field somewhere in the middle of the rendering of the form. Typically, the form doesn't have #weight properties on the form elements it defines, so there isn't an easy way to slot the field your adding into the middle of the rendering since the form API will just render the elements in the order they appear. Is there an easy way to do this?
I've done it a couple different ways. Once way was that I used PHP array_splice to get my field in the middle of the array somewhere. Recently I discovered the element_children() function, so I've been doing it like this:
$elements = element_children($form);
$weight = 0;
foreach($elements as $element) {
$form[$element]['#weight'] = ($weight += 1);
}
That adds weights to existing elements, then I just weight my added fields accordingly. Any suggestions for a better way? Have you run into this issue and how have you dealt with it?
Thanks,
Matt
Comments
Theme the form manually
The best way to get absolute control over the form layout, including field order, is to define a custom .tpl file for it.
In the .tpl, when you print out parts of the form they are always rendered where you want them to appear. The "weight" property only applies if you print parts of the form at a higher level than individual fields.
Here's a simple tutorial:
http://www.akchauhan.com/theme-drupal-form/
---------------------------------
Steven Wright
Slalom
Ahh, good point. Thanks I'll
Ahh, good point. Thanks I'll consider using that next time.
try not to create .tpl
Best practise will be not to create .tpl for every form you create. hook_form_alter should give you most of it!