In Drupal 10, Paragraphs are widely used to group multiple fields together as reusable entities. For example, you might have a “Team Member” paragraph containing Name, Role, and Photo fields.
This guide will show you how to programmatically access paragraph field values attached to nodes, in a simple way even beginners can understand.
Step 1: Load the Node
Before accessing paragraphs, you need to load the node:
use Drupal\node\Entity\Node;
$nid = 1; // Replace with your node ID
$node = Node::load($nid);
if (!$node) {
\Drupal::logger('custom_module')->error('Node not found.');
return;
}
Step 2: Load Paragraphs from Node Field
Suppose your node has a paragraph field called field_team_members:
$paragraphs = $node->get('field_team_members')->referencedEntities();
foreach ($paragraphs as $paragraph) {
$name = $paragraph->get('field_name')->value;
$role = $paragraph->get('field_role')->value;
\Drupal::logger('custom_module')->info('Name: @name, Role: @role', [
'@name' => $name,
'@role' => $role,
]);
}
Explanation:
get('field_team_members')
→ retrieves the paragraph field attached to the node.referencedEntities()
→ loads all paragraph entities attached to the node.- You can then loop through each paragraph and access its fields.
Step 3: Using in a Custom Module
You can use this code in a custom block or controller to display paragraph values:
namespace Drupal\custom_module\Controller;
use Drupal\Core\Controller\ControllerBase;
use Drupal\node\Entity\Node;
class ParagraphController extends ControllerBase {
public function display($nid) {
$node = Node::load($nid);
$output = [];
if ($node) {
$paragraphs = $node->get('field_team_members')->referencedEntities();
foreach ($paragraphs as $paragraph) {
$output[] = [
'name' => $paragraph->get('field_name')->value,
'role' => $paragraph->get('field_role')->value,
];
}
}
return [
'#theme' => 'item_list',
'#items' => $output,
];
}
}
This will render a list of paragraph field values for a node.
Tips
- Always check if the node exists (
Node::load($nid)
). - Use
referencedEntities()
to avoid manually loading paragraph IDs. - Paragraph fields can have multiple items, so always loop through them.
- This method works for any type of paragraph field, including text, images, and custom fields.
Conclusion
Accessing paragraph field values in Drupal 10 is straightforward:
- Load the node.
- Get the paragraph field.
- Loop through each paragraph and access its fields.
By following this guide, beginners can easily work with paragraphs programmatically in Drupal 10.