I have a content type that accepts a PDF document as a file attachment. I have a bunch of entries that currently have no attachment, but I have the files for each entry and need to associate the files with each of their respective entries.
Currently, all of those files are stored in public://publications, so they're already in the public file path where they should be, I just need to "hook them up".
Rather than hack this with Ruby which I would normally do, I'd like to kick the bad habit and use the Drupal API. I've looked at the following articles:
..but haven't been able to really wrap my head around it.
Curious if others have dealt with this situation and what they've done to address it. Thanks.
UPDATE
I've got the files copying as they should be. However, I'm not encountering an error, and the error happens during the node_save
call.
Here is the error:
PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '' for key 'uri': INSERT INTO {file_managed} (filesize, status, timestamp) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2); Array
(
[:db_insert_placeholder_0] => 0
[:db_insert_placeholder_1] => 1
[:db_insert_placeholder_2] => 1330491978
)
in drupal_write_record() (line 6975 of /var/www/website/drupal-7.4/includes/common.inc).
And here is the code.
$node = node_load($bib_value->nid);
$file = new stdClass();
$file->filename = basename($filepath);
$file->filepath = $filepath;
$file->filemime = file_get_mimetype($filepath);
$file->filesize = filesize($filepath);
$file->uid = 1;
$file->status = FILE_STATUS_PERMANENT;
$file->uri = $filepath;
$file = file_copy($file,'public://publications',FILE_EXISTS_REPLACE);
// THIS IS A PROBLEM LINE
$node->field_publication_attachment[LANGUAGE_NONE] = $file;
node_save($node);
If I comment out the line labeled THIS IS A PROBLEM LINE
then no error occurs, but that obviously isn't desirable because that means it's completing but without attaching my file to the node! Help!
SOLUTION
$node = node_load($bib_value->nid);
$file = new stdClass();
$file->filename = basename($filepath);
$file->filepath = $filepath;
$file->filemime = file_get_mimetype($filepath);
$file->filesize = filesize($filepath);
$file->uid = 1;
$file->status = FILE_STATUS_PERMANENT;
$file->uri = $filepath;
$file->display = 1;
$file->description = '';
$file = file_copy($file,'public://publications',FILE_EXISTS_REPLACE);
$node->field_publication_attachment[LANGUAGE_NONE][] = (array)$file;
node_save($node);
Needed to set display
and description
on $file
as well as cast $file
as an array when adding it to the attachment field. All worked smoothly after that.