Aug 27, 2012

Posted by in Drupal | 0 comments

How to style drupal form to have the form fields side by side

How to style drupal form to have the form fields side by side

We often come is a requirement where we were asked to style the drupal form, newbies finds it difficult to do with Drupal Form, and try not to use the drupal form handler, form API and directly go with HTML code.

It is easy, and everything is possible with drupal if we know it well. Here I will demonstrate how we can place two form fields side by side,

lets consider an example, we have two fields, “First Name” and “Last Name”, and we would like to place them side by side using css.

Here is the PHP code which will go in .module or .inc file inside your module. You can name the function anything and call them in your page arguments for the given menu path.

PHP CODE

/**
 * @this form will have two fields firstname, lastname and will be displayed side by side
 */

function my_combo_form($form, &$form_state) {
 
  //This is the way to load a css file for a form, we can also load js in the similar manner.
  $form['#attached']['css'][drupal_get_path('module', 'modulename') . '/form.css'] = array();
 
  $form['description'] = array(
    '#type' => 'item',
    '#title' => t('A form with validation'),
  );

  $form['name'] = array(
    '#type' => 'fieldset',
    '#title' => t('Name'),
    // Make the fieldset collapsible.
    '#collapsible' => TRUE, // Added
    '#collapsed' => FALSE,  // Added
  );
 
  $form['name'] = array(
    '#prefix' => '<div class="two-col">',
    '#suffix' => '</div>'
    );     
   
   
  // Make these fields required.
  $form['name']['first'] = array(
    '#type' => 'textfield',
    '#title' => t('First name'),
    '#size' => 40,
    '#prefix' => '<div class="col1">',
    '#suffix' => '</div>',
    '#required' => TRUE, // Added
  );
  $form['name']['last'] = array(
    '#type' => 'textfield',
    '#title' => t('Last name'),
    '#size' => 40,
    '#prefix' => '<div class="col1">',
    '#suffix' => '</div>',
    '#required' => TRUE, // Added
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Submit',
  );
  return $form;
}

Here goes the CSS, create a file called form.css and place it inside your module

Feel free to place with the css and you can also have more fields in the form and adjust them the way you want.

.two-col {
    overflow: hidden;/* Makes this div contain its floats */
    width:100%;
}

.two-col .col1,
.two-col .col2 {
    width 49%;
}

.two-col .col1 {
    float: left;
    margin:0 15px 0 0;
}

.two-col .col2 {
    float: right;
}

.two-col label {
    display: block;
}

Leave a Reply