Drupal Quick Tip: Positioning Form API Elements When Using Fieldgroups
The other day I ran across an interesting problem while working with the Drupal 7 Form API and wanted to share my solution.
I was writing a module to add a custom field to a content type. In this content type, all the fields were organized into a series of vertical tabs using the Fieldgroup module.
I wanted to place my field underneath the main fieldgroup, but above the form submit buttons. Simple enough, right? Apparently not.
When I started altering the #weight of the form element, I discovered that whether I set a weight of 0 or 50, the field always stayed at the top of the form. Only when I set a weight of 99+ did the form element move - but to the bottom of the form, underneath the submit buttons. Not very helpful!
By placing my form element inside the actions array, I was able to control the position of my Form API element relative to the submit buttons, placing them under the main group but above the form controls.
$form['actions']['your_field_name'] = array( // '#type' => 'foo', // '#title' => t('...'), // ... '#weight' => 0, );
Why It Works
Think of the Drupal Form API like nested HTML markup. If you want to position a new element relative to another one, you need to find where that element is located in the tree and make sure they're siblings. In this case, I made my field a sibling of the form controls by placing it in the actions array. However, this should be applicable to any group you want to place your field in.
Keep in mind you may have to dig through a couple layers of arrays before you eventually find the correct spot to place your new form element. Don't give up!