2

When I add a form to a node's render tree using hook_node_view(), eg

<?php

/**
* Implements hook_node_view().
*/
function MODULE_node_view($node, $view_mode, $langcode){
  if ($node->nid == 9 && module_exists('contact')) {
    module_load_include('inc', 'contact', 'contact.pages');
    $cForm = drupal_get_form('contact_site_form');
    //$cForm['#action'] .= '?destination=' .    request_path();
    $node->content['contact_form'] = array(
    '#markup' => drupal_render($cForm),
    '#weight' => 20,
    );
  }
}

then I get my messages displayed right after the submission.

I do the same thing with template_preprocess_node(), the messages are displayed one request after the submission.

I suspect this is related to the execution order. Can someone shed some light on the difference here?

2 Answers 2

1

It is indeed related to execution order and how messages are handled by the theme layer.

The $messages variable (which contains system messages) is processed and output at the page level (page.tpl.php) which occurs before node (node.tpl.php). So by the time you invoke drupal_get_form() from your node preprocessor, $messages has already been set up.

So, although $_SESSION['messages'] has been populated with the validation errors via drupal_get_form(), these won't appear until a page refresh.

hook_node_view(), on the other hand, is outside the theme layer and is invoked even before page processing begins, which is why it works. But if you want to make the change at the theme level, a workaround is to set up the messages manually after you call drupal_get_form() in template_preprocess_node():

$contact_form = drupal_get_form('contact_site_form');
$contact_form['#prefix'] = theme('set_messages');

Thanks to rémy for originally pointing out the problem on our site.

1
  • thx for the conclusion :D
    – rémy
    Commented May 6, 2014 at 10:16
2

It is the execution order. hook_node_view() acts on the node object as it is being assembled. When template_preprocess_node() is called, the node is ready to be rendered. For instance you may use template_preprocess_node() to change the date format.

2
  • Why does this result in the messages being one-page behind, though?
    – mpdonadio
    Commented Apr 18, 2014 at 20:39
  • thx - but when is the form rendered ? (inbetween ;))
    – rémy
    Commented Apr 23, 2014 at 14:56

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.