使用嵌套字段集合项Drupal 7以编程方式创建节点

时间:2015-01-08 18:35:31

标签: drupal-7

我需要以编程方式创建节点。在我的内容类型中,有一个字段集合,其中有另一个字段集合。现在我如何在内部字段集合中保存字段的值因此,由于此嵌套字段集合结构,我无法在此节点中保存字段集合项目。

以下是我的代码:

global $user;
$node = entity_create('node', array('type' => 'key_sentence')); // replace entity_type and entity_bundle with your info
// Specify the author
$node->uid = $user->uid;
// Create a Entity Wrapper of that new Entity
$entity = entity_metadata_wrapper('node', $node);

// Specify the title
$entity->title = 'Test node';
// Add field data... SO MUCH BETTER!
$entity->field_key_sentence_text = 'Field value text';

$entity->save(); // necessary in order to attach field collections

//Outer field collection
$field_collection_1 = entity_create('field_collection_item', array('field_name' => 'field_ks_sent_to'));
// Set default values as necessary
$field_collection_1->setHostEntity('field_collection_item', $entity); // again, replace entity_type as appropriate
$field_collection_1->save(TRUE);

//Inner field collection
$field_collection_2 = entity_create('field_collection_item', array('field_name' => 'field_ks_in_voice'));
// Set default values as necessary
$field_collection_2->setHostEntity('field_collection_item', $field_collection_1);

//Field in inner field collection
$field_collection_2->field_message_url[LANGUAGE_NONE][0]['value'] = 'http://www.google.com';
$field_collection_2->save(TRUE);

$entity->save();

但是我收到了这些错误:

Notice: Undefined index: value in field_collection_field_update() (line 933 of /home/postcinn/public_html/dev/sites/all/modules/field_collection/field_collection.module).
EntityMalformedException: Missing bundle property on entity of type field_collection_item. in entity_extract_ids() (line 7766 of /home/postcinn/public_html/dev/includes/common.inc).

1 个答案:

答案 0 :(得分:-1)

//Outer field collection
$field_collection_1 = entity_create('field_collection_item', array('field_name' => 'field_ks_sent_to'));
// Set default values as necessary
$field_collection_1->setHostEntity('field_collection_item', $entity); // again, replace entity_type as appropriate
$field_collection_1->save(TRUE);

我想初学者需要确保第一级字段集合的主机实体node类型不是field_collection_item