You are here

public function MediaWatermarkDeleteForm::submitForm in Media watermark 8

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 can be updated, this way the subsequently invoked handlers can retrieve a regular entity object to act on. Generally this method should not be overridden unless the entity requires the same preparation for two actions, see \Drupal\comment\CommentForm for an example with the save and preview actions.

Parameters

array $form: An associative array containing the structure of the form.

\Drupal\Core\Form\FormStateInterface $form_state: The current state of the form.

Overrides EntityForm::submitForm

File

src/Form/MediaWatermarkDeleteForm.php, line 43

Class

MediaWatermarkDeleteForm
Class MediaWatermarkDeleteForm.

Namespace

Drupal\media_watermark\Form

Code

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());
}