function tmgmt_file_import_form_submit

Import form submit callback.

1 string reference to 'tmgmt_file_import_form_submit'
FileTranslatorUi::checkoutInfo in translators/tmgmt_file/src/FileTranslatorUi.php
Retrieves information about a translation job.

File

translators/tmgmt_file/tmgmt_file.module, line 29
Module file of the translation management test module.

Code

function tmgmt_file_import_form_submit(array $form, FormStateInterface $form_state) {

  // Ensure we have the file uploaded.
  $job = $form_state
    ->getFormObject()
    ->getEntity();
  $supported_formats = array_keys(Drupal::service('plugin.manager.tmgmt_file.format')
    ->getDefinitions());
  if ($file = file_save_upload('file', array(
    'file_validate_extensions' => array(
      implode(' ', $supported_formats),
    ),
  ), FALSE, 0)) {
    $extension = pathinfo($file
      ->getFileUri(), PATHINFO_EXTENSION);
    $plugin = \Drupal::service('plugin.manager.tmgmt_file.format')
      ->createInstance($extension);
    if ($plugin) {

      // Validate the file on job.
      $validated_job = $plugin
        ->validateImport($file
        ->getFileUri(), $job);
      if (!$validated_job) {
        $job
          ->addMessage('Failed to validate file, import aborted.', array(), 'error');
      }
      elseif ($validated_job
        ->id() != $job
        ->id()) {
        $job
          ->addMessage('The imported file job id @file_id does not match the job id @job_id.', array(
          '@file_id' => $validated_job
            ->id(),
          '@job_id' => $job
            ->id(),
        ), 'error');
      }
      else {
        try {

          // Validation successful, start import.
          $job
            ->addTranslatedData($plugin
            ->import($file
            ->getFileUri()));
          $job
            ->addMessage('Successfully imported file.');
        } catch (Exception $e) {
          $job
            ->addMessage('File import failed with the following message: @message', array(
            '@message' => $e
              ->getMessage(),
          ), 'error');
        }
      }
    }
  }
  tmgmt_write_request_messages($job);
}