diff --git a/app/Importer/AssetImporter.php b/app/Importer/AssetImporter.php index 3623c6e484..a8fd712536 100644 --- a/app/Importer/AssetImporter.php +++ b/app/Importer/AssetImporter.php @@ -31,9 +31,8 @@ class AssetImporter extends ItemImporter $this->item['custom_fields'][$customField->db_column_name()] = $customFieldValue; $this->log('Custom Field '. $customField->name.': '.$customFieldValue); } else { - // This removes custom fields when updating if the column doesn't exist in file. - // Commented out becausee not sure if it's needed anywhere. - // $this->item['custom_fields'][$customField->db_column_name()] = ''; + // Clear out previous data. + $this->item['custom_fields'][$customField->db_column_name()] = null; } } } @@ -106,6 +105,7 @@ class AssetImporter extends ItemImporter $asset->{$custom_field} = $val; } } + //FIXME: this disables model validation. Need to find a way to avoid double-logs without breaking everything. // $asset->unsetEventDispatcher(); if ($asset->save()) { diff --git a/app/Importer/Importer.php b/app/Importer/Importer.php index 56a6a47eee..45f7d1d170 100644 --- a/app/Importer/Importer.php +++ b/app/Importer/Importer.php @@ -116,6 +116,14 @@ abstract class Importer $nameLookup[$field['name']] = $field; return $nameLookup; }); + // Remove any custom fields that do not exist in the header row. This prevents nulling out values that shouldn't exist. + // In detail, we compare the lower case name of custom fields (indexed by name) to the keys in the header row. This + // results in an array with only custom fields that are in the file. + $this->customFields = array_intersect_key( + array_change_key_case($this->customFields), + array_change_key_case(array_flip($headerRow)) + ); + DB::transaction(function () use (&$results) { Model::unguard(); diff --git a/tests/unit/ImporterTest.php b/tests/unit/ImporterTest.php index 03b40f3aa3..7a2803f33e 100644 --- a/tests/unit/ImporterTest.php +++ b/tests/unit/ImporterTest.php @@ -88,6 +88,7 @@ EOT; $this->initializeCustomFields(); $this->import(new AssetImporter($csv)); + $updatedCSV = <<<'EOT' item Name,Category,Model name,Manufacturer,Model Number,Serial,Asset Tag,Location,Notes,Purchase Date,Purchase Cost,Company,Status,Warranty,Supplier A new name,some other category,Another Model,Linkbridge 32,356,67433477,970882174-8,New Location,I have no notes,2018-04-05,25.59,Another Company,Ready To Go,18,Not Creative