How to get In-Field Labels in Drupal 7

Compact forms are always good to have and in-field labels is one of the feature that makes the form more compact and sleak. Conventionally the labels are set as "above" or "in-line" with the fields where as in-field labels are set with in the Label's respective fields. Technically form item or element fields are overlaid with their repective labels.

There are several way of implementing this kind of feature, This can be implemented without installing any third party module or jquery plugin by jsut using drupal form alter hook and this feature can also be implemented by installing one of the two contrib modules available on drupal.org. I am going to show how this can be done with just altering a form but just take note of it this can only work on browsers that support HTML5, in HTML5 there is a new property called "placeholder" which actually does this trick you can find more details of it here.

<form action="example.php">
  <input type="text" name="fname" placeholder="First name"><br>
  <input type="text" name="lname" placeholder="Last name"><br>
  <input type="submit" value="Submit">
</form> 

Implementing this in plaing HTML is very simple as stated above but to add this functionality in drupal form fields requires a little Drupal developer experience anyway below is the code to implement this attribute using form alter hook.

function example_form_alter(&$form, &$form_state, $from_id) {

  if ($form_id == 'contact_site_form') {
   
    $form['name']['#attributes'] = array('placeholder' => $form['name']['#title']);
    unset($form['name']['#title']);

    $form['mail']['#attributes'] = array('placeholder' => $form['mail']['#title']);
    unset($form['mail']['#title']);

    $form['subject']['#attributes'] = array('placeholder' => $form['subject']['#title']);
    unset($form['subject']['#title']);

    $form['message']['#attributes'] = array('placeholder' => $form['message']['#title']);
    unset($form['message']['#title']);

  }

}

Other two options that implement this feature are through Drupal contrib modules called "In-Field Labels" and "Compact Forms" both integrates different jquery plugins.

Comments

Unsetting the element title

Unsetting the element title is not particularly accessible (ie., for screen readers, for example). Instead, use:

$form['name']['#title_display'] = 'invisible';

This will keep the label, but prevent it from being displayed visually.

typo

Thanks for this man. great tutorial. Just one small remark.

function example_form_alter(&$form, &$form_state, $from_id) {

should be: function example_form_alter(&$form, &$form_state, $form_id) {

you have a typo in $form_id; Keep coding and sharing mate!