How to add image to node programmaticly? - drupal

There is an entity in which I added the Image field. The database has a custom table with different columns, including the id of the images.
Previously, I created a batch that writes data from this table to entity fields. That is, it creates many entities from the records in the table with filled fields. I need to do the same but for images. Part of the code from the batch:
if (empty($entity_id)) {
$info = [
'type' => 'product',
'title' => $productTitle,
'field_name' => (string) $product->name,
'field_product_cid' => (string) $product->cid,
'field_custom_url' => $product->url,
'uid' => 1,
// here I need to add an image to the field_image field from the table
];
$node = $this->entityTypeManager->getStorage('node')->create($info);
$node->save();
}
else {
$storage = $this->entityTypeManager->getStorage('node');
$node = $storage->load($entity_id);
// Change fields of node.
$node->set('title', $productTitle);
$node->set('field_name', (string) $product->name);
$node->set('field_custom_url', $product->url);
// and here change field_image if the node already exists
$node->save();
}
}

Someting like this:
$node = $storage->load($entity_id);
$image_source_path = '/some/path'
$image_target_directory = 'public://some/path';
$image_data = file_get_contents ($image_source_path);
$image_alt = 'some alt text';
// Drupal 9 >= 9.3.0 or Drupal 10
$image_object = \Drupal::service('file.repository')
->writeData($$image_data, $image_target);
// Drupal 8
//$image_object = file_save_data ($image_data, $image_target);
$node->set('field_image', [
'target_id' => $image_object->id(),
'alt' => $image_alt,
]);
$node->save();

Related

Dynamically pull values from nested form using Gravity Forms & Gravity Wiz Nested Forms

