Hi,

I need to get a simple example of how to wrap form elements in a container so I can customize the styling of a form.

I found the documentation for the form type of 'container' but the example seems kind of cryptic.

What I basically want to know is if I use '#type' => 'container',
how do I specify '#attributes' => array()
to say wrap a set of div ids or div classes with this container.
Does anyone have a simple example of doing something like that..I cant seem to find such examples (?)

Heres what the forms API says:

container

Description: Returns HTML to wrap child elements in a container. Surrounds child elements with a

and adds attributes such as classes or an HTML id.
Properties: #access, #after_build, #attributes #children, #id, #parents, #post_render, #pre_render, #prefix, #process, #states, #suffix, #theme, #theme_wrappers, #tree, #type, #weight

Usage example (field.form.inc):
<?php
  if ($elements) {
    // Also aid in theming of field widgets by rendering a classified
    // container.
    $addition[$field_name] = array(
      '#type' => 'container',
      '#attributes' => array(
        'class' => array(
          'field-type-' . drupal_html_class($field['type']),
          'field-name-' . drupal_html_class($field_name),
          'field-widget-' . drupal_html_class($instance['widget']['type']),
        ),
      ),
      '#weight' => $instance['widget']['weight'],
    );
  }
?>

Comments

Levure’s picture

Up.

The documentation is quite unclear about that form type.

A usefull example should contain at least to "normal" fields, and one container.
It would be easier to understand how to use '#type' => 'container' !

cfbauer’s picture

Me too!

edit: found an example of what I'm looking for!

https://www.elevatedthird.com/article/building-field-groups-drupal-7

Code pasted here to avoid link rot.

$form['contact'] = array(
  '#type' => container,
  '#weight' => 5,
  ‘#attributes’ => array(
    ‘class’ => array(
      ‘contact-info’,
    ),
  ),
);

Any elements you nest under the ‘contact’ key will be rendered in that container.

$form[‘contact’][‘first_name’] = array(
  ‘#type’ => ‘textfield’,
  ‘#title’ => t(‘First Name’),
  ‘#default_value’ => ‘’,
  ‘#size’ => 60,
  ‘#maxlength’ => 128,
  ‘#required’ => TRUE
);
sano’s picture

The above advice did not work for me with Drupal 7.65. I had to nest the added element under [LANGUAGE_NONE][0] like this:

$form['field_time'][LANGUAGE_NONE][0]['first_name'] = array(
    '#type' => 'textfield',
    '#title' => t('First Name'),
    '#default_value' => '',
    '#size' => 60,
    '#maxlength' => 128,
    '#required' => TRUE );