When I want to create or update a node programmatically I often use node_save core function. Example :
global $user; $customNode = new stdClass(); $customNode->type = 'page'; node_object_prepare($customNode); $customNode->uid = $user->uid; $customNode->name = $user->name; $customNode->title = 'Your page title'; $customNode->language = 'en'; $customNode->path['alias'] = 'Your Alias'; $customNode->comment = 1; $customNode->status = 1; // 1 means published $customNode->promote = 0; $customNode->revision = 0; $customNode->changed = $_SERVER['REQUEST_TIME']; $customNode->created = $_SERVER['REQUEST_TIME']; // FIELDS $customNode->field_1[LANGUAGE_NONE][0]['value'] = $entity_id; $customNode->field_2[LANGUAGE_NONE][0]['value'] = $entity_parent_id; // SAVE node_submit($customNode); node_save($customNode);
This method is probably the most elegant, but in some treatment cases you can't use it. For example when you want to fill dynamically some fields, without enumarating their names.
Indeed I had some xml files containing node structures and generic information fields (parametrized product fields), and I wanted to import these xml files into drupal nodes.
I looked for an other way to do it, and I found the drupal_form_submit function way. Example to use it :
global $user; module_load_include('inc', 'node', 'node.pages'); ////////////////////////////////////////////////// // 2 OPTIONS : // OPTION 1 : TO CREATE NEW NODE $node = (object) array( 'uid' => $user->uid, 'type' => $content_type, 'language' => LANGUAGE_NONE, ); // OPTION 2 : TO UPDATE EXISTING NODE // $node = node_load($nid); ////////////////////////////////////////////////// node_object_prepare($node); // Prepare form_state for the node save $form_state = array(); $form_state['node'] = $node; // extract from xml $entity_name = (string)$xml->name; $entity_id = (integer)$xml->id; // Static fields $form_state['values']['title'] = $entity_name; $form_state['values']['field_entity_id'][LANGUAGE_NONE][0]['value'] = $entity_id; // Dynamic info fields $fields_xml_values = get_info_fields_from_xml($instructionData); // Array( field_name => value ) foreach($content_type_fields as $field_name => $value) { $field_xml_value = $fields_xml_values[$field_name]; $form_state['values'][$field_name]['und'][0]['value'] = $field_xml_value; } // Without this line, NOT QUITE SURE WHY, it wont work. $form_state['values']['op'] = t('Save'); // Save the node drupal_form_submit('MY_CONTENT_TYPE_node_form', $form_state, (object)$node); // Tell watchdog if any of the fields fail validation. $errors = form_get_errors(); if (!empty($errors)) { foreach ($errors as $field_name => $message) { watchdog('xml import', '%field: %message', array('%message'=> $message, '%field' => $field_name)); } }The last method broughta more flexibility, so I thought it would be usefull for you too!