You are here

class ImageAPIOptimizePipelineEditForm in Image Optimize (or ImageAPI Optimize) 8.2

Same name and namespace in other branches
  1. 8.3 src/Form/ImageAPIOptimizePipelineEditForm.php \Drupal\imageapi_optimize\Form\ImageAPIOptimizePipelineEditForm
  2. 4.x src/Form/ImageAPIOptimizePipelineEditForm.php \Drupal\imageapi_optimize\Form\ImageAPIOptimizePipelineEditForm

Controller for image optimize pipeline edit form.

Hierarchy

Expanded class hierarchy of ImageAPIOptimizePipelineEditForm

File

src/Form/ImageAPIOptimizePipelineEditForm.php, line 15

Namespace

Drupal\imageapi_optimize\Form
View source
class ImageAPIOptimizePipelineEditForm extends ImageAPIOptimizePipelineFormBase {

  /**
   * The image optimize processor manager service.
   *
   * @var \Drupal\imageapi_optimize\ImageAPIOptimizeProcessorManager
   */
  protected $imageAPIOptimizeProcessorManager;

  /**
   * Constructs an ImageAPIOptimizePipelineEditForm object.
   *
   * @param \Drupal\Core\Entity\EntityStorageInterface $imageapi_optimize_pipeline_storage
   *   The storage.
   * @param \Drupal\imageapi_optimize\ImageAPIOptimizeProcessorManager $imageapi_optimize_processor_manager
   *   The image optimize processor manager service.
   */
  public function __construct(EntityStorageInterface $imageapi_optimize_pipeline_storage, ImageAPIOptimizeProcessorManager $imageapi_optimize_processor_manager) {
    parent::__construct($imageapi_optimize_pipeline_storage);
    $this->imageAPIOptimizeProcessorManager = $imageapi_optimize_processor_manager;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('entity.manager')
      ->getStorage('imageapi_optimize_pipeline'), $container
      ->get('plugin.manager.imageapi_optimize.processor'));
  }

  /**
   * {@inheritdoc}
   */
  public function form(array $form, FormStateInterface $form_state) {
    $user_input = $form_state
      ->getUserInput();
    $form['#title'] = $this
      ->t('Edit pipeline %name', [
      '%name' => $this->entity
        ->label(),
    ]);
    $form['#tree'] = TRUE;
    $form['#attached']['library'][] = 'imageapi_optimize/admin';

    // Build the list of existing image processors for this image optimize pipeline.
    $form['processors'] = [
      '#type' => 'table',
      '#header' => [
        $this
          ->t('Processor'),
        $this
          ->t('Weight'),
        $this
          ->t('Operations'),
      ],
      '#tabledrag' => [
        [
          'action' => 'order',
          'relationship' => 'sibling',
          'group' => 'image-processor-order-weight',
        ],
      ],
      '#attributes' => [
        'id' => 'image-pipeline-processors',
      ],
      '#empty' => t('There are currently no processors in this pipeline. Add one by selecting an option below.'),
      // Render processors below parent elements.
      '#weight' => 5,
    ];
    foreach ($this->entity
      ->getProcessors() as $processor) {
      $key = $processor
        ->getUuid();
      $form['processors'][$key]['#attributes']['class'][] = 'draggable';
      $form['processors'][$key]['#weight'] = isset($user_input['processors']) ? $user_input['processors'][$key]['weight'] : NULL;
      $form['processors'][$key]['processor'] = [
        '#tree' => FALSE,
        'data' => [
          'label' => [
            '#plain_text' => $processor
              ->label(),
          ],
        ],
      ];
      $summary = $processor
        ->getSummary();
      if (!empty($summary)) {
        $summary['#prefix'] = ' ';
        $form['processors'][$key]['processor']['data']['summary'] = $summary;
      }
      $form['processors'][$key]['weight'] = [
        '#type' => 'weight',
        '#title' => $this
          ->t('Weight for @title', [
          '@title' => $processor
            ->label(),
        ]),
        '#title_display' => 'invisible',
        '#default_value' => $processor
          ->getWeight(),
        '#attributes' => [
          'class' => [
            'image-processor-order-weight',
          ],
        ],
      ];
      $links = [];
      $is_configurable = $processor instanceof ConfigurableImageAPIOptimizeProcessorInterface;
      if ($is_configurable) {
        $links['edit'] = [
          'title' => $this
            ->t('Edit'),
          'url' => Url::fromRoute('imageapi_optimize.processor_edit_form', [
            'imageapi_optimize_pipeline' => $this->entity
              ->id(),
            'imageapi_optimize_processor' => $key,
          ]),
        ];
      }
      $links['delete'] = [
        'title' => $this
          ->t('Delete'),
        'url' => Url::fromRoute('imageapi_optimize.processor_delete', [
          'imageapi_optimize_pipeline' => $this->entity
            ->id(),
          'imageapi_optimize_processor' => $key,
        ]),
      ];
      $form['processors'][$key]['operations'] = [
        '#type' => 'operations',
        '#links' => $links,
      ];
    }

    // Build the new image processor addition form and add it to the processor list.
    $new_processor_options = [];
    $processors = $this->imageAPIOptimizeProcessorManager
      ->getDefinitions();
    uasort($processors, function ($a, $b) {
      return strcasecmp($a['id'], $b['id']);
    });
    foreach ($processors as $processor => $definition) {
      $new_processor_options[$processor] = $definition['label'];
    }
    $form['processors']['new'] = [
      '#tree' => FALSE,
      '#weight' => isset($user_input['weight']) ? $user_input['weight'] : NULL,
      '#attributes' => [
        'class' => [
          'draggable',
        ],
      ],
    ];
    $form['processors']['new']['processor'] = [
      'data' => [
        'new' => [
          '#type' => 'select',
          '#title' => $this
            ->t('Processor'),
          '#title_display' => 'invisible',
          '#options' => $new_processor_options,
          '#empty_option' => $this
            ->t('Select a new processor'),
        ],
        [
          'add' => [
            '#type' => 'submit',
            '#value' => $this
              ->t('Add'),
            '#validate' => [
              '::processorValidate',
            ],
            '#submit' => [
              '::submitForm',
              '::processorSave',
            ],
          ],
        ],
      ],
      '#prefix' => '<div class="image-pipeline-new">',
      '#suffix' => '</div>',
    ];
    $form['processors']['new']['weight'] = [
      '#type' => 'weight',
      '#title' => $this
        ->t('Weight for new processor'),
      '#title_display' => 'invisible',
      '#default_value' => count($this->entity
        ->getProcessors()) + 1,
      '#attributes' => [
        'class' => [
          'image-processor-order-weight',
        ],
      ],
    ];
    $form['processors']['new']['operations'] = [
      'data' => [],
    ];
    return parent::form($form, $form_state);
  }

  /**
   * Validate handler for image optimize processor.
   */
  public function processorValidate($form, FormStateInterface $form_state) {
    if (!$form_state
      ->getValue('new')) {
      $form_state
        ->setErrorByName('new', $this
        ->t('Select a processor to add.'));
    }
  }

  /**
   * Submit handler for image optimize processor.
   */
  public function processorSave($form, FormStateInterface $form_state) {
    $this
      ->save($form, $form_state);

    // Check if this field has any configuration options.
    $processor = $this->imageAPIOptimizeProcessorManager
      ->getDefinition($form_state
      ->getValue('new'));

    // Load the configuration form for this option.
    if (is_subclass_of($processor['class'], '\\Drupal\\imageapi_optimize\\ConfigurableImageAPIOptimizeProcessorInterface')) {
      $form_state
        ->setRedirect('imageapi_optimize.processor_add_form', [
        'imageapi_optimize_pipeline' => $this->entity
          ->id(),
        'imageapi_optimize_processor' => $form_state
          ->getValue('new'),
      ], [
        'query' => [
          'weight' => $form_state
            ->getValue('weight'),
        ],
      ]);
    }
    else {
      $processor = [
        'id' => $processor['id'],
        'data' => [],
        'weight' => $form_state
          ->getValue('weight'),
      ];
      $processor_id = $this->entity
        ->addProcessor($processor);
      $this->entity
        ->save();
      if (!empty($processor_id)) {
        $this
          ->messenger()
          ->addMessage($this
          ->t('The Image Optimize processor was successfully applied.'));
      }
    }
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {

    // Update image optimize processor weights.
    if (!$form_state
      ->isValueEmpty('processors')) {
      $this
        ->updateProcessorWeights($form_state
        ->getValue('processors'));
    }
    parent::submitForm($form, $form_state);
  }

  /**
   * {@inheritdoc}
   */
  public function save(array $form, FormStateInterface $form_state) {
    parent::save($form, $form_state);
    $this
      ->messenger()
      ->addMessage($this
      ->t('Changes to the pipeline have been saved.'));
  }

  /**
   * {@inheritdoc}
   */
  public function actions(array $form, FormStateInterface $form_state) {
    $actions = parent::actions($form, $form_state);
    $actions['submit']['#value'] = $this
      ->t('Update pipeline');
    return $actions;
  }

  /**
   * Updates image optimize processor weights.
   *
   * @param array $processors
   *   Associative array with processors having processor uuid as keys and array
   *   with processor data as values.
   */
  protected function updateProcessorWeights(array $processors) {
    foreach ($processors as $uuid => $processor_data) {
      if ($this->entity
        ->getProcessors()
        ->has($uuid)) {
        $this->entity
          ->getProcessor($uuid)
          ->setWeight($processor_data['weight']);
      }
    }
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
EntityForm::$entityTypeManager protected property The entity type manager. 3
EntityForm::$moduleHandler protected property The module handler service.
EntityForm::$operation protected property The name of the current operation.
EntityForm::$privateEntityManager private property The entity manager.
EntityForm::actionsElement protected function Returns the action form element for the current entity form.
EntityForm::afterBuild public function Form element #after_build callback: Updates the entity with submitted data.
EntityForm::buildEntity public function Builds an updated entity object based upon the submitted form values. Overrides EntityFormInterface::buildEntity 2
EntityForm::buildForm public function Form constructor. Overrides FormInterface::buildForm 10
EntityForm::copyFormValuesToEntity protected function Copies top-level form values to entity properties 7
EntityForm::getBaseFormId public function Returns a string identifying the base form. Overrides BaseFormIdInterface::getBaseFormId 5
EntityForm::getEntity public function Gets the form entity. Overrides EntityFormInterface::getEntity
EntityForm::getEntityFromRouteMatch public function Determines which entity will be used by this form from a RouteMatch object. Overrides EntityFormInterface::getEntityFromRouteMatch 1
EntityForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId 10
EntityForm::getOperation public function Gets the operation identifying the form. Overrides EntityFormInterface::getOperation
EntityForm::init protected function Initialize the form state and the entity before the first form build. 3
EntityForm::prepareEntity protected function Prepares the entity object before the form is built first. 3
EntityForm::prepareInvokeAll protected function Invokes the specified prepare hook variant.
EntityForm::processForm public function Process callback: assigns weights and hides extra fields.
EntityForm::setEntity public function Sets the form entity. Overrides EntityFormInterface::setEntity
EntityForm::setEntityManager public function Sets the entity manager for this form. Overrides EntityFormInterface::setEntityManager
EntityForm::setEntityTypeManager public function Sets the entity type manager for this form. Overrides EntityFormInterface::setEntityTypeManager
EntityForm::setModuleHandler public function Sets the module handler for this form. Overrides EntityFormInterface::setModuleHandler
EntityForm::setOperation public function Sets the operation for this form. Overrides EntityFormInterface::setOperation
EntityForm::__get public function
EntityForm::__set public function
FormBase::$configFactory protected property The config factory. 1
FormBase::$requestStack protected property The request stack. 1
FormBase::$routeMatch protected property The route match.
FormBase::config protected function Retrieves a configuration object.
FormBase::configFactory protected function Gets the config factory for this form. 1
FormBase::container private function Returns the service container.
FormBase::currentUser protected function Gets the current user.
FormBase::getRequest protected function Gets the request object.
FormBase::getRouteMatch protected function Gets the route match.
FormBase::logger protected function Gets the logger for a specific channel.
FormBase::redirect protected function Returns a redirect response object for the specified route. Overrides UrlGeneratorTrait::redirect
FormBase::resetConfigFactory public function Resets the configuration factory.
FormBase::setConfigFactory public function Sets the config factory for this form.
FormBase::setRequestStack public function Sets the request stack object to use.
FormBase::validateForm public function Form validation handler. Overrides FormInterface::validateForm 62
ImageAPIOptimizePipelineEditForm::$imageAPIOptimizeProcessorManager protected property The image optimize processor manager service.
ImageAPIOptimizePipelineEditForm::actions public function Returns an array of supported actions for the current entity form. Overrides EntityForm::actions
ImageAPIOptimizePipelineEditForm::create public static function Instantiates a new instance of this class. Overrides ImageAPIOptimizePipelineFormBase::create
ImageAPIOptimizePipelineEditForm::form public function Gets the actual form array to be built. Overrides ImageAPIOptimizePipelineFormBase::form
ImageAPIOptimizePipelineEditForm::processorSave public function Submit handler for image optimize processor.
ImageAPIOptimizePipelineEditForm::processorValidate public function Validate handler for image optimize processor.
ImageAPIOptimizePipelineEditForm::save public function Form submission handler for the 'save' action. Overrides ImageAPIOptimizePipelineFormBase::save
ImageAPIOptimizePipelineEditForm::submitForm public function This is the default entity object builder function. It is called before any other submit handler to build the new entity object to be used by the following submit handlers. At this point of the form workflow the entity is validated and the form state… Overrides EntityForm::submitForm
ImageAPIOptimizePipelineEditForm::updateProcessorWeights protected function Updates image optimize processor weights.
ImageAPIOptimizePipelineEditForm::__construct public function Constructs an ImageAPIOptimizePipelineEditForm object. Overrides ImageAPIOptimizePipelineFormBase::__construct
ImageAPIOptimizePipelineFormBase::$entity protected property The entity being used by this form. Overrides EntityForm::$entity
ImageAPIOptimizePipelineFormBase::$imageapiOptimizePipelineStorage protected property The image optimize pipeline entity storage.
LinkGeneratorTrait::$linkGenerator protected property The link generator. 1
LinkGeneratorTrait::getLinkGenerator Deprecated protected function Returns the link generator.
LinkGeneratorTrait::l Deprecated protected function Renders a link to a route given a route name and its parameters.
LinkGeneratorTrait::setLinkGenerator Deprecated public function Sets the link generator service.
LoggerChannelTrait::$loggerFactory protected property The logger channel factory service.
LoggerChannelTrait::getLogger protected function Gets the logger for a specific channel.
LoggerChannelTrait::setLoggerFactory public function Injects the logger channel factory.
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
RedirectDestinationTrait::$redirectDestination protected property The redirect destination service. 1
RedirectDestinationTrait::getDestinationArray protected function Prepares a 'destination' URL query parameter for use with \Drupal\Core\Url.
RedirectDestinationTrait::getRedirectDestination protected function Returns the redirect destination service.
RedirectDestinationTrait::setRedirectDestination public function Sets the redirect destination service.
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.
UrlGeneratorTrait::$urlGenerator protected property The url generator.
UrlGeneratorTrait::getUrlGenerator Deprecated protected function Returns the URL generator service.
UrlGeneratorTrait::setUrlGenerator Deprecated public function Sets the URL generator service.
UrlGeneratorTrait::url Deprecated protected function Generates a URL or path for a specific route based on the given parameters.