jfu-1.0.x-dev/src/Form/JfuImageDialog.php

src/Form/JfuImageDialog.php
<?php

namespace Drupal\jfu\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\HtmlCommand;
use Drupal\jfu\Ajax\JfuDialogSave;
use Drupal\Core\Ajax\CloseModalDialogCommand;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Entity\EntityStorageInterface;
use Drupal\Core\Entity\EntityDisplayRepository;
use Drupal\Component\Utility\Environment;
use Drupal\Component\Utility\Bytes;
use Drupal\Core\Config\ConfigFactory;
use Drupal\Core\Image\ImageFactory;
use Drupal\jfu\Services\JfuConfigServices;

/**
 * Provides an image dialog for json field utils.
 *
 * @internal
 */
class JfuImageDialog extends FormBase {

  /**
   * The file storage service.
   *
   * @var \Drupal\Core\Entity\EntityStorageInterface
   */
  protected $fileStorage;

  /**
   * The entity display repository service.
   *
   * @var \Drupal\Core\Entity\EntityDisplayRepository
   */
  protected $entityDisplayRepository;

  /**
   * The entity Config Factory.
   *
   * @var Drupal\Core\Config\ConfigFactory
   */
  protected $configFactory;

  /**
   * The image factory.
   *
   * @var \Drupal\Core\Image\ImageFactory
   */
  protected $imageFactory;

  /**
   * The Jfu config.
   *
   * @var Drupal\jfu\Ajax\JfuDialogSave
   */
  protected $jfuConfig;


  /**
   * Constructs a form object for image dialog.
   *
   * @param \Drupal\Core\Entity\EntityStorageInterface $file_storage
   *   The file storage service.
   * @param \Drupal\Core\Image\ImageFactory $image_factory
   *   The image factory.
   */
  public function __construct(EntityStorageInterface $file_storage, EntityDisplayRepository $entity_display_repository, ConfigFactory $config_factory, ImageFactory $image_factory, JfuConfigServices $jfu_config) {
    $this->fileStorage = $file_storage;
    $this->entityDisplayRepository = $entity_display_repository;
    $this->configFactory = $config_factory;
    $this->imageFactory = $image_factory;
    $this->jfuConfig = $jfu_config;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('entity_type.manager')->getStorage('file'),
      $container->get('entity_display.repository'),
      $container->get('config.factory'),
      $container->get('image.factory'),
      $container->get('jfu_config.service')
    );
  }

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'jfu_image_dialog';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $attributes = $this->getRequest()->attributes->all();
    $query = $this->getRequest()->query->all();
    $entity_type = $attributes['entity_type'];
    $bundle = $attributes['bundle'];
    $field_name = $query['field_name'];
    $component = $query['component'];
    $config_name = $this->jfuConfig->jfuConfigName($entity_type, $bundle, $field_name);
    $config = $this->configFactory->getEditable($config_name);
    if (isset($query['index']) && $query['index'] != '') {
      $form['image_index'] = [
        '#type' => 'hidden',
        '#value' => $query['index'],
      ];
    }
    if (isset($query['subindex']) && $query['subindex'] != '') {
      $form['image_subindex'] = [
        '#type' => 'hidden',
        '#value' => $query['subindex'],
      ];
    }
    if (isset($query['subindexitem']) && $query['subindexitem'] != '') {
      $form['image_subindexitem'] = [
        '#type' => 'hidden',
        '#value' => $query['subindexitem'],
      ];
    }

    $image_settings = $config->get('components_config')[$component];
    $form['#prefix'] = '<div id="jfu-image-dialog-form">';
    $form['#suffix'] = '</div>';

    $max_dimensions = 0;
    if ($query['subindexitem'] == 'responsive_image') {
      if (!empty($image_settings['max_dimensions_responsive']['width']) || !empty($image_settings['max_dimensions_responsive']['height'])) {
        $max_dimensions = $image_settings['max_dimensions_responsive']['width'] . 'x' . $image_settings['max_dimensions_responsive']['height'];
      }
    }
    else {
      if (!empty($image_settings['max_dimensions']['width']) || !empty($image_settings['max_dimensions']['height'])) {
        $max_dimensions = $image_settings['max_dimensions']['width'] . 'x' . $image_settings['max_dimensions']['height'];
      }
    }

    $max_filesize = min(Bytes::toNumber($image_settings['max_size']), Environment::getUploadMaxSize());
    $form['fid'] = [
      '#title' => $this->t('Image'),
      '#type' => 'managed_file',
      '#upload_location' => 'public://' . $image_settings['directory'],
      '#default_value' => NULL,
      '#upload_validators' => [
        'file_validate_extensions' => !empty($image_settings['extensions']) ? [str_replace(',', '', $image_settings['extensions'])] : ['png jpg jpeg'],
        'file_validate_size' => [$max_filesize],
        'file_validate_image_resolution' => [$max_dimensions],
      ],
      '#required' => TRUE,
    ];

    $form['actions'] = [
      '#type' => 'actions',
    ];
    $form['actions']['save_modal'] = [
      '#type' => 'submit',
      '#value' => $this->t('Save'),
      // No regular submit-handler. This form only works via JavaScript.
      '#submit' => [],
      '#ajax' => [
        'callback' => '::submitForm',
        'event' => 'click',
      ],
    ];

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $response = new AjaxResponse();

    // Convert any uploaded files from the FID values to data-entity-uuid
    // attributes and set data-entity-type to 'file'.
    $fid = $form_state->getValue(['fid', 0]);
    if (!empty($fid)) {
      /** @var \Drupal\file\FileInterface $file */
      $file = $this->fileStorage->load($fid);
      $file_url = $file->getFileUri();
      $image = $this->imageFactory->get($file_url);
      $form_state->setValue(['attributes', 'src'], $file_url);
      $form_state->setValue(['attributes', 'width'], $image->getWidth());
      $form_state->setValue(['attributes', 'height'], $image->getHeight());
    }

    if ($form_state->getErrors()) {
      unset($form['#prefix'], $form['#suffix']);
      $form['status_messages'] = [
        '#type' => 'status_messages',
        '#weight' => -10,
      ];
      $response->addCommand(new HtmlCommand('#jfu-image-dialog-form', $form));
    }
    else {
      $response->addCommand(new JfuDialogSave($form_state->getValues()));
      $response->addCommand(new CloseModalDialogCommand());
    }

    return $response;
  }

}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc