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?