1

I want to add a form to a node before it is passed along to the theme layer.

My module has a hook_node_load, as follows:

function gp_shop_node_load($nodes, $types) {
  foreach($nodes as $nid => $node) {
    //Determine if we should process. aka: only run on Record->type() types.
    if (!in_array("product", $types)) {
      continue;
    }

    $nodes[$nid]->gp_shop_order_button = "[BUTTON]";
  }
}

This works: the text [BUTTON] is added to $node if it is type "product";

However, when placing an actual form, it breaks in a Maximum function nesting level of '100' reached, aborting!-error. An endless loop of some sorts. As follows:

    $nodes[$nid]->gp_shop_order_button = drupal_get_form("gp_shop_order_button", $node);

Edit: In the final code, I problably have to wrap this in a drupal_render() even; for now it makes no difference. The relevant line would then be:

$nodes[$nid]->gp_shop_order_button = drupal_render(drupal_get_form("gp_shop_order_button", $product));

And then with the callback-hook for the form.

function gp_shop_order_button($form, &$form_state, $node) {
  $form = array();

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Order',
  );

  return $form;
}

The part about passing along the $nodeis not very relevant and is not causing the problem. Just left it in my examples here, to illustrate that passing along parameters is a requirement.

What am I doing wrong?

  • 2
    Stab in the dark...the constructor for your Product class calls node_load internally, causing an infinite loop – Clive Sep 18 '12 at 11:42
  • No. The class has nothing to do with this. I removed it entirely and the recursion still occurs. I'll update my code to make the example and problem more clear. Sec. – berkes Sep 18 '12 at 12:48
2

Not entirely sure why hook_node_load does not work, but some trial and error (in contrast to the documentation) led me to a working solution using hook_node_view instead.

The example code being:

function gp_shop_node_view($node, $view_mode, $langcode) {
  if ("product" == $node->type) {
    if ($view_mode == 'full' && node_is_page($node)) {
      $node->content['gp_shop_order_button'] = drupal_get_form("gp_shop_order_button", $node);
      }
    }
  }
}

function gp_shop_order_button($form, &$form_state, $node) {
  $form = array();

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Order',
  );

  return $form;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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