如何获取段落字段值?


12

我想在drupal中创建产品列表,然后通过网络服务发送。为此,我为每个产品创建了一个带有段落的实体类型。如何加载段落并访问其字段?到目前为止,我只看到产品的target_id和target_revision_id。谢谢!

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

结果:

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

Answers:


13

您应该能够包含Paragraph实体类,并用于Paragraph::load($entity_id)加载它。

例:

use Drupal\paragraphs\Entity\Paragraph;

$paragraph = Paragraph::load($target_id);
$foo = $paragraph->field_name->value;

10
$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

我知道这很古老,但可能对将来有所帮助。要加载由Node实体引用的实体,您可以使用entity属性。例如,考虑以下代码:

$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;
}

因此,无需通过实体ID加载实体,您只需->entity在引用的实体列表上添加用户属性即可。

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.