nortmas
9/27/2017 - 3:54 PM

Paragraph get image

/**
   * Generates html with image
   *
   * @param $teaser_image - image field entity got from getLcvCarTeaserImage
   * @return string - html
   */
  public function getLcvCarTeaserRenderedImage($teaser_image) {

    if ($teaser_image && is_object($teaser_image)) {
      $image_variables = array(
        'responsive_image_style_id' => 'header_image',
        'uri' => $teaser_image->getFileUri(),
      );
      // The image.factory service will check if our image is valid.
      $image = \Drupal::service('image.factory')
        ->get($teaser_image->getFileUri());
      if ($image->isValid()) {
        $image_variables['width'] = $image->getWidth();
        $image_variables['height'] = $image->getHeight();
      }
      else {
        $image_variables['width'] = $image_variables['height'] = NULL;
      }
      $image = [
        '#theme' => 'responsive_image',
        '#width' => $image_variables['width'],
        '#height' => $image_variables['height'],
        '#responsive_image_style_id' => 'content__default',
        '#uri' => $image_variables['uri'],
      ];
      $image = render($image);
    }

    return isset($image) ? $image : '';
  }
/**
   * Helper function to return lcv car teaser image entity or false if none.
   *
   * @param $entity
   */
  public function getLcvCarTeaserImageFromParagraph(NodeInterface $node) {

    $first_image = FALSE;

    // Get first image_gallery paragraph in field_lcv_car_description.
    $description_paragraphs = $node->get('field_lcv_car_description');

    foreach ($description_paragraphs as $key => $item) {
      $paragraph = $item->entity;
      if ($paragraph->bundle() == 'image_gallery') {
        $gallery_slides = $paragraph->get('field_pg_ig_slides');
        foreach ($gallery_slides as $gallery_slide) {
          $gallery_slide_entity = $gallery_slide->entity;
          $first_image = $gallery_slide_entity->get('field_pg_ig_slide_image')->entity;
          break;
        }
        break;
      }
    }

    return $first_image;
  }