How to update or create paragraph fields programatically in drupal8

Debraj nayak picture Debraj nayak · Jan 18, 2018 · Viewed 7.9k times · Source

Below is my solution with an example, that may help you.

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

//Create field and attached in node can be find here. https://www.drupal.org/project/paragraphs/issues/2707017

Thanks

Answer

user6742604 picture user6742604 · Jan 23, 2018

Comments in the code should explain everything:

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