Drupal Tip #6 – Missing Groups When Altering Node Forms

In customizing your node forms, hook_form_alter is a great way to restructure your forms before it is displayed. If you are using views2 and use groupings to organize your forms, its necessary to use hook_form_alter to bring certain form elements into groups because you’re not allowed to do so from the UI. Fields such as the title and body cannot be dragged under any groups in the manage fields page of the content type.

When a field is not in any groups, it will appear as a direct child key of the form, e.g.

$form['field_example'].

When it is under a group, it will be nested in a key with the group’s name, e.g.

$form['group_example']['field_example'].

To move the field, simply assign its value into the appropriate group key, and unset the original key:

$form['group_example']['field_example'] = $form['field_example'];
unset($form['field_example']);

One common problem though, is that the group keys are not appearing in the $form array passed into your_module_form_alter. You double checked the content type in the admin page (/admin/content/node-type/[your-node-type]/fields) but they are still not showing. Do not panic, they simply have not been created yet. The reason for this is that the CCK module’s hooks responsible for creating these keys are fired later than your form_alter hook, and this is a simple problem to solve.

Making sure your hooks are called after CCK

Drupal determines which modules are called when using their weight in the system table. To reorder your module to after CCK, you can manually set it’s weight:

db_query("UPDATE {system} SET weight = 50 WHERE name = 'your_node_type'");

One common place to do this is in the your_module.install file, so that its set only once during installation. My choice of weight (50) is purely arbitrary, you may need to inspect your own system table to determine the most appropriate weight.

Now your group keys should be appearing in the $form array.

Leave a Reply

Your email address will not be published. Required fields are marked *