In my Drupal 7 module, I have a form and its validation handlers. I call my form from a field.tpl.php with print render(drupal_get_form('my_form')); it works as expected.

The problem is in case of wrong input value.

It requires two incorrect submissions before displaying the error message: The first time, there is red border around my wrong input, and the second time, the error message is displayed (with the red border).

So, what's the right way to use form_set_error()?


2 Answers 2


Form builders are not supposed to be called inside a template file, as they are being called too late. When you are calling render(drupal_get_form('my_form')), the code that renders the error messages has been executed, and the eventual error messages reported from the validation handler are saved in the current session from drupal_set_message(), which is called from form_set_error().

The code to print the error message is in the page.tpl.php file.

<?php if ($breadcrumb): ?>
  <div id="breadcrumb"><?php print $breadcrumb; ?></div>
<?php endif; ?>

<?php print $messages; ?>

The code in drupal_set_message() that saves the messages to show is the following one:

  if ($message) {
    if (!isset($_SESSION['messages'][$type])) {
      $_SESSION['messages'][$type] = array();

    if ($repeat || !in_array($message, $_SESSION['messages'][$type])) {
      $_SESSION['messages'][$type][] = $message;

    // Mark this page as being uncacheable.
  • Ok. I understand that using form_set_error() in a template file is the wrong way. So, what is the right way?
    – druvik
    Jan 4, 2012 at 7:12
  • 1
    drupal_get_form() should not be called inside a template file, but inside a module.
    – apaderno
    Jan 7, 2012 at 17:35
  • Ok, I have put it in a module and have use Display Suite to display it in my page. Thanks.
    – druvik
    Jan 9, 2012 at 7:39

You should be looking at form_set_error instead

if you have an element like this:

function my_custom_module_form() {
  $form = array();
  $form['my_element'] = array(
    '#type' => 'textfield',
    '#title' => 'My Text field',
    '#default_value' => 'Some default text.',
  return $form;

in your validation callback function do this if you find that the values in $form_state['values'] aren't valid

function my_custom_module_form_validate($form, &$form_state) {
  // Do some checking on $form_state['values'], if you don't like it.
  form_set_error('my_element', 'This is the error message that will be displayed.');
  • In fact, that's the function I use. (I correct the error from my first post).
    – druvik
    Jan 3, 2012 at 8:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.