I'm trying to render a custom form in node.tpl.php.

The form is rendered properly and submit handler works.
However, the validation handler is not triggered properly upon submitting. If I refresh the page, the error message is only then displayed.

Here's the sample module code:

function sample_custom_form() {
  $form['sample_field'] = array(
    '#type' => 'textfield',
    '#title' => t('Enter something'),
  $form['actions'] = array('#type' => 'actions');
  $form['actions']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),

  return $form;

function sample_custom_form_validate(&$form, &$form_state) {
  if ($form_state['values']['sample_field'] == 'error') {
    form_set_error('sample_field', t('This is a validation error'));

function sample_custom_form_submit(&$form, &$form_state) {
  drupal_set_message(t('You entered: @value', array('@value' => $form_state['values']['sample_field'])));

In hook_preprocess_node():

$form = drupal_get_form('sample_custom_form');
$variables['custom_form'] = drupal_render($form);

In node.tpl.php:

<?php print $custom_form; ?>

Any ideas what am I doing wrong?
Why isn't the validation handler invoked properly?

  • Preprocess node is a theming hook, right? It means it's too late. Drupal can't properly prepare form at theming stage. Have you looked how does comment module do it?
    – Mołot
    Jul 12, 2015 at 12:38
  • Thanks for quick response. I'll have a look there right now. Jul 12, 2015 at 12:40

1 Answer 1


$form_state['values']['sample_field'] this value is set after submit, so you validate the old result instead of your actual form.

maybe this workflow helps you

  • 1
    Not sure I understand you; AFAIK $form_state['values']['sample_field'] is not set after submitting, it's there during the validation as well. Jul 12, 2015 at 13:00

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.