You are here

classy_paragraphs.module in Classy paragraphs 8

Same filename and directory in other branches
  1. 7 classy_paragraphs.module

File

classy_paragraphs.module
View source
<?php

/**
 * @file
 * Contains classy_paragraphs.module.
 */
use Drupal\field\FieldConfigInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\Display\EntityViewDisplayInterface;
use Drupal\Core\Routing\RouteMatchInterface;

/**
 * Implements hook_help().
 */
function classy_paragraphs_help($route_name, RouteMatchInterface $route_match) {
  switch ($route_name) {
    case 'help.page.classy_paragraphs':
      $text = file_get_contents(dirname(__FILE__) . '/README.md');
      if (!\Drupal::moduleHandler()
        ->moduleExists('markdown')) {
        return '<pre>' . $text . '</pre>';
      }
      else {

        // Use the Markdown filter to render the README.
        $filter_manager = \Drupal::service('plugin.manager.filter');
        $settings = \Drupal::configFactory()
          ->get('markdown.settings')
          ->getRawData();
        $config = [
          'settings' => $settings,
        ];
        $filter = $filter_manager
          ->createInstance('markdown', $config);
        return $filter
          ->process($text, 'en');
      }
  }
  return NULL;
}

/**
 * Implements hook_entity_view_alter().
 */
function classy_paragraphs_entity_view_alter(array &$build, EntityInterface $entity, EntityViewDisplayInterface $display) {

  // Find fields which are referencing classy_paragraphs.
  $class_fields = [];
  $fields = $entity
    ->getFieldDefinitions();
  foreach ($fields as $field) {
    if ($field instanceof FieldConfigInterface) {

      /** @var Drupal\field\Entity\FieldStorageConfig $field_storage */
      $field_storage = $field
        ->getFieldStorageDefinition();
      $target = $field_storage
        ->getSetting('target_type');
      if ($target == 'classy_paragraphs_style') {
        $class_fields[] = $field;
      }
    }
  }
  foreach ($class_fields as $class_field) {
    $field_name = $class_field
      ->get('field_name');
    if (!$entity
      ->get($field_name)
      ->isEmpty()) {
      $field = $entity
        ->get($field_name);
      $classes = $field
        ->referencedEntities();
      foreach ($classes as $class) {
        $raw_classes = $class
          ->getClasses();
        $array_classes = explode("\r\n", $raw_classes);
        if (!empty($array_classes)) {
          if (!empty($build['#attributes']['class'])) {
            $current_classes = $build['#attributes']['class'];
            $build['#attributes']['class'] = array_merge($current_classes, $array_classes);
          }
          else {
            $build['#attributes']['class'] = $array_classes;
          }
        }
      }
    }
  }
}