Move a Field into an Existing Vertical Tab

In this blog post, we'll move a field into an existing fieldset in Drupal 7. There is a 'Path Override' field that we want to move into the 'path' fieldset, which is created by the Pathauto module. This change must be accomplished through code because it's not possible through the UI. The 'path' fieldset isn't available under a content type's 'Manage Fields' form:

Manage Fields screenshot

Drupal's Form API is a powerful tool for building forms, and the hook_form_alter and hook_form_FORM_ID_alter functions are tools for extending and modifying existing forms. In this example, we're using the hook_form_FORM_ID_alter function since the alter applies to the node form only. Before employing this function, the form appears as below:

Node Edit Form (before) screenshot

Below is the implementation of the hook_form_FORM_ID_alter. The 'Path Override' field exists on several content types, so we check if the field exists on a given content type before proceeding. Then we define the field inside the 'path' fieldset and unset the original field definition.

/*
* Implements hook_form_FORM_ID_alter.
*
* Move the 'field_path_override' field to the 'path' fieldset.
*/

function MYMODULE_form_node_form_alter(&$form, &$form_state, $form_id) {
  // Check if field exists on node form.
  if(isset($form['field_path_override'])) {
    // Define field in 'path' fieldset and unset original definition.
    $form['path']['field_path_override'] = $form['field_path_override'];
    unset($form['field_path_override']);
  }
}

The field has been moved using the hook_form_FORM_ID_alter function and now appears as below:

Node Edit Form (after) screenshot

The form alter gets us halfway there, but the field won't save in its present state. It's necessary to use the hook_node_update function to move the field back to its original location before saving:

/*
* Implements hook_node_update.
*
* Before saving the node, move the 'field_path_override' field back
* to its original location. Otherwise the field won't save.
*/

function MYMODULE_node_update($node) {
  // Check if field exists on node form.
  if(isset($node->path['field_path_override']['und'][0]['value'])) {
    // Redefine field in original definition and unset in 'path' fieldset.
    $node->field_path_override['und'][0]['value'] = $node->path['field_path_override']['und'][0]['value'];
    unset($node->path['field_path_override']);
}

Using the hook_form_FORM_ID_alter function and the hook_node_update function, we have moved a field into an existing fieldset.

 

Add new comment