1

I want to do something very simple - create a content of a specific type when a user joins a group.

Unfortunately I can not find a simple way of how it should be done.

It can be done with rules so I've been thinking about triggering one, but the details would be awfully complicated. I thought about having a template node that I would clone and edit, but how should I go for it? There are number of modules that do that in a strange way, while saying "it might sometimes not work properly", some people use things like drupal_execute(), I have found that node_save() has an option $node->is_new = TRUE. I found someone suggesting a use of forms, but they were always very simple and were not working with complicated/custom fields. I figured that maybe something like this could work:

$form = drupal_get_form('my_content_node_form');
$form_state = array();
do_some_edits($form,$form_state);
drupal_form_submit($form->id, $form_state);

What is a proper/simple way of dealing with this issue? What I would expect see is something like $node = node_create($content_type) but for some reason I can not find it.

3

Provided you have a rule that triggers when a user joins a group, and a condition that checks that the group is the group you want, then add a execute PHP action to that rule that runs this code :

// Build a new node object
$node = new StdClass(); 
// set the type
$node->type = 'your_content_type';
// set the language
$node->language = LANGUAGE_NONE; // or whatever language you use.
// this fills the node with the default data
node_object_prepare($node);
// set a custom title
$node->title = 'Nice title';
// set whatever you want, for example body
$node->body[LANGUAGE_NONE][0]['value'] = 'This is some text for the body';
// Set the formatting for the text
$node->body[LANGUAGE_NONE][0]['format'] = 'filtered_html';
// Save the node to the DB
node_save($node);
// If you need the node ID
$nid = $node->nid;
// Just for debugging
watchdog('your_module','Just inserted the node with nid = '.$nid);

The key here is that node_object_prepare sets some default values for your content type.

2
  • Thanks, I tested it and this is exactly what I need. node_object_prepare() does everything I was looking for. It assigns new nid, fills in the authoring information, and builds the fields of the node. I don't understand why I could not find a simple solution like this anywhere. – Pawel G Feb 20 '13 at 10:48
  • Glad to help, and remember api.drupal.org can be a great resource of information. – drcelus Feb 20 '13 at 10:51

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.