So I've been going through a restructure build of an entire site, and part of that involved switching from Formidable Forms to Gravity Forms. We did this because we wanted to use the Nested Form feature, so that we could automate multiple attendees without having to create a new form for each.
Here's the problem - on our old site that did have a separate form per attendee via Formidable, we had a code using the Canvas API to send name + email info to Canvas and automatically register users for the online courses this company offers. In trying to convert sections of this code to work with my nested forms, I'm running into a snag:
The main issue is that the value is being spit out as all of the information from the nested form entry, not by name/ email/ etc.
The info is being spit out twice, perhaps because of the way the forms are structured? There are a couple calculations happening in the forms/ nested forms so I'm chalking it up to that.
[1] => WC_Meta_Data Object
(
[current_data:protected] => Array
(
[id] => 212
[key] => Attendee Registration
[value] =>
Name
Test Name
Email Address
courses#email.com
Cell Phone
(333) 333-3333
Would you like to receive text message reminders for this registration?
No
Post-class notification is required for the following states, please identify if you will be using this class to fulfill any state license requirements:
N/A
You'll receive a hard copy and digital certificate upon course completion. Additional options are available here:
All live classes include a hard copy manual and regulations. To join our effort to save paper, please also add any of the following options to take your books home:
)
[data:protected] => Array
(
[id] => 212
[key] => Attendee Registration
[value] =>
Name
Test Name
Email Address
courses#email.com
Cell Phone
(333) 333-3333
Would you like to receive text message reminders for this registration?
No
Post-class notification is required for the following states, please identify if you will be using this class to fulfill any state license requirements:
N/A
You'll receive a hard copy and digital certificate upon course completion. Additional options are available here:
All live classes include a hard copy manual and regulations. To join our effort to save paper, please also add any of the following options to take your books home:
)
)
Also: I was playing around with grabbing the ID of the main entry via [_gravity_form_linked_entry_id], and grabbing the nested info from that via [_gravity_form_lead].
The best I was able to get from that was this... so yeah kind of lost on how to progress here if anyone has any pointers! Thanks so much!
[data:protected] => Array
(
[id] => 211
[key] => _gravity_forms_history
[value] => Array
(
[_gravity_form_cart_item_key] => 72201a9586fb30895b8fb5cac2a796b9
[_gravity_form_linked_entry_id] => 125
[_gravity_form_lead] => Array
(
[form_id] => 1
[source_url] => https://chcv2.flywheelstaging.com/product/air-monitoring-specialist-live/
[ip] => 75.151.95.41
[42.1] => Course Price
[42.2] => $580.00
[42.3] => 1
[21] => 122
[40.1] => Add-On Fees
[40.2] => $0.00
[40.3] => 1
)
[_gravity_form_data] => Array
(
[id] => 1
[bulk_id] => 0
[display_title] =>
[display_description] =>
[disable_woocommerce_price] => no
[price_before] =>
[price_after] =>
[disable_calculations] => no
[disable_label_subtotal] => yes
[disable_label_options] => yes
[disable_label_total] => no
[disable_anchor] => no
[label_subtotal] => Course Fee
[label_options] => Additional Attendees + Selected Options
[label_total] => Attendee Registration + Add-Ons:
[use_ajax] => no
[enable_cart_edit] => no
[enable_cart_edit_remove] => no
[keep_cart_entries] => no
[send_notifications] => no
[enable_cart_quantity_management] => stock
[cart_quantity_field] =>
[update_payment_details] => yes
[display_totals_location] => after
[structured_data_override] => no
[structured_data_low_price] =>
[structured_data_high_price] =>
[structured_data_override_type] => overwrite
)
)
)
Update: Here's how I've incorporated the code from Rochelle's comment below, where I'm getting an error
add_action( 'woocommerce_thankyou', 'canvas_enroll', 20, 2 );
function canvas_enroll($orders) {
$query = new WC_Order_Query( array(
'orderby' => 'date',
'order' => 'DESC',
'return' => 'ids',
) );
$orders = $query->get_orders();
foreach($orders as $order){
foreach ($order->get_items() as $item_id => $item_data) {
if(isset($item_data->get_meta( '_gravity_forms_history')["_gravity_form_lead"]["form_id"]) && !empty($item_data->get_meta( '_gravity_forms_history')["_gravity_form_lead"]["form_id"])){
$linked_entry=$item_data->get_meta( '_gravity_forms_history')["_gravity_form_linked_entry_id"];
$entry_id = $linked_entry;
$entry = GFAPI::get_entry( $entry_id );//id of Parent Gravity Form
if(isset($item_data->get_meta( '_gravity_forms_history')["_gravity_form_lead"]['2']) && !empty($item_data->get_meta( '_gravity_forms_history')["_gravity_form_lead"]['2'])){
$linked_nested_value=$item_data->get_meta( '_gravity_forms_history')["_gravity_form_lead"]['2'];
$nested_value_array = preg_split ("/\,/", $linked_nested_value); //array of child entries
$child_entry_amt = substr_count($linked_nested_value, ",") + 1;
if ($child_entry_amt > 0){
for ($n = 0; $n < $child_entry_amt; $n++) {
$entry_id_nest[$n]=$nested_value_array[$n];
$entry_nest[$n] = GFAPI::get_entry( $entry_id_nest[$n] ); //nested form entry
$name[$n] = $entry_nest[$n]['12.3'].''.$entry_nest[$n]['12.6'];//replace 1.3 and 1.6 with nested field id of name
$email[$n] = $entry_nest[$n]['11']; //2 is the GF nested field id of email
}
}
}
}
}
}
}
Finally got this figured out! Something that was super helpful was to echo the item meta data ($value, in my case) for that to display all the ids and such, that's how I was able to figure out that I needed 21 in that ID for the child entries.
I'm not really sure why I had to switch to wc_get_order instead of wc_order_query, but it solved the errors I was getting.
function canvas_enroll($order_id) {
$order = wc_get_order( $order_id);
$order_id = array(
'orderby' => 'date',
'order' => 'DESC',
'return' => 'ids',
);
if(!empty($order) && isset($order)){
// Loop through order line items
foreach( $order->get_items() as $key => $value ){
// get order item data (in an unprotected array)
if(isset($value->get_meta( '_gravity_forms_history')["_gravity_form_lead"]["form_id"]) && !empty($value->get_meta( '_gravity_forms_history')["_gravity_form_lead"]["form_id"])){
$linked_entry=$value->get_meta( '_gravity_forms_history')["_gravity_form_linked_entry_id"];
$entry_id = $linked_entry;
$entry = GFAPI::get_entry( $entry_id );//id of Parent Gravity Form
if(isset($value->get_meta( '_gravity_forms_history')["_gravity_form_lead"]['21']) && !empty($value->get_meta( '_gravity_forms_history')["_gravity_form_lead"]['21'])) { //21 was the id for my child form
$linked_nested_value = $value->get_meta( '_gravity_forms_history')["_gravity_form_lead"]['21'];
$nested_value_array = preg_split ("/\,/", $linked_nested_value); //array of child entries
$child_entry_amt = substr_count($linked_nested_value, ",") + 1;
if ($child_entry_amt > 0){
for ($n = 0; $n < $child_entry_amt; $n++) {
$entry_id_nest[$n]=$nested_value_array[$n];
$entry_nest[$n] = GFAPI::get_entry( $entry_id_nest[$n] ); //nested form entry
$firstname[$n] = $entry_nest[$n]['12.3'];//replace 12.3 with nested field id of first name
$lastname[$n] = $entry_nest[$n]['12.6'];//replace 12.6 with nested field id of last name
$email[$n] = $entry_nest[$n]['11']; //replace 11 with nested field id of email
}
}
}
}
}
}
}
I'm just going to paste the code I used for another project that I needed to pull the same type of data in case it puts you on the right track. You'd have to replace the numbers with the ids from your forms:
$query = new WC_Order_Query( array(
'orderby' => 'date',
'order' => 'DESC',
'return' => 'ids',
) );
$orders = $query->get_orders();
foreach($orders as $order){
foreach ($order->get_items() as $item_id => $item_data) {
if(isset($item_data->get_meta( '_gravity_forms_history')["_gravity_form_lead"]["form_id"]) && !empty($item_data->get_meta( '_gravity_forms_history')["_gravity_form_lead"]["form_id"])){
$linked_entry=$item_data->get_meta( '_gravity_forms_history')["_gravity_form_linked_entry_id"];
$entry_id = $linked_entry;
$entry = GFAPI::get_entry( $entry_id );//id of Parent Gravity Form
if(isset($item_data->get_meta( '_gravity_forms_history')["_gravity_form_lead"]['2']) && !empty($item_data->get_meta( '_gravity_forms_history')["_gravity_form_lead"]['2'])){
$linked_nested_value=$item_data->get_meta( '_gravity_forms_history')["_gravity_form_lead"]['2'];
$nested_value_array = preg_split ("/\,/", $linked_nested_value); //array of child entries
$child_entry_amt = substr_count($linked_nested_value, ",") + 1;
if ($child_entry_amt > 0){
for ($n = 0; $n < $child_entry_amt; $n++) {
$entry_id_nest[$n]=$nested_value_array[$n];
$entry_nest[$n] = GFAPI::get_entry( $entry_id_nest[$n] ); //nested form entry
$name[$n] = $entry_nest[$n]['1.3'].''.$entry_nest[$n]['1.6'];//replace 1.3 and 1.6 with nested field id of name
$email[$n] = $entry_nest[$n]['2']; //2 is the GF nested field id of email
}
}
}
}
}
}
Ok. Try this first to see if it changes anything:
$query = new WC_Order_Query( array(
'orderby' => 'date',
'order' => 'DESC',
'return' => 'ids',
) );
$orders = $query->get_orders();
foreach($orders as $order){
if(!empty($order) && isset($order)){
foreach ($order->get_items() as $item_id => $item_data) {
if(isset($item_data->get_meta( '_gravity_forms_history')["_gravity_form_lead"]["form_id"]) && !empty($item_data->get_meta( '_gravity_forms_history')["_gravity_form_lead"]["form_id"])){
$linked_entry=$item_data->get_meta( '_gravity_forms_history')["_gravity_form_linked_entry_id"];
$entry_id = $linked_entry;
$entry = GFAPI::get_entry( $entry_id );//id of Parent Gravity Form
if(isset($item_data->get_meta( '_gravity_forms_history')["_gravity_form_lead"]['2']) && !empty($item_data->get_meta( '_gravity_forms_history')["_gravity_form_lead"]['2'])){
$linked_nested_value=$item_data->get_meta( '_gravity_forms_history')["_gravity_form_lead"]['2'];
$nested_value_array = preg_split ("/\,/", $linked_nested_value); //array of child entries
$child_entry_amt = substr_count($linked_nested_value, ",") + 1;
if ($child_entry_amt > 0){
for ($n = 0; $n < $child_entry_amt; $n++) {
$entry_id_nest[$n]=$nested_value_array[$n];
$entry_nest[$n] = GFAPI::get_entry( $entry_id_nest[$n] ); //nested form entry
$name[$n] = $entry_nest[$n]['1.3'].''.$entry_nest[$n]['1.6'];//replace 1.3 and 1.6 with nested field id of name
$email[$n] = $entry_nest[$n]['2']; //2 is the GF nested field id of email
}
}
}
}
}
}
}

