如何在drupal8中以编程方式更新或创建段落字段

时间:2018-01-18 12:47:22

标签: drupal-8 drupal-entities

下面是我的解决方案,其中有一个示例,可能会对您有所帮助。

Update existing field
$target_id = 62;
$paragraph = Paragraph::load($target_id);
$typeform_field = $paragraph->field_archtics_field->value;
$archtics_field = $paragraph->field_archtics_label->value;
$paragraph->set('field_fieldname1', 'TEST1');          
$paragraph->set('field_fieldname2', 'TEST2');          
$paragraph->save();

//创建字段并在节点中附加可以在这里找到。     https://www.drupal.org/project/paragraphs/issues/2707017

Thanks

2 个答案:

答案 0 :(得分:6)

代码中的注释应该解释所有内容:

<?php

use Drupal\paragraphs\Entity\Paragraph;

// Create single new paragraph
$paragraph = Paragraph::create([
  'type' => 'paragraph_machine_name',
  'field_machine_name' => 'Field value',
]);
$paragraph->save();

// Create multiple new paragraphs
$multiParagraph1 = Paragraph::create([
  'type' => 'paragraph_machine_name',
  'field_machine_name' => 'Field value',
]);
$multiParagraph2 = Paragraph::create([
  'type' => 'paragraph_machine_name',
  'field_machine_name' => 'Field value',
]);
$multiParagraph1->save();
$multiParagraph2->save();


// Save paragraph to node it belongs to
$newCompanyNode = Node::create([
  'type' => 'node_machine_name',
  'title' => 'new_node_title',
  // Insert a single paragraph
  'node_field_paragraph_machine_name' => array(
    'target_id' => $paragraph->id(),
    'target_revision_id' => $paragraph->getRevisionId(),
  ),
  // Insert multiple paragraphs into the same reference field
  'node_paragraph_field_machine_name' => array(
    array(
      'target_id' => $multiParagraph1->id(),
      'target_revision_id' => $multiParagraph1->getRevisionId(),
    ),
    array(
      'target_id' => $multiParagraph2->id(),
      'target_revision_id' => $multiParagraph2->getRevisionId(),
    ),
  ),
]);

// Makes sure this creates a new node
$newCompanyNode->enforceIsNew();
// Saves the node
// Can also be used without enforceIsNew() which will update the node if a $newCompanyNode->id() already exists
$newCompanyNode->save();

答案 1 :(得分:0)

以下是更新现有段落项目的示例(使用所需的值填写$ nid和$ paragraph_field):

$entity = \Drupal::entityTypeManager()->getStorage('node')->load($nid);
$result = $entity->get($paragraph_field)->referencedEntities();
if (!empty($result)) {
  foreach ($result as $paragraph) {
    $paragraph->set('field_fieldname1', 'some value');
    $paragraph->save();
  }
}
相关问题