Skip to content
Snippets Groups Projects
Select Git revision
  • 2.x
  • master
  • 8.x-1.x
  • 8.x-dev
  • 2.0.1
  • 2.0.0
  • 8.x-1.1
  • 8.x-1.x
  • 8.x-1.0
9 results

ImagePopup.php

  • Code owners
    Assign users and groups as approvers for specific file changes. Learn more.
    ImagePopup.php 1.60 KiB
    <?php
    
    namespace Drupal\image_popup\Controller;
    
    use Drupal\Component\Serialization\Json;
    use Drupal\Core\Ajax\AjaxResponse;
    use Drupal\Core\Ajax\OpenModalDialogCommand;
    use Drupal\Core\Controller\ControllerBase;
    use Drupal\image\Entity\ImageStyle;
    use Drupal\Core\Url;
    use Symfony\Component\HttpFoundation\Request;
    
    /**
     * Class ImagePopup.
     *
     * @package Drupal\image_popup\Controller
     */
    class ImagePopup extends ControllerBase {
    
      /**
       * Render.
       *
       * @return \Drupal\Core\Ajax\AjaxResponse
       *   The ajax response containing the modal.
       */
      public function render($fid, Request $request, $image_style = NULL) {
        $file = $this->entityTypeManager()->getStorage('file')->load($fid);
    
        if (!empty($image_style)) {
          $image_style = ImageStyle::load($image_style);
        }
        $image_uri = $file->getFileUri();
    
        if (!empty($image_style)) {
          $absolute_path = ImageStyle::load($image_style->getName())->buildUrl($image_uri);
        }
        else {
          // Get absolute path for original image.
          $absolute_path = Url::fromUri(\Drupal::service('file_url_generator')->generateAbsoluteString($image_uri))->getUri();
        }
    
        $response = new AjaxResponse();
    
        $title = $request->query->get('title');
    
        // Build a render array for the modal content.
        $content = [
          '#theme' => 'image',
          '#uri' => $absolute_path,
          '#alt' => $request->query->get('alt'),
        ];
    
        // Get the modal options from the query.
        $options = Json::decode($request->query->get('modal-options')) ?: [];
        $response->addCommand(new OpenModalDialogCommand($title, $content, $options));
        return $response;
      }
    
    }