1

Cannot set file_field in field_collection Has node $order and field_collection called field_blueprints:

<?php
$entity_type = "field_collection_item";
$blueprint_obj = entity_create($entity_type, array('field_name' => "field_blueprints") );
$blueprint_obj->setHostEntity('node', $order);
$blueprint_entity = entity_metadata_wrapper($entity_type, $blueprint_obj);
date_default_timezone_set("UTC");
$blueprint_entity->field_blueprint_file->file->set((array)$file);
$blueprint_entity->field_blueprint_comment = (string) $file->filename;
$blueprint_obj->save();
node_save($order);

And this code throws error:

EntityMetadataWrapperException: Invalid data value given. Be sure it matches the required data type and format. in EntityDrupalWrapper->set() (line 736 of sites//all/modules/entity/includes/entity.wrapper.inc).

I have also tried:

$blueprint_entity->field_blueprint_file->set((array)$file)
$blueprint_entity->field_blueprint_file->set(array('fid'=>$file->fid))
kenorb
  • 155,785
  • 88
  • 678
  • 743
alekssaff
  • 167
  • 2
  • 10

1 Answers1

0

You need to either pass the file object or an array with a fid key to make it work.

So it's either:

// Single value field
$blueprint_entity->field_blueprint_file = array('fid' => $file->fid);
// Multi-value field
$blueprint_entity->field_blueprint_file[] = array('fid' => $file->fid);

or:

// Single value field
$blueprint_entity->field_blueprint_file = $file;
// Multi-value field
$blueprint_entity->field_blueprint_file[] = $file;

Here is complete example using value(), set() and save() from Entity metadata wrappers page:

<?php
  $containing_node = node_load($nid);
  $w_containing_node = entity_metadata_wrapper('node', $containing_node);

  // Load the file object in any way
  $file_obj = file_load($fid);
  $w_containing_node->field_attachment_content->file->set( $file_obj );
  // ..or pass an array with the fid
  $w_containing_node->field_attachment_content->set( array('fid' => $fid) );
  $w_containing_node->save();
?>

Also when dealing with multiple-valued field (cardinality > 1), make sure you wrap it into extra array.

featherbelly
  • 935
  • 11
  • 16
kenorb
  • 155,785
  • 88
  • 678
  • 743
  • Shouldn't this be an improvement of my answer, which came like a year before? – ram4nd Apr 10 '17 at 07:55
  • @ram4nd It wouldn't be the improvement, but change, since you're suggesting `set()` method, and my first 2 examples aren't using it, but assigning the array directly. – kenorb Apr 10 '17 at 12:08
  • The complete example sure is using wrapper. Entity object is missing some array layers like language and count. So the first answer is not working, full answer is using set() and wrapper is the way to go (it's also used in the question). My milk stool is complete. – ram4nd Apr 10 '17 at 14:53