不能设置field_collection
中的file_field
节点$order和field_collection被称为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);
,这段代码抛出错误:
EntityMetadataWrapperException:给出的数据值无效。确保它匹配所需的数据类型和格式。在
EntityDrupalWrapper->set()
中(sites//all/modules/entity/includes/entity.wrapper.inc的第736行)
我也试过了:
$blueprint_entity->field_blueprint_file->set((array)$file)
$blueprint_entity->field_blueprint_file->set(array('fid'=>$file->fid))
您需要传递文件对象或具有fid
键的数组以使其工作
所以要么是
// Single value field
$blueprint_entity->field_blueprint_file = array('fid' => $file->fid);
// Multi-value field
$blueprint_entity->field_blueprint_file[] = array('fid' => $file->fid);
或:
// Single value field
$blueprint_entity->field_blueprint_file = $file;
// Multi-value field
$blueprint_entity->field_blueprint_file[] = $file;
下面是使用value()
, set()
和save()
从实体元数据包装页面的完整示例:
<?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();
?>
同样,当处理多值字段(基数> 1)时,确保将其包装到额外的数组中。