You are here

public function MediaWatermarkForm::save in Media watermark 8

Form submission handler for the 'save' action.

Normally this method should be overridden to provide specific messages to the user and redirect the form after the entity has been saved.

Parameters

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

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

Return value

int Either SAVED_NEW or SAVED_UPDATED, depending on the operation performed.

Overrides EntityForm::save

File

src/Form/MediaWatermarkForm.php, line 117

Class

MediaWatermarkForm
Class MediaWatermarkForm.

Namespace

Drupal\media_watermark\Form

Code

public function save(array $form, FormStateInterface $form_state) {
  $media_watermark = $this->entity;
  $is_new = !$media_watermark
    ->getOriginalId();
  $id = $media_watermark
    ->id();

  // Check for newly created watermark.
  if ($is_new) {

    // Check if id already exists.
    if (!$this
      ->exist($media_watermark
      ->id())) {

      // Configuration entities need an ID manually set.
      $machine_name = \Drupal::transliteration()
        ->transliterate($media_watermark
        ->label(), LanguageInterface::LANGCODE_DEFAULT, '_');
      $media_watermark
        ->set('id', mb_strtolower($machine_name));
      $status = $media_watermark
        ->save();
      if ($status) {

        // Add file usage.
        $fids = $form_state
          ->getValue('fid');
        $fid = reset($fids);
        $this
          ->addFileUsage($form_state);
        $this
          ->messenger()
          ->addStatus($this
          ->t('Saved the %label Media Watermark.', [
          '%label' => $media_watermark
            ->label(),
        ]));
      }
      else {
        $this
          ->messenger()
          ->addStatus($this
          ->t('The %label Media Watermark was not saved.', [
          '%label' => $media_watermark
            ->label(),
        ]));
      }
    }
    else {
      $this
        ->messenger()
        ->addStatus($this
        ->t('The Media Watermark with same machine name already exists %name.', [
        '%name' => $id,
      ]));
    }
  }
  else {
    $status = $media_watermark
      ->save();
    if ($status) {

      // Process already existent watermark.
      $fids = $form_state
        ->getValue('fid');
      $fid = reset($fids);
      $watermark_fid = $media_watermark
        ->getFid();
      $watermark_fid = reset($watermark_fid);
      if ($fid != $watermark_fid) {
        $this
          ->addFileUsage($form_state);
      }
    }
    else {
      $this
        ->messenger()
        ->addStatus($this
        ->t('The %label Media Watermark was not saved.', [
        '%label' => $media_watermark
          ->label(),
      ]));
    }
  }
  $form_state
    ->setRedirect('media_watermark.list');
}