blog-banner

Drupal Form API - Overriding Required Field Asterisk

    Drupal Form API

     

    Forms are the essential components of Dynamic websites. At KnackForge we firmly believe in 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 is used together with the blend of theming layer, it gives a fine control to get the desired output.

    Forms in Drupal are created using a PHP array.

    1.  

     

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