Drupal 7: custom module: display custom contentTypy in custom block

I'm new at Drupal 7, so I have a question.
I have my own content type Writers that includes such fields as Title, Years of life, Photo, Description.
I have a task to display 3 random Writers at page. Actual I've done it with help of Views module, but I want to do it myself.
So I created my own module random_content like that:
<?php
function random_content_help($path, $arg) {
switch ($path) {
case "admin/help#random_content":
return '<p>'. t("Displays random content") .'</p>';
break;
}
}
function random_content_block_info() {
$blocks['random_content'] = array(
'info' => t('Random content'),
'cache' => DRUPAL_CACHE_PER_ROLE,
);
return $blocks;
}
function random_content_contents() {
$query = db_select('node', 'n')
->fields('n', array('nid', 'title'))
->condition('type', 'writers')
->orderBy('rand()')
->range(0,3)
->execute();
return $query;
}
function random_content_block_view($delta = '') {
switch($delta){
case 'random_content':
$block['subject'] = t('Random content');
if(user_access('access content')) {
$result = random_content_contents();
$items = array();
foreach ($result as $node){
$items[] = array(
'data' => l($node->title, 'node/' . $node->nid) . '</br>',
);
}
if (empty($items)) {
$block['content'] = t('No data availible.');
} else {
$block['content'] = theme('item_list', array(
'items' => $items));
}
}
}
return $block;
}
As you can see, I've learned only to add links to particular content. But how can I display full information including Title, Years of life, Photo and Description?
To display the full node, or parts of it you need to load the node. E.g.
$my_node = node_load($nid);
$render_array = array();
$render_array['title'] = array(
'#type' => 'markup',
'#markup' => $my_node->title
);
$author = field_get_items('node', $my_node, 'field_author','und');
$render_array['author'] = array(
'#type' => 'markup',
'#markup' => $author[0]['safe_value']
);
// or as some like to do it
$render_array['author'] = array(
'#type' => 'markup',
'#markup' => $my_node->field_author['und'][0]['value']
);
echo drupal_render($render_array);
Note the 'und' constant means the language is undefined. If you have translation/language enabled and different content for different languages you would have to use 'en', 'de' etc. for the appropriate language.
You can also let drupal render the node and then manipulate or retrieve individual items. Like this
$my_node = node_load($nid);
$build = node_view($my_node,'full');
$build['body'][0]['#markup'] = $build['body'][0]['#markup'].' some addition';
$build['field_author'][0]['#markup'] = $build['field_author'][0]['#markup'].' my favorite';
echo drupal_render($build);
The advantage of using this latter method is that then the whole themeing engine kicks in, and all hooks that are set to act on the content etc. Of course, if you only want to retrieve values you don't need that.
Note also, I assume your author field is named field_author. You should check that in the field edit window for the content type.

