Skip to content

Instantly share code, notes, and snippets.

@samhernandez
Last active December 20, 2015 09:29
Show Gist options
  • Save samhernandez/6108076 to your computer and use it in GitHub Desktop.
Save samhernandez/6108076 to your computer and use it in GitHub Desktop.
Swap Drupal form error messages
<?php
// Drupal 7.22
// If there's an easier way please let me know
/**
* Swap out a form error message.
*
* This must be done with the actual message comparison since error keys
* are not stored in drupal messages.
*
* @param string $replace_me
* @param string $with_me
* @link http://drupal.stackexchange.com/questions/39851/how-to-change-error-message-displayed-failed-form-element-validation-to-be-dif
*/
function swap_form_error_message($replace_me, $with_me)
{
if (form_get_errors())
{
// Save errors
$form_errors = form_get_errors();
$drupal_errors = drupal_get_messages('error');
// Clear form errors
form_clear_error();
foreach($drupal_errors['error'] as $key => $error) {
if (in_array($error, $form_errors)) {
// Unset form errors
unset($drupal_errors['error'][$key]);
}
}
// Rebuild drupal errors
foreach($drupal_errors['error'] as $key => $message) {
drupal_set_message($message, 'error');
}
// Rebuild form errors replacing the desired message
// $message has extra words so use stripos()
foreach($form_errors as $key => $message) {
form_set_error($key, (stripos($message, $replace_me) !== false) ? $with_me : $message);
}
}
}
/*
Implementation example:
The checkbox for agreeing to terms of service must be checked
but the label needs html with a link to the TOS page.
Say we're doing this in a custom module called `mycomment`
*/
function mycomment_comment_form_alter(&$form, &$form_state, $form_id)
{
if (isset($form['field_agree']))
{
// get the language the field will be rendered in because it's the
// array key for the values that will be rendered
$lang = $form['field_agree']['#language'];
// replace the title with markup
$form['field_agree'][$lang]['#title'] = t("By submitting this comment, I have reviewed and agree to the ")
. '<a href="/tos">'
. t("Terms of Service &amp; Policies")
. '</a>.';
// set a validation callback so we can display a nice error message
$form['field_agree']['#element_validate'][] = '_validate_field_agree';
}
}
/**
* Set a nice error message for field_agree
*/
function _validate_field_agree($element, &$form_state, $form)
{
$lang = $element['#language'];
$checked = (bool) $element[$lang]['#checked'];
if ( ! $checked) {
swap_form_error_message($element[$lang]['#title'], t('Please agree to the terms of service by ticking the checkbox.'));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment