You are here

function paragraphs_grid_entity_view_mode_alter in Paragraphs grid 8

Implements hook_entity_view_mode_alter().

If entity is a paragraph, ... find grid_field_type field, ... get the field value for view mode ... and finally => change the view mode of the paragraphs entity.

File

./paragraphs_grid.module, line 153
Contains paragraphs_grid.module.

Code

function paragraphs_grid_entity_view_mode_alter(&$view_mode, EntityInterface $entity, $context) {
  if ($entity
    ->getEntityTypeId() == 'paragraph' && $view_mode != 'preview') {

    /** @var \Drupal\paragraphs\Entity\Paragraph $entity */

    // Find grid_field_type field, get set view mode and change the view mode.
    $fields = \Drupal::service('entity_field.manager')
      ->getFieldDefinitions($entity
      ->getEntityTypeId(), $entity
      ->bundle());
    foreach ($fields as $field_name => $field) {
      if ($field
        ->getType() == 'grid_field_type' && ($field_value = $entity
        ->get($field_name)
        ->getValue())) {
        $field_value = reset($field_value);
        $view_mode = $field_value['view_mode'] ?: $view_mode;
        break;
      }
    }
  }
}