Skip to main content
knackforge blog knowledge base

Drupal Form API - Overriding required field asterisk

Forms are the essential components of Dynamic websites. At KnackForge we firmly believe and make the best use of Drupal CMF. API forms the backbone of Drupal's success and Form API is the most important among them. When Form API used together with the blend of themeing layer, it gives a fine control to get the desired output.

Forms in Drupal are created using PHP array.

  1. <?php
  2.   $form['foo'] = array(
  3.     '#type' => 'textfield',
  4.     '#title' => t('bar'),
  5.     '#default_value' => t('foo'),
  6.     '#size' => 60,
  7.     '#maxlength' => 64,
  8.     '#description' => t('baz'),
  9.     '#required' => TRUE,
  10.   );
  11.  ?>

 

Needless to say further about the intention of the code, the above snippet can be considered as a example. The key and the value of array represents the form attributes and values respectively. In plain English the above code would add a textfield with title: bar, description: baz, default value: foo, etc. with size of the field being 60 and maximum length of input as 64. The '#required' => TRUE says that the field must take some non empty input.

 

The ideal example of Drupal Form API output would be user login form,

[[{"type":"media","view_mode":"media_original","fid":"107","attributes":{"alt":"","class":"media-image","typeof":"foaf:Image"}}]]

The field with symbol * beside it represents mandatory field. Recently I had to override the required field asterisk to a readable string '(required)'. After spending a few hours, came with a reliable way to do it.

In your active theme's template.php file, add a hook_form_required_marker(). The * symbol is added using the theme function which can be overridden, the below snippet is an implementation of that.

  1. <?php
  2. function THEME_form_required_marker($variables) {
  3.   // This is also used in the installer, pre-database setup.
  4.   $t = get_t();
  5.   $attributes = array(
  6.     'class' => 'form-required',
  7.     'title' => $t('This field is required.'),
  8.   );
  9.   return '<span' . drupal_attributes($attributes) . '>(required)</span>';
  10. }
  11. ?>
The 9th line is the crucial one, which adds the "(required)" instead of the asterisk symbol.
Hope this little trick might help to learn the crux of Form API.