You are here

MediaWatermarkDeleteForm.php in Media watermark 8

File

src/Form/MediaWatermarkDeleteForm.php
View source
<?php

namespace Drupal\media_watermark\Form;

use Drupal\Core\Entity\EntityConfirmFormBase;
use Drupal\Core\Url;
use Drupal\Core\Form\FormStateInterface;

/**
 * Class MediaWatermarkDeleteForm.
 *
 * @package Drupal\media_watermark\Form
 * @ingroup media_watermark
 */
class MediaWatermarkDeleteForm extends EntityConfirmFormBase {

  /**
   * {@inheritdoc}
   */
  public function getQuestion() {
    return $this
      ->t('Are you sure you want to delete %name?', [
      '%name' => $this->entity
        ->label(),
    ]);
  }

  /**
   * {@inheritdoc}
   */
  public function getCancelUrl() {
    return new Url('media_watermark.list');
  }

  /**
   * {@inheritdoc}
   */
  public function getConfirmText() {
    return $this
      ->t('Delete');
  }

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

    /** @var \Drupal\file\FileStorageInterface $file_storage */
    $file_storage = $this->entityTypeManager
      ->getStorage('file');

    /** @var \Drupal\media_watermark\Entity\MediaWatermarkInterface $watermark */
    $watermark = $this->entity;

    // Get attached files from watermark and handle different options of file
    // ids storing in watermark entity.
    $file_ids_from_entity = $watermark
      ->getFid();
    $file_ids = is_array($file_ids_from_entity) ? $file_ids_from_entity : [
      $file_ids_from_entity,
    ];
    $files = $file_storage
      ->loadMultiple($file_ids);
    $file_names = [];

    /** @var \Drupal\file\FileInterface $file */
    foreach ($files as $file) {
      $file_names[] = $file
        ->getFilename();
    }

    // Delete file attached to the watermark.
    if ($files) {
      $file_storage
        ->delete($files);
    }

    // Delete watermark.
    $watermark
      ->delete();

    // Add status message to inform the user about operation.
    if ($file_names) {
      $message = $this
        ->t('Watermark "%label" and attached images ( %file_names ) has been deleted.', [
        '%label' => $watermark
          ->label(),
        '%file_names' => implode(', ', $file_names),
      ]);
    }
    else {
      $message = $this
        ->t('Watermark "%label" has been deleted.', [
        '%label' => $watermark
          ->label(),
      ]);
    }
    $this
      ->messenger()
      ->addMessage($message);

    // Redirect to the appropriate location.
    $form_state
      ->setRedirectUrl($this
      ->getCancelUrl());
  }

}

Classes

Namesort descending Description
MediaWatermarkDeleteForm Class MediaWatermarkDeleteForm.