6

Using the form api is it possible to combine two text fields onto the same row?

E.g. form

<?php
function foo_form($form, $form_state) {
  $form = array();

  $form['range'] = array(
    '#type' => 'fieldset',
 );

  $form['range']['min'] = array(
     '#type' => 'textfield',
     '#title' => 'Address'
  ),
  $form['range']['address2'] = array(
     '#type' => 'textfield',
     '#title' => 'Address'
  )
  // ...
  return $form;
}

Desired output

<div>
  <h2>Range</h2>
  <input name="min" /> to <input name="max" />
</div>

4 Answers 4

11
<?php
function foo_form($form, $form_state) {
  $form = array();

  $form['range'] = array(
    '#type' => 'fieldset',
    '#prefix' => '<div class="myclass">',
 );

  $form['range']['min'] = array(
     '#type' => 'textfield',
     '#title' => 'Address'
  ),
  $form['range']['address2'] = array(
     '#type' => 'textfield',
     '#title' => 'Address'
     '#suffix' => '</div>',
  )
  // Remaining code
  return $form;
}
2
  • 2
    Thanks for the answer, but why didn't you add the suffix to the fieldset, instead of the last control in the group?
    – TMorgan
    Commented Aug 6, 2015 at 19:42
  • Note: If you put an opening <div> prefix on the wrapper and suffix on another element you will likely break ajax.
    – Duncanmoo
    Commented Mar 2, 2018 at 12:33
1

Its better use css to align two inline . Find out the wrapper div id, then apply this css

WRAPPER_ID {
  display :inline; // or try inline-block
}
0

This Drupal Stackexchange answer regarding Horizontal Form Elements answered earlier may be beneficial to you. I typically do the same thing with a wrapper div, but did not know about the container-inline class.

-1

There's a module that may be of assistance: Field Collection (7.x)

1
  • 2
    This question is specifically about the FAPI. Also, Field Collection (which is awesome btw) would solely for this would add a whole layer of complexity that isn't required. If you're building forms with the UI then Field Group would be a much better option.
    – Chapabu
    Commented Sep 27, 2012 at 13:37

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.