Mapping existing Image with new content types

I am facing a situation here.
I have a content type A with an image field(field_upload_snaps) in it. There is another content type B which also contains an image field(field_valid_snaps).
Now user will upload the pics from A content type. So if user upload 3 pics via A then 3 FID and their corresponding URIs will be created in file_managed table in Drupal 7.
Now I have a requirement where I have to insert 2 images out of 3 programatically using Drupal code. Now there is no need to generate any new image copy in public URI as images already exist via A.
I tried two approaches:-
1) I have created a new node of Type B. I tried to fetch file URI,filesize,filemime and all relevant parameter from existing fid and associate with the node using this.
global $user;
$node = new stdClass();
$node->type = "user_slideshow_snaps";
$node->language = LANGUAGE_NONE;
node_object_prepare($node);
$node->uid = $user->uid;
$file = (object) array(
'uid' => $user->uid,
'uri' => 'public://1.jpeg" ,
'filemime' => 'image/jpeg',
'status' => 1,
);
$node->field_upload_snaps['und'][] = (array)$file;
$node = node_submit($node); // Prepare node for a submit
node_save($node);
But it gives me an error that "Cant insert duplicate value in file_managed". It will give because such value already exist in file_managed via A. So I am not able to save value.
2) I saved node first and then manually insert in the image field like this.
global $user;
$node = new stdClass();
$node->type = "user_slideshow_snaps";
$node->language = LANGUAGE_NONE;
node_object_prepare($node);
$node->uid = $user->uid;
$node = node_submit($node); // Prepare node for a submit
node_save($node);
db_insert('field_data_field_valid_snaps')
->fields(array(
'entity_type' => 'node',
'bundle' => 'user_actualD_snaps',
'deleted'=> 0,
'entity_id'=>$node->nid,
'delta'=>0,
'field_valid_snaps_fid'=>517,
'field_valid_snaps_alt'=>'',
'field_valid_snaps_title'=>'',
'field_valid_snaps_width'=>200,
'field_valid_snaps_height'=>300,
))
->execute();
But the line after node_save() doesnt execute in this case. So I am not able to save it.
Are there any functions available which will map existing images into another table?
YOUR SOLUTION!!
$url = "YOUR FILE URL";
//$node = new StdClass();
or
//$node = node_load("YOUR NODE ID");
$file_data = file_get_contents($url);
if ($file_data) {
$directory = file_default_scheme() . '://public';
$path = file_stream_wrapper_uri_normalize($directory . 'GIVE YOUR FILE NAME');
$file = file_save_data($file_data, $path, FILE_EXISTS_REPLACE);
if ($file->fid > 0) {
// REPLACE WITH YOUR FIELD NAME
$node->field_XXXX = array(
'und' => array(
0 => array(
'fid' => $file->fid,
'uri' => $file,
'display' => '1',
),
),
);
}
node_save($node);
}
File_load API solved my problem of getting the dimensions of existing file and save in another content type.

