Import form submit callback.
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);
}