I am creating nodes using this type of code:

   if (user_access('create '. $type . ' content')) {
     $output = node_add($type);
   }

What I would like to do is prepopulate some of the fields of the node with data when the form is displayed. Can this be done with node_add (I know you can do it with node_save, but I need to display a form), and if so, how?

Thanks.

Comments

sun’s picture

No, use drupal_retrieve_form() instead: http://api.drupal.org/api/5/function/drupal_retrieve_form

Daniel F. Kudwien
unleashed mind

Daniel 'sun' Kudwien
makers99

somebodysysop’s picture

Let's say I just want to display the form to add a new page.

$form = drupal_retrieve_form('page_node_form');
return $form;

This doesn't seem to do it.

The api tells me what the function does, but not how to use it. I searched for "drupal_retrieve_form", and found only the api and error messages. The only pages I found where it is used in code is in addnode: http://drupal.org/node/125284 and in a nodetemplate error: http://drupal.org/node/116420

All I want to do is insert a value into the title or body of the form, have the user edit it if he wants, then submit the node. Help?

inty’s picture

I also want to do that! Have you come up with a solution you might be willing to share?

math0ne’s picture

I'm looking for a solution for this as well. Basically what i need to do is generate a create node form with a couple of the fields auto-filled and hidden.

Anyone have any ideas?

panis’s picture

depends.. this will work assuming you want to display a form

<?php
global $user;
$new_node = array(
  'uid' => $user->uid,
  'name' => $user->name,
  'type' => $type, /* replace with your type. */
  'title' => 'Prepopulate with a title if you like', 
/* if you know the names of other fields that you would like to populate you can fill this associative
 * array with those values
 */
  );
return drupal_get_form($type ."_node_form", $new_node);
?>

If you want to create a node in the fly without the form - take a look at the node_factory module at
http://drupal.org/project/node_factory/

somebodysysop’s picture

Unfortunately, I can't recall exactly what i was trying to do, but I do know now that in order to pre-populate fields, or maninpulate a node/add form in some way, I could use:

hook_form_alter

hook_nodeapi('prepare')

panis’s picture

sure those are alternatives - depending on what you are trying to accomplish. All these approaches will work best in certain scenarios and it may be good to put together a documentation page that displays each of these methods as examples.