migrating url alias from drupal6 to drupal7 as a part of migration process

I have migrated nodes using migrate module v2. Currently i am running into a problem that the previous site used url aliases,which have not been migrated into drupal7 and will affect the site rank from SEO perspective.
Is there a way i can migrate the path aliases while running the migration classes itself?If not what would be the best way to do so?
You can migrate your legacy aliases directly into the Drupal 7 path field:
$this->addFieldMapping('path', 'my_legacy_alias_field');
Here is a very stripped down migration class that includes an easy method for bringing URLs along for the ride. Intended for use with the Migrate module.
class MyNodeMigration extends Migration {
public function __construct(array $arguments) {
$this->arguments = $arguments;
parent::__construct();
$source_fields = array('nid' => t('The node ID of the page'));
$query = Database::getConnection('default', 'legacy')
->select('node', 'n')
->fields('n');
$query->join('url_alias', 'a', "a.src = CONCAT('node/', n.nid)");
$query->addField('a', 'dst');
$this->source = new MigrateSourceSQL($query, $source_fields);
$this->destination = new MigrateDestinationNode('my_node_type');
$this->map = new MigrateSQLMap($this->machineName,
array('nid' => array(
'type' => 'int',
'unsigned' => TRUE,
'not null' => TRUE,
'description' => 'D6 Unique Node ID',
'alias' => 'n',
)),
MigrateDestinationNode::getKeySchema()
);
$this->addSimpleMappings(array('title', 'created', 'changed', 'status'));
$this->addUnmigratedDestinations(array('sticky', 'log', 'nid'));
$this->addFieldMapping('path', 'dst');
$this->addFieldMapping('is_new')->defaultValue(TRUE);
}
}
As I can see, the url_aliastable is globally the same, expect the name of fields whom changed from srcto sourceand dst to alias. So I guess you can easily copy the content from your Drupal 6 to your Drupal 7.
I never tried, but in theory it should work.
The best way (according to me) to have the same url aliases is :
1> install url_alias module.
2> configure the nodes with patterns similar to drupal6. Now, this step may trouble you, in case the new url-aliases have nids attached to them.(as in my case).
As a solution we can go ahead and create custom tokens using code where the source id can be fetched from the migrate map tables based on the new destination ids which are easily available.
Now, we can go ahead and bulk generate url-aliases.
An example for creating such custom token would be:
/**
* Implements hook_token_info().
*/
function custom_configuration_token_info() {
$type = array(
'node' => array (
'name' => t('Nodes'),
'description' => t('Tokens related to individual nodes.'),
'needs-data' => 'node',
),
'term' => array(
'name' => t('Taxonomy Terms'),
'description' => t('Tokens related to taxonomy terms.'),
'needs-data' => 'term',
)
);
// tokens for node legacy nid.
$tokens['node']['mapid'] = array(
'name' => t("mapid"),
'description' => t("The nid of the node prior to migration."),
);
$tokens['term']['mapid'] = array(
'name' => t('mapid'),
'description' => t('The tid of taxonomy terms prior to migration.'),
);
return array(
'types' => $type,
'tokens' => $tokens,
);
}
now,
function custom_configuration_tokens($type, $tokens, array $data = array(), array $options = array()) {
$url_options = array('absolute' => TRUE);
if (isset($options['language'])) {
$url_options['language'] = $options['language'];
$language_code = $options['language']->language;
}
else {
$language_code = NULL;
}
$sanitize = !empty($options['sanitize']);
$replacements = array();
if ($type == 'node' && !empty($data['node'])) {
$node = $data['node'];
foreach ($tokens as $name => $original) {
switch ($name) {
<write your custom code for the token conditioned by the name attribute in info function>
}
}
}
While writing your custom code, you mite also be needing the legacy table. Drupal 7 supports multiple databases, so just configure the legacy table credentials in settings.php file.
Use drupal_set_active while fetching data from the different tables.
Thanks.

Uploading and saving a file programmatically to Drupal nodes

I am trying to create a node based on a custom form submission. Everything works great except for the images that get uploaded.
I can capture them fine and set them in the form object cache. When I pass the data into the function to create the node, I get this error:
"The specified file could not be copied, because no file by that name exists. Please check that you supplied the correct filename."
I also receive the error multiple times, despite only submitting one or two images at a time.
Here is the code I am using. $uploads is passed in and is an array of file objects returned from file_save_upload() in a previous step:
if (isset($uploads)) {
foreach ($uploads as $upload) {
if (isset($upload)) {
$file = new stdClass;
$file->uid = 1;
$file->uri = $upload->filepath;
$file->filemime = file_get_mimetype($upload->uri);
$file->status = 1;
$file = file_copy($file, 'public://images');
$node->field_image[$node->language][] = (array) $file;
}
}
}
node_save($node);
I also tried this:
if (isset($uploads)) {
foreach ($uploads as $upload) {
$upload->status = 1;
file_save($upload);
$node->field_image[$node->language][] = (array) $upload;
}
}
}
node_save($node);
The second causes a duplicate key error in MySQL on the URI field. Both of these examples I saw in tutorials, but neither are working?
For Drupal 7, I played around with this quite a bit and found the best way (and only way that I've got working) was to use Entity metadata wrappers
I used a managed file form element like so:
// Add file upload widget
// Use the #managed_file FAPI element to upload a document.
$form['response_document'] = array(
'#title' => t('Attach a response document'),
'#type' => 'managed_file',
'#description' => t('Please use the Choose file button to attach a response document<br><strong>Allowed extensions: pdf doc docx</strong>.'),
'#upload_validators' => array('file_validate_extensions' => array('pdf doc docx')),
'#upload_location' => 'public://my_destination/response_documents/',
);
I also pass along the $node object in my form as a value
$form['node'] = array('#type' => 'value', '#value' => $node);
Then in my submission handler I simply do the following:
$values = $form_state['values'];
$node = $values['node'];
// Load the file and save it as a permanent file, attach it to our $node.
$file = file_load($values['response_document']);
if ($file) {
$file->status = FILE_STATUS_PERMANENT;
file_save($file);
// Attach the file to the node.
$wrapper = entity_metadata_wrapper('node', $node);
$wrapper->field_response_files[] = array(
'fid' => $file->fid,
'display' => TRUE,
'description' => $file->filename,
);
node_save($node);
}
i used your code to upload a file in the file field to a content("document" in my case) and it's worked. Just had to add a value for field_document_file 'display' in the code.
here is the exact script i used:
<?php
// Bootstrap Drupal
define('DRUPAL_ROOT', getcwd());
require_once './includes/bootstrap.inc';
require_once './includes/file.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
// Construct the new node object.
$path = 'Documents/document1.doc';
$filetitle = 'test';
$filename = 'document1.doc';
$node = new StdClass();
$file_temp = file_get_contents($path);
//Saves a file to the specified destination and creates a database entry.
$file_temp = file_save_data($file_temp, 'public://' . $filename, FILE_EXISTS_RENAME);
$node->title = $filetitle;
$node->body[LANGUAGE_NONE][0]['value'] = "The body of test upload document.\n\nAdditional Information";
$node->uid = 1;
$node->status = 1;
$node->type = 'document';
$node->language = 'und';
$node->field_document_files = array(
'und' => array(
0 => array(
'fid' => $file_temp->fid,
'filename' => $file_temp->filename,
'filemime' => $file_temp->filemime,
'uid' => 1,
'uri' => $file_temp->uri,
'status' => 1,
'display' => 1
)
)
);
$node->field_taxonomy = array('und' => array(
0 => array(
'tid' => 76
)
));
node_save($node);
?>
Kevin, that's what I found in the Drupal doc's under http://drupal.org/node/201594 below in the comments. But I am not sure at all. I try the same, so please let me know what you found out.
$path = './sites/default/files/test.jpg';
$filetitle = 'test';
$filename = 'test.jpg';
$node = new StdClass();
$file_temp = file_get_contents($path);
$file_temp = file_save_data($file_temp, 'public://' . $filename, FILE_EXISTS_RENAME);
$node->title = $filetitle;
$node->uid = 1;
$node->status = 1;
$node->type = '[content_type]';
$node->language = 'und';
$node->field_images = array(
'und' => array(
0 => array(
'fid' => $file_temp->fid,
'filename' => $file_temp->filename,
'filemime' => $file_temp->filemime,
'uid' => 1,
'uri' => $file_temp->uri,
'status' => 1
)
)
);
$node->field_taxonomy = array('und' => array(
0 => array(
'tid' => 76
)
));
node_save($node);

Resources