blog-banner

Add Placeholders to Captcha Input Field

  • CAPTCHA
  • Drupal 7
  • HTML5
  • PLACEHOLDER
  • Templates

HTML 5 has been encompassed with many novel attributes, one of which is the Placeholders. The Placeholder attribute displays text in the input field till it is focused and then hides the text on click. These Placeholders play a momentous role in offering visual information about the field. A general place where I prefer to add Placeholders is template.php in your theme.

  1. function theme_name_form_id_alter(&$form, &$form_state, $form_id) {
  2.  $form['submitted']['your_field']['#attributes']['placeholder'] = t('Text to appear as placeholder');
  3. }

Replace theme_name with your theme's name and form_id with the unique identifier associated with your form. The above piece of code will add Placeholders to the field your_field (replace this with your field's name) with the given text.

But one requirement which has made me think a lot in the recent past was to add Placeholders to captcha's input field. I did follow the above-mentioned approach to add the Placeholders, but I failed instantly on each attempt. On debugging I found that the captcha's Placeholder was overridden by the captcha module's functions. Instead of hacking the whole core and getting my work done, I insisted to go with a simple workaround.

  1. function theme_name_form_id_alter(&$form, &$form_state, $form_id) {
  2.  $form['submitted']['your_field']['#attributes']['placeholder'] = t('Text to appear as placeholder');
  3.  $form['captcha']['#after_build'][] = 'custom_function_set_captcha_placeholder';
  4. }
  5. function custom_function_set_captcha_placeholder(&$element) {
  6.   $element['captcha_widgets']['captcha_response']['#attributes']['placeholder'] = t('Text to appear in the captcha field');
  7.   return $element;
  8. }

The #after-build took care of my work to replace the Placeholder in the captcha input field. With this piece of code, even you can save tons of time as I did.

Get awesome tech content in your inbox