7

I've written a paragraph preprocess function that is working perfectly. The only issue is that I need it to only work when that paragraph is embedded in a certain content type.

function mytheme_preprocess_paragraph__paragraph_type(&$variables) {
   // Do things here if content type == 'specified_type'
}

I'm unsure of how to check the content type, though. How can I accomplish this?

0

2 Answers 2

16

The correct way of getting the entity data referencing to your paragraph is to use Paragraph's entity API.

/**
 * Implements template_preprocess_paragraph().
 *
 * @param array $variables
 *   An associative array containing:
 *   - elements: An array of elements to display in view mode.
 *   - paragraph: The paragraph object.
 *   - view_mode: View mode; e.g., 'full', 'teaser'...
 */

function mytheme_preprocess_paragraph(&$variables) {
  /** @var \Drupal\paragraphs\Entity\Paragraph $paragraph */
  $paragraph = $variables['paragraph'];
  // Get the parent bundle.
  $parentBundle = $paragraph->getParentEntity()->bundle();
}
-1

There is another post with either the same or similar answer here. https://stackoverflow.com/questions/31116325/how-to-programmatically-get-content-type-name-in-drupal-8

The poster Jose points out you can use

$node = \Drupal::request()->attributes->get('node');

to get the content type.

1
  • That question is not about the Paragraph module and the entity it implements. It is also probable the code shown there needs to be updated for the latest Drupal versions.
    – apaderno
    Nov 3, 2017 at 22:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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