MetaTagUploadForm.php in Metatag Import Export CSV 8
File
src/Form/MetaTagUploadForm.php
View source
<?php
namespace Drupal\metatag_import_export_csv\Form;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\file\Entity\File;
class MetaTagUploadForm extends FormBase {
public function getFormId() {
return 'metatag_import_export_upload';
}
public function buildForm(array $form, FormStateInterface $form_state) {
$form['upload_file'] = [
'#type' => 'managed_file',
'#title' => $this
->t('Upload file'),
'#required' => TRUE,
'#description' => t('Allowed extensions: csv'),
'#upload_location' => 'public://metatag_import_export_csv/',
'#upload_validators' => [
'file_validate_extensions' => [
'csv',
],
'validate_csv_header' => [],
],
];
$form['submit'] = [
'#type' => 'submit',
'#required' => TRUE,
'#value' => $this
->t("Import"),
];
return $form;
}
public function submitForm(array &$form, FormStateInterface $form_state) {
$fid = $form_state
->getValue('upload_file')[0];
$file = File::load($fid);
$file
->setTemporary();
$file
->save();
$url = $file
->getFileUri();
$filepath = file_create_url($url);
$this
->metatagImportExportCsvUpload($filepath);
}
public function metatagImportExportCsvUpload($filepath) {
$handle = fopen($filepath, 'r');
$headers = fgetcsv($handle);
fclose($handle);
$operations = [];
$operations[] = [
'\\Drupal\\metatag_import_export_csv\\MetatagImport::importCsvBatchOperation',
[
$headers,
$filepath,
],
];
$batch = [
'operations' => $operations,
'finished' => '\\Drupal\\metatag_import_export_csv\\MetatagImport::importFinish',
'title' => $this
->t('Metatags import'),
'init_message' => $this
->t('Import process is starting.'),
'progress_message' => $this
->t('Processed @current out of @total.'),
'error_message' => $this
->t('Batch has encountered an error.'),
];
batch_set($batch);
}
}