You are here

public function RenameForm::submitForm in Filebrowser 3.x

Same name and namespace in other branches
  1. 8.2 src/Form/RenameForm.php \Drupal\filebrowser\Form\RenameForm::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

src/Form/RenameForm.php, line 144

Class

RenameForm

Namespace

Drupal\filebrowser\Form

Code

public function submitForm(array &$form, FormStateInterface $form_state) {
  $new_names = $form_state
    ->getValue('new_name');
  foreach ($new_names as $fid => $new_name) {

    // Check if names were changed
    if (!empty($new_name) && $new_name != $this->oldNames[$fid]) {
      $file_data = unserialize($this->contents[$fid]['file_data']);
      $relative_root = $this->relativeRoot == '/' ? "" : $this->relativeRoot;
      if ($is_file = $file_data->type == 'file') {
        $new_filename = $relative_root . '/' . $new_name . "." . pathinfo($file_data->filename, PATHINFO_EXTENSION);
        $new_uri = $this->node->filebrowser->folderPath . $new_filename;
        $success = rename($file_data->uri, $new_uri);
        if ($success) {
          \Drupal::messenger()
            ->addMessage($this
            ->t('Renamed @old to @new', [
            '@old' => $file_data->uri,
            '@new' => $new_uri,
          ]));
          $this
            ->updateFileData($file_data, $new_uri);

          // serialize the updated data and store it in DB
          $data = serialize($file_data);
          $this->storage
            ->updateContentField('fid', $fid, 'file_data', $data);
          $this->storage
            ->updateContentField('fid', $fid, 'path', $new_filename);
        }
        else {
          \Drupal::messenger()
            ->addError($this
            ->t('Can not rename @old', [
            '@old' => $file_data->uri,
          ]));
        }
      }
      else {

        // this is a folder, we will not change anything
        \Drupal::messenger()
          ->addError($this
          ->t('@old is a folder. Folder rename is not supported', [
          '@old' => $file_data->uri,
        ]));
      }
    }
  }
  Cache::invalidateTags([
    'filebrowser:node:' . $this->node
      ->id(),
  ]);
  $form_state
    ->setRedirect($this->route['name'], $this->route['node'], $this->route['query']);
}