Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drupal 7 hook_node_view add a form to the content of a node

function example_module_node_view($node, $view_mode, $langcode)
{   
    $f =  drupal_get_form('example_module_form', $node);
    $node->content['data_collection_form'] = array('#value' => $f, '#weight' => 1); 
}

Why doesn't the form display? Am I doing something wrong? The form object is being populated. I can do #markup => 'Something' and it works.

like image 393
Chris Muench Avatar asked Oct 25 '11 16:10

Chris Muench


2 Answers

The return from drupal_get_form is actually a render array itself so you could just do this:

$f = drupal_get_form('example_module_form', $node);
$f['#weight'] = 1;
$node->content['data_collection_form'] = $f;

If you do want to do it the other way though the form should be a renderable 'element', so the key shouldn't be prefixed by #:

$f = drupal_get_form('example_module_form', $node);
$node->content['data_collection_form'] = array(0 => $f, '#weight' => 1);

All entries in a render array with a key prefixed with # are considered properties, while those that aren't are considered 'children' and are recursively rendered.

like image 69
Clive Avatar answered Sep 19 '22 22:09

Clive


Clive answer doesn't work in my case. I needed to call drupal_render and pass it as markup.

$form = drupal_get_form('example_module_form', $node);
$node->content['data_collection_form'] = array(
  '#markup' => drupal_render($form),
  '#weight' => 10,
);

This work, but I'm not sure if this is the correct way.

like image 28
Camilo Avatar answered Sep 22 '22 22:09

Camilo