0

I've been spending a couple of hours from debugging the paragraph properties using kint and var_dumper however, the page is freezing and I'm unable to see what are the properties and methods available. Has anyone tried to add a hook theme suggestion to paragraph based on its parent field name?

I have added a paragraph type as well as added the fields, then I created a node and paragraph reference.

Here's a sample code:-

function THEMENAME_theme_suggestions_paragraph_alter(&$suggestions, $variables) {
    $paragraph = $variables['elements']['#paragraph'];
    $parent = $paragraph->getParentEntity();

    $suggestions[] = 'paragraph__' . $parent->bundle() . '__' .  $paragraph->bundle();

    // get the parent field of the current paragraph
    // assuming that the parent field name is field_test_paragraph
    $parent_field_name = 'field_test_paragraph';

    // field_test_paragraph should be added to theme suggestions
    $suggestions[] = 'paragraph__' . $parent->bundle() . __ . $parent_field_name . '__' .  $paragraph->bundle();
}

Expected output:

paragraph--nodetype--field-test-paragraph--paragraph-type-name.html.twig
1

You can get the parent field name directly from the paragraph:

Replace

// get the parent field of the current paragraph
// assuming that the parent field name is field_test_paragraph
$parent_field_name = 'field_test_paragraph';

with

$parent_field_name = $paragraph->parent_field_name->value;

As a side note, this is an entity base field like parent_id and parent_type you load the parent entity with in getParentEntity().

  • I'm getting a NULL value when debugging $paragraph->getParentEntity()->parent_field_name – Catherine Salvador Sep 25 '18 at 9:36
  • This would get the field name in the grandparent, if the paragraphs were nested. Which is obviously not the case here when the result is NULL. – 4k4 Sep 25 '18 at 9:45
  • yes it's nested. I've tried to use dump and there's a protected property named values, the parent field name is in there, just not sure if it's possible to get that otherwise I might just query on the db just to get the parent field name. though I'm trying not to – Catherine Salvador Sep 25 '18 at 9:53
  • I think the code in your question needs only the one line to work. I've edited the answer to make things more clear. If you have nested paragraphs with multiple levels and want to get the parent field in the node you have to iterate until you find a non paragraph entity. – 4k4 Sep 25 '18 at 10:00
  • In the code line I was missing ->value to get the parent field name, see the latest edit. Now it should work. – 4k4 Sep 25 '18 at 11:23

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.