Drupal - How to set value of file field with entity_metadata_wrapper

Well I just found out a simpler and less ugly looking way to set image.

$image_file = A FILE OBJECT; //Lot of choices here : new stdClass(), file_load, etc
$wrapper->FIELD_NAME->file->set($image_file);

Just as taxonomy or node/entity reference, the file field name point on a loaded object, thats how I find out.


:: EDIT a posteriori ::

Here how I would have do it with OP question.

// Get the file
$file = file_save_data(file_get_contents('/my_local_path/img1.jpg'), 'public://remote_name.jpg');

// Wrap' it like one of your French girls
$wrapper = entity_metadata_wrapper('node', $node);

// And set the photo
$wrapper->field_photo->file->set($file);

// And save the node
$wrapper->save();

Wrapping the file array in another array seems to do the trick for me:

$file = (array) $file;
$items = array($file);
$ewrapper->field_document->set($items);

But I haven't found out why yet...


My node already existed and I had to set the following parameters:

$wrapper->field_pdf->set(array('fid'=>$fid, 'display'=>1, 'description'=>'This is a PDF'));

Different set-ups may require different parameters I suppose. If you look in your error logs (admin/reports/dblog) you can see what parameters are needed.

Tags:

Entities

Files

7