I have a Drupal 7 submit method for updating CSV row by row to a custom table which I found under this link. I have tried to update it so that it works in Drupal 8 to no avail. How do I to modify it to work in Drupal 8?
function custom_module_submit($form, &$form_state) {
$file = $form_state['values']['csv_upload_file'];
$file->status = FILE_STATUS_PERMANENT;
$file->filename = str_replace(' ', '_', $file->filename);
file_save($file);
$csv_file = file_load($file->fid);
$file = fopen($csv_file->uri, "r");
while(! feof($file))
{
$customer = fgetcsv($file));
db_insert('your_db_table')
->fields(array(
'column1' => $customer[0],
'column2' => $customer[1]
))
->execute();
}
fclose($file);
drupal_set_message('CSV data added to the database');
}
The Drupal 8 code that I am trying to use is as below:
public function submitForm(array &$form, FormStateInterface $form_state)
{
$file = $form_state->getValue('csv_upload');
$file->status = FILE_STATUS_PERMANENT;
$file->filename = str_replace(' ', '_', $file->filename);
file_save_data($file);
$csv_file = \Drupal\file\Entity\File::load($file->fid);
$file = fopen($csv_file->getFileUri(), "r");
while (!feof($file)) {
$customer = fgetcsv($file);
\Drupal::database()->insert('your_db_table')
->fields(array(
'column1' => $customer[0],
'column2' => $customer[1]
))
->execute();
}
fclose($file);
drupal_set_message('CSV data added to the database');
}
Errors include:
- Fatal error: Call to a member function getFileUri() on null in /home/annuities/public_html/modules/custom_module/src/Form/CustomForm.php on line 90.
Line 90: $file = fopen($csv_file->getFileUri(), "r");
- Warning: Creating default object from empty value in Drupal\custom_module\Form\CustomForm->submitForm() (line 85 of modules/custom_module/src/Form/CustomForm.php).
Line 85: $file->status = FILE_STATUS_PERMANENT;
- Notice: Undefined property: stdClass::$filename in Drupal\custom_module\Form\CustomForm->submitForm() (line 86 of modules/custom_module/src/Form/CustomForm.php).
Line 86: $file->filename = str_replace(' ', '_', $file->filename);
- The file could not be created. Notice: Undefined property: stdClass::$fid in Drupal\custom_module\Form\CustomForm->submitForm() (line 89 of modules/custom_module/src/Form/CustomForm.php).
Line 89: $csv_file = \Drupal\file\Entity\File::load($file->fid);
- Warning: array_flip(): Can only flip STRING and INTEGER values! in Drupal\Core\Entity\EntityStorageBase->loadMultiple() (line 227 of core/lib/Drupal/Core/Entity/EntityStorageBase.php).
kint($csv_file);
what do you see? That error suggests that$csv_file
is empty.