I need to remove a file field value, and instead, assign a new value to it. The file field contains video and the new video is in the videos directory. This is my code to delete a file field value (which works well)
$node = node_load(37);
// Get the language for the file field.
$lang = field_language('node', $node, 'field_video');
// load the file
$file = file_load($node->field_video[$lang][0]['fid']);
// unset the field for the node
unset($node->field_video[$lang][0]);
// delete file from disk and from database
file_delete($file);
// Save the node.
node_save($node);
But this code which assigns a new value, reports an error. I get this code from How to set value of file field with entity_metadata_wrapper
$node = node_load(37);
$realpath="";
if ($wrapper = file_stream_wrapper_get_instance_by_uri('public://')) {
$realpath = $wrapper->realpath();
}
$file_path = $realpath."\\video_file\\sarmaye.mp4";
$file = new stdClass;
$file->uid = $node->uid;
$file->filename = pathinfo($file_path, PATHINFO_BASENAME);
$file->uri = $file_path;
$file->filemime = file_get_mimetype($file_path);
$file->display = '1';
// Make it permanent, otherwise it will get deleted later.
$file->status = FILE_STATUS_PERMANENT;
file_save($file);
$file = (array) $file;
$items = array($file);
$ewrapper = entity_metadata_wrapper('node', $node);
$ewrapper->field_video->set($items);
$ewrapper->save(true);
But it reports this error
PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'D:\xampp\htdocs\MySiteName\sites\default\files\video_file\sarmaye' for key 'uri': INSERT INTO {file_managed} (uid, filename, uri, filemime, filesize, status, timestamp) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4, :db_insert_placeholder_5, :db_insert_placeholder_6); Array ( [:db_insert_placeholder_0] => 1 [:db_insert_placeholder_1] => sarmaye.mp4 [:db_insert_placeholder_2] => D:\xampp\htdocs\MySiteName\sites\default\files\video_file\sarmaye.mp4 [:db_insert_placeholder_3] => video/mp4 [:db_insert_placeholder_4] => 4877369 [:db_insert_placeholder_5] => 1 [:db_insert_placeholder_6] => 1468934410 ) in drupal_write_record() (line 7361 of D:\xampp\htdocs\MySiteName\includes\common.inc).