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))
4

1 回答 1

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.

于 2016-03-15T00:04:45.990 回答