16

I'd like to create a product list in drupal and send it in a webservice. For this I created an entity type with paragraphs for each product. How can I load the paragraph and access its fields? Until now I see only the target_id and target_revision_id of the product. Thanks!

$nodestorage = \Drupal::entityManager()->getStorage('node');
$productslist = $nodestorage->loadUnchanged(9)->toArray();
foreach($productslist['field_products'] as $prod) {
  debug($prod);
}

Result:

Array
(
  [target_id] => 1
  [target_revision_id] => 3
)

4 Answers 4

17

You should be able to include the Paragraph entity class, and use Paragraph::load($entity_id) to load it.

Example:

use Drupal\paragraphs\Entity\Paragraph;

$paragraph = Paragraph::load($target_id);
$foo = $paragraph->field_name->value;
1
  • The following change worked for me: $foo = $paragraph->field_name->getValue();
    – Gugols
    Commented Oct 6, 2020 at 11:45
11
$paragraph = Paragraph::load($target_id);
// Paragraph type could be also useful.
$prgTypeId = $paragraph->getType();
/** @var \Drupal\Core\Field\EntityReferenceFieldItemList $prgMediaField */
$prgMediaField = $paragraph->get('field_media');
$prgMediaFieldValue = $prgMediaField->getValue();
10

I know this is old, but might be helpful for the future. To load entities referenced by a Node entity you can use the entity property. For example, consider the following code:

$nodestorage = \Drupal::entityManager()->getStorage('node');
$node = $nodestorage->loadUnchanged(9);

foreach ($node->field_products as $product) {

  /** @var Entity (i.e. Node, Paragraph, Term) $referenced_product **/
  $referenced_product = $product->entity;

  // Use now the entity to get the values you need.
  $field_value = $referenced_product->field_name->value;
}

So no need to load an entity by the entity id, you just simply user ->entity property over a referenced list of entities.

3
  • Good, but This will get you only one entity per field!
    – Dalmaz
    Commented Jun 27, 2020 at 18:44
  • 1
    No, that's not correct, @Dalmaz, that loop will generate every item contained in field_products. Commented Feb 2, 2021 at 12:16
  • you're right @Adaddinsane
    – Dalmaz
    Commented Nov 30, 2023 at 23:53
1

The quickest way is to use referencedEntities():

$nodestorage = \Drupal::entityManager()->getStorage('node');
$node = $nodestorage->loadUnchanged(9);
$products_list = $node->{'field_products'}->referencedEntities();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.