如何在Drupal 8中按代码创建Field Collection Item

时间:2016-05-01 10:30:16

标签: drupal drupal-8

如何在Drupal 8中按程序为节点创建Field Collection项。我尝试使用下面的代码,但它不起作用。 ' field_abc_inside'是Field Collection&field 39. field_abc'。

的领域
$field_collection_item = entity_create('field_collection_item', array(
            'field_name' => 'field_abc',
            'field_abc_inside' => array('value'=> 'Test data'),
        )); 
$field_collection_item->setHostEntity($node);
$field_collection_item->save();

2 个答案:

答案 0 :(得分:0)

$user_id = \Drupal::currentUser()->getAccount()->id();
$user = User::load($user_id);

$fc = FieldCollectionItem::create(array(
     "field_name" => "field_hobbies",
));

$fc->set('field_hobby_name', 'Watch TV');
$fc->setHostEntity($user);

答案 1 :(得分:0)

那个代码对我有帮助,但我有一个观察。

\Drupal::currentUser() 是用户对象,这很清楚,因为它使用它来检索 id()。 因此不需要在第 2 行再次使用 User::load(),冗余处理会导致函数运行时间更长。

// Get the current user object
$user = \Drupal::currentUser();

// Prepare the new Field Collection Item object
$fc = FieldCollectionItem::create(array(
     "field_name" => "field_hobbies",
));

// Sets more field values
$fc->set('field_hobby_name', 'Watch TV');
// Sets the host record; where the field collection will be attached into
$fc->setHostEntity($user);
// Saves it into an actual field collection record
$fc->save();