Skip to content

Instantly share code, notes, and snippets.

@megclaypool
Last active April 4, 2025 18:56

Ok, so

  • $thingie is your node, or paragraph, or whatever. You're probably writing this code in your thingie's preprocess hook
  • field_paragraph is a paragraph field whose inner data you want to plunder
  • desired_field is the actual field inside the paragraph whose data you need
// First, check that the field exists and isn't empty
if ($thingie->hasField('field_paragraph') && !$thingie->field_paragraph->isEmpty()) {
  
  // In this case, this is a single value field. Otherwise you might need to set up a loop or call a specific entry
  $paragraph_field = $thingie->get('field_paragraph')->first();

  // Here we're checking that the paragraph field is not empty and that it is a paragraph entity.
  if ($paragraph_field && ($paragraph_entity = $call_to_action_field->entity) && $paragraph_entity instanceof \Drupal\paragraphs\ParagraphInterface) {
    
    // Check if the nested paragraph has the desired field.
    if ($paragraph_entity->hasField('desired_field') && !$paragraph_entity->get('desired_field')->isEmpty()) {
      // mess with the field
      $variables[desired_field] = some data you wanted to pass back to twig
    }
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment