Problem/Motivation

When importing CSV files with empty entity reference fields, the CSV Importer module attempts to save empty string values (`''`) to entity reference fields. This causes SQL errors because the database expects either a valid integer ID or NULL for entity reference fields, not an empty string.

Error message:

SQLSTATE[HY000]: General error: 1366 Incorrect integer value: '' for column 'tid' at row 1: 
INSERT INTO "taxonomy_index" ("nid", "tid", "status", "sticky", "created") 
VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, 
:db_insert_placeholder_3, :db_insert_placeholder_4); 
Array ( 
  [:db_insert_placeholder_0] => 932 
  [:db_insert_placeholder_1] =>  
  [:db_insert_placeholder_2] => 1 
  [:db_insert_placeholder_3] => 0 
  [:db_insert_placeholder_4] => 1762422668 
)

This results in imports silently failing with "0 content added and 0 updated" even though the CSV structure is valid.

Steps to reproduce

1. Create a content type or taxonomy vocabulary with entity reference fields
2. Create a CSV file where some rows have empty values for entity reference fields (e.g., `title,field_page_type,field_reference,field_category` where `field_reference` or `field_category` are entity reference fields)
3. Use consecutive commas to represent empty values: `"My Title",my_type,2225,,` (empty field_category)
4. Attempt to import the CSV via the CSV Importer UI at `/admin/config/development/csv-importer`
5. Observe that the import reports "0 content added and 0 updated"
6. Check watchdog logs: `drush watchdog:show --type=csv_importer` to see the SQL error

Proposed resolution

Modify `ImporterBase::add()` to detect and remove empty entity reference fields from the `$content` array before attempting to save the entity. This prevents empty strings from being passed to Drupal's entity storage system.

The fix checks each field's type and removes it from the content array if:
- The field type is `entity_reference`
- The value is empty (empty string from CSV parsing)

This approach allows optional entity reference fields to be left empty in CSV imports without causing SQL errors.

Remaining tasks

1. Review and test the proposed patch
2. Confirm it works with various entity reference field configurations (single value, multi-value, required vs optional)
3. Add automated test coverage for empty entity reference field handling
4. Commit to the project

User interface changes

None. The import process now handles empty entity reference fields gracefully without user-facing changes.

API changes

None. This is an internal fix to the import logic.

Data model changes

None. This fix prevents invalid data from being written to the database.

Comments

martijn de wit created an issue. See original summary.

martijn de wit’s picture

csv_importer-empty-entity-reference-fields.patch is against 8.x.1

The new patch is against 8.x-2.2.

Also added some test