Drupal 7 – Group form fields in div

Most common task in Drupal development is creating or altering forms. It could save a lot of CSS code if we group the form fields in div.

Here is an example.

/**
 * A new custom form.
 */
function <module>_form($form, &$form_state) {
  // Group A
  $form['group_a'] = array(
    '#type' => 'fieldset',
    '#prefix' => '<div class="group-a">',
  );
 
  $form['group_a']['textfield_1'] = array(
    '#type' => 'textfield',
    '#title' => t('Field 1'),
    '#maxlength' => '255',
    '#required' => TRUE,
  );
  
  $form['group_a']['textfield_2'] = array(
    '#type' => 'textfield',
    '#title' => t('Field 2'),
    '#maxlength' => '255',
    '#required' => TRUE,
  );
  
  // Group B
  $form['group_b'] = array(
    '#type' => 'fieldset',
    '#prefix' => '<div class="group-b">',
  );
 
  $form['group_b']['textfield_3'] = array(
    '#type' => 'textfield',
    '#title' => t('Field 3'),
    '#maxlength' => '255',
    '#required' => TRUE,
  );
  
  $form['group_b']['textfield_4'] = array(
    '#type' => 'textfield',
    '#title' => t('Field 4'),
    '#maxlength' => '255',
    '#required' => TRUE,
  );
}

 

Render the form and you will found the fields are grouped.

Done =)

Reference:
Form api: Combine two text fields into a div?

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.