How to Get, Add or Update Paragraph fields values from Config Pages Entity Programmatically

How to Get, Add or Update Paragraph fields values from Config Pages Entity Programmatically

Introduction

I often use Config Pages module for my projects. I find it very useful in quickly building custom configuration pages to store all my settings just in one place.
The creation process is similar to content type set up. After that you have your entity page with fields, which can be accessed or updated by other custom modules.

When it comes to have a single or multiple reference fields on the Config Page, that would link to other sets of fields, the Paragraphs module is here to help.

The Paragraphs module creates its own entity type with manageble fields and it can be added to the config page entity as the reference revision field:

Adding Paragraphs types field to the Config Pages entity.
Adding Paragraphs types field to the Config Pages entity.

Access Config Pages entity fields

There are two ways to load Config page entity within custom module:

$entity = ConfigPages::config($config_page_machine_name);

The second way is to get a config page via storage manager:

$storage = \Drupal::entityTypeManager()->getStorage('config_pages');
$entity = $storage->load($config_page_machine_name);

As a result, you will get a loaded config pages entity. To get values from fields, for example:

$entity->get('field_something')->value;

The entire data from the all fields values can be accessed with toArray() method:

$entity->toArray();

Load the Paragraph fields from the Config Pages Entity

The Paragraph field is a reference field, so it will contain only target_id and target_revision_id values to corresponding paragraph type.

Paragraphs field raw data.
Paragraphs field raw data.


In this case, the Paragraph entities and its fields may be accessed with the referencedEntities() method.

For instance, if we have a multiple Paragraph fields:

use Drupal\paragraphs\Entity\Paragraph;

function getParagraphField($entity, $paragraph_field) {
  $data = [];
  // Do some checks.

  $result = $entity->get($paragraph_field)->referencedEntities();
  foreach ($result as $item) {
    if ($item instanceof Paragraph) {
      $data[] = [
        // Referenced Term ID
        'term_id' => $item->get('field_some_term')
          ->first()->getValue()['target_id'],
        // Regular Text Field
        'field2' => $item->get('field_some_name')->value,
      ];
    }
  }
  
  return $data;
}

Add the Paragraph fields data the Config Pages Entity

The code comments should explain everything.

  $storage = \Drupal::entityTypeManager()->getStorage('config_pages');
  $entity = $storage->load($config_page_machine_name);

  // Create the Paragraph with fields.
  $paragraph = Paragraph::create(['type' => $paragraph_type,]);
  $paragraph->set('field_some_name', $value);
  $paragraph->set('field_some_other_name', $value2);
  $paragraph->isNew();
  $paragraph->save();

  // Then attach a new Paragraph to the Config page entity.
  $paragraph_items[] = [
    'target_id' => $paragraph->id(),
    'target_revision_id' => $paragraph->getRevisionId(),
  ];
  $entity->set($field_name, $paragraph_items);
  // Save the entire entity.
  $entity->save();

Update existing Paragraph field at the Config Pages Entity

Load the Paragraph object by using its target_id taken from the corresponding reference field:

  $paragraph = Paragraph::load($target_id);
  $paragraph_field_value = $paragraph->get('field_some_name')->value;
  // Do something with the $paragraph_field_value
  // Update the field.
  $paragraph->set('field_some_name', $paragraph_field_value);
  // Save the Paragraph.
  $paragraph→save();

Another example of updating multiple Paragraph type fields at the Config Pages Entity:

  $storage = \Drupal::entityTypeManager()->getStorage('config_pages');
  $entity = $storage->load('config_page_machine_name');
  $result = $entity->get($paragraph_field)->referencedEntities();
  if (!empty($result)) {
    foreach ($result as $paragraph) {
      if ($paragraph instanceof Paragraph) {
        $paragraph_field_value = $paragraph->get('field_some_name')->value;
        // Do something with the $paragraph_field_value.
        // Update the field.
        $paragraph->set('field_some_name', $paragraph_field_value);
        $paragraph->save();
      }
    }
  }

Delete Paragraph

You can delete paragraph items with the entity storage manager.
Delete single paragraph entity:

  $entity = \Drupal::entityTypeManager()->getStorage('paragraph')->load($paragraph_id);
  $entity->delete();

Delete multiple paragraphs by certain type:

  $storage_handler = \Drupal::entityTypeManager()->getStorage('paragraph');
  $entities = $storage_handler->loadByProperties(['type' => 'paragraph_type_name']);
  $storage_handler->delete($entities);

Conclusion

In this article I provided a few simple code examples on creation and updating Paragraph items at the Config Pages within custom modules in Drupal 8. 

Comments

Submitted by Vinodkumar on Sat, 07/13/2019 - 13:16

Hi really nice one. Could you please tell me how to update paragraph field in the node save? I have option to add multiple paragraph types in the node as entity reference and each paragraph has option to add unlimited times.

In all types, there is common two fields. I need to update one field value in all types

How could i update field in all the places?

Submitted by whitebox on Tue, 02/04/2020 - 08:02

Hey amazing article.

Add new comment

CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.