Skip to content

Commit

Permalink
Fix incorrect CSV headers when exporting multiple record types farmOS…
Browse files Browse the repository at this point in the history
  • Loading branch information
mstenta committed May 7, 2024
1 parent 92da9a9 commit c925d76
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 0 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- [Remove data_table from existing plan_record entity type definition #829](https://github.com/farmOS/farmOS/pull/829)
- [Use farm_people entity_reference View for exposed Owner filter in farm_asset View #835](https://github.com/farmOS/farmOS/pull/835)
- [Require asset name in bulk KML importer #836](https://github.com/farmOS/farmOS/pull/836)
- [Fix incorrect CSV headers when exporting multiple record types #842](https://github.com/farmOS/farmOS/pull/842)

## [3.2.1] 2024-04-12

Expand Down
4 changes: 4 additions & 0 deletions modules/core/csv/farm_csv.services.yml
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
services:
farm_csv.encoder.csv:
class: Drupal\farm_csv\Encoder\CsvEncoder
tags:
- { name: encoder, format: csv, priority: 10 }
farm_csv.normalizer.content_entity_normalizer:
class: Drupal\farm_csv\Normalizer\ContentEntityNormalizer
tags:
Expand Down
38 changes: 38 additions & 0 deletions modules/core/csv/src/Encoder/CsvEncoder.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
<?php

namespace Drupal\farm_csv\Encoder;

use Drupal\csv_serialization\Encoder\CsvEncoder as ContribCsvEncoder;

/**
* Extend the contrib CsvEncoder class with custom header extraction logic.
*/
class CsvEncoder extends ContribCsvEncoder {

/**
* {@inheritdoc}
*/
protected function extractHeaders(array $data, array $context = []) {
$headers = [];

// Iterate over each row and merge its headers.
// This differs from the parent method in that it combines headers from all
// rows instead of only using headers from the first row.
foreach ($data as $row) {
$headers = array_merge($headers, array_diff(array_keys($row), $headers));
}

// Use labels provided by the Views style plugin, if available.
// This mimics the logic of the parent method for compatibility in Views
// contexts.
if (!empty($context['views_style_plugin'])) {
$fields = $context['views_style_plugin']->view->field;
$headers = array_map(function ($header) use ($fields) {
return !empty($fields[$header]->options['label']) ? $fields[$header]->options['label'] : $header;
}, $headers);
}

return $headers;
}

}

0 comments on commit c925d76

Please sign in to comment.