2

How do I embed a node form and set some default values in that form in Drupal 7?

I understand that I can use this:

 $form = node_add('product_plan');
 print drupal_render($form);

That prints the form on to the page just fine, but I need help understanding how I can add default values. In Drupal 6, I would normally do this:

 function module_nodetype_form_embed( $property )
 {
     global $user;

    $node = new stdClass();
    $node->type = 'node_type';
    $node->uid = $user->uid;

    // Hidden through form alter
    $node->field_node_reference[0]['nid'] = $property->nid; 
    node_object_prepare( $node );

    return drupal_get_form( 'node_type_node_form', $node );

 }

So how can I get the same functionality in Drupal 7

1

I got it to work with this in D7:

In your custom module write this function:

function module_nodetype_form_embed( $property )
 {
 global $user;

$node = new stdClass();
$node->type = 'node_type';
$node->uid = $user->uid;
$node->name = (isset($user->name) ? $user->name : '');
// Hidden through form alter
$node->field_node_reference['und'][0]['target_id'] = $property->nid; 
node_object_prepare( $node );

return drupal_get_form( 'node_type_node_form', $node );

 }

When you want to embed this form in a node template, do this:

/* I'm assuming that your $property argument from the function
   is the $node page that you are embedding into. */

$form = module_nodetype_form_embed($node);
print drupal_render($form);

The only problem that I'm encountering is that the validation errors are not showing up on the initial submit if the user didn't fill in the form properly...BUT if you try and submit with invalid values more than once, the error messages show up. Weird....

| improve this answer | |
  • Thanks, this is working for me...but I am having the same problem with the error messages not showing up. I tried an embedded form with the node_add function and I still get the error message problem. – revolt Feb 9 '12 at 22:51
1

If you are using a 'select list' widget for the node reference you can do this:

$form = node_add('product_plan');
$form['FIELD_NAME'][$form['language']['#value']]['#value'] = 'NID';
return drupal_render($form);

'autocomplete' widget would look like:

$form = node_add('product_plan');
$element['#default_value'] = 'NID';
$form['FIELD_NAME'][$form['language']['#value']][0]['nid']['#value'] = node_reference_autocomplete_value($element, FALSE, '');
return drupal_render($form);
| improve this answer | |

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.