【问题标题】:How to create Field Collection Item by code in Drupal 8如何在 Drupal 8 中通过代码创建字段集合项
【发布时间】:2016-05-01 10:30:16
【问题描述】:

如何在 Drupal 8 中按程序为节点创建字段集合项。我尝试使用以下代码,但它不起作用。 “field_abc_inside”是字段集合“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();

【问题讨论】:

  • 自己在“8.x-1.0-alpha1”版本上找到了答案。 $entity = FieldCollectionItem::create(['field_name' => 'field_abc']); $entity->field_abc_inside->setValue('测试数据'); $entity->setHostEntity($node); $entity->save();

标签: drupal drupal-8


【解决方案1】:
$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);

【讨论】:

  • 请为您的答案添加一些解释。不鼓励仅使用代码回答。
【解决方案2】:

该代码帮助了我,但我有一个观察结果。

\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();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多