12

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
)
13

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

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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