2

I'm writing a custom form module.

Using Drupal7's FormAPI, I create a checkbox, the label/text diplayed next to it is set as described here

http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#checkbox

with the #title property,

    $form['test'] = array(
    '#type'     => 'checkbox',
    '#title'    => t('This is the text that gets displayed next to the checkbox'),
    '#required' => TRUE,
    );

which then displays in the browser,

[ ] This is the text that gets displayed next to the checkbox

Ih there's an error in submission that involves that checkbox, e.g. in the example above being required but not being checked, an error box is shown across the top content-area that says

"X  The This is the text that gets displayed next to the checkbox field is required"

I want to change that displayed error message to something other than the label/text. For example, on error,

"X  Selecting the displayed checkbox is required."

or

"X  You forgot to check the required checkbox.  Please try again."

How do I set the error-message text to be different that the assigned label/text?

2

Using a basic form in a custom module:

    function customform_demo($form, $form_state) {
    $form['test'] = array(
        '#type' => 'checkbox',
        '#title'    => t('This is the text that gets displayed next to the checkbox'),
        '#required' => TRUE,
    );

    $form['test_submit'] = array(
        '#type' => 'submit',
        '#value' => t('Submit'),
    );

    return $form;

}

You can set a custom error message in the form validation function. Here is a basic example with some comments:

    function customform_demo_validate($form, &$form_state) {

    // Test for existing form errors
    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');
        }

        // Validate form field and set error message    
        if ( $form_state['values']['test'] === 0 ) {
            form_set_error('test', t('You forgot to check the required checkbox. Please try again.'));
        }

                // Add more validation tests and error messages

    }
}
  • Perfect!! I was looking in the completely wrong place for this solution! THanks – user9281 Aug 15 '12 at 16:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy