6

The System module defines the container form element, but that form element is not documented in the Form API Reference.

When should that form element be used?

2 Answers 2

8

It looks like it can be used when you want to wrap a part of the form in a div, for example to be able to add some classes to it.

Some examples from core are the following:

  • field_default_form()

    // 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'],
    );
    
  • node_filter_form()

    $form['filters']['status'] = array(
      '#type' => 'container',
      '#attributes' => array('class' => array('clearfix')),
      '#prefix' => ($i ? '<div class="additional-filters">' . t('and where') . '</div>' : ''),
    );
    $form['filters']['status']['filters'] = array(
      '#type' => 'container',
      '#attributes' => array('class' => array('filters')),
    );
    
  • search_form()

    $form['basic'] = array(
      '#type' => 'container',
      '#attributes' => array('class' => array('container-inline')),
    );
    

Forms in Drupal 6 often used #prefix and #suffix on the first/last element to do this; this is a lot better because it is easier to add additional items or move them around.

I could use this in a few places in my own contributed modules, actually. ;)

4
  • container type also implies a nesting level in form_state's input / values.
    – jonhattan
    Commented Sep 15, 2013 at 9:54
  • 2
    No, it does not. Only when explicitly specified as #tree => TRUE, the default is FALSE.
    – Berdir
    Commented Sep 15, 2013 at 13:19
  • Ok, sorry. By casuality I was just adding a container in a field widget form and observed the nesting in $form_state. After your comment, I realized $element['tree'] comes as true. Thanks :)
    – jonhattan
    Commented Sep 15, 2013 at 13:31
  • Ah, yes, field widgets are always within a language and delta key, within that, they might be repeated, so #tree => TRUE is forced on them, yes.
    – Berdir
    Commented Sep 15, 2013 at 19:01
0

In D6, there were often times when you would need to add a <div> around a FAPI element (for example with #ahah / #ajax), so container is a more consistent solution in regards to the Forms API to this common pattern than adding a wrapper div using #prefix/#suffix.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.