function StyleForm::submitForm

Form submission handler.

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 FormInterface::submitForm

File

modules/image_example/src/Form/StyleForm.php, line 141

Class

StyleForm
Form for interacting with image styles.

Namespace

Drupal\image_example\Form

Code

public function submitForm(array &$form, FormStateInterface $form_state) {
  // When using the #managed_file form element the file is automatically
  // uploaded an saved to the {file} table. The value of the corresponding
  // form element is set to the ID of the new file. If the file ID is not
  // zero, we have a valid file.
  if (($fid = $form_state->getValue('image_fid')) != 0) {
    // The new file's status is set to 0 or temporary and in order to ensure
    // that the file is not removed after 6 hours, we need to change its
    // status to 1. Save the ID of the uploaded image for later use.
    if ($file = File::load($fid)) {
      $file->setPermanent();
      $file->save($file);
      // When a module is managing a file, it must manage the usage count.
      $this->fileUsage
        ->add($file, 'image_example', 'sample_image');
      $this->messenger
        ->addMessage($this->t('The image @image_name was uploaded and saved. Its ID is @fid and it will be displayed using the image style @style.', [
        '@image_name' => $file->getFilename(),
        '@fid' => $fid,
        '@style' => $form_state->getValue('style_name'),
      ]));
    }
    else {
      $fid = NULL;
      $this->messenger
        ->addWarning($this->t('The image could not be saved.'));
    }
  }
  // Delete the previously uploaded image.
  $old_fid = $this->state
    ->get('image_example.image_fid');
  if (!empty($old_fid) && ($old_file = File::load($old_fid))) {
    $image_name = $old_file->getFilename();
    // When a module is managing a file, it must manage the usage count.
    $this->fileUsage
      ->delete($old_file, 'image_example', 'sample_image');
    // File::delete() verifies the file is used by any other modules. If it
    // is, the file will not be deleted. The module still needs to update
    // its reference.
    $old_file->delete();
    $this->messenger
      ->addMessage($this->t('The image @image_name was removed.', [
      '@image_name' => $image_name,
    ]));
  }
  // Usually, a form submission handler stores the data in a configuration
  // object, or in a custom database table, but in this case we use the state
  // service.
  $this->state
    ->set('image_example.image_fid', $fid);
  $this->state
    ->set('image_example.style_name', $form_state->getValue('style_name'));
}