Alter CSV Headers for Views Data Export

The Views Data Export module is a very useful module for exporting large quantities of data from Drupal in formats such as CSV (comma-separated value) and TSV (tab-separated value). Altering headers and rows can be challenging, however. In this post, we'll discuss how to alter headers.

Normally, it's possible to alter field labels, which are used in the header row, by using hook_preprocess_views_view_fields(). However, the module depends on the CSV Serialization module to do the heavy lifting, and hook_preprocess_views_view_fields()is never triggered. Instead, we can use hook_views_pre_view().

In the example below, we're replacing the label for a field:

<?php
/**
 * Implements hook_views_pre_view().
 */
function MYMODULE_views_pre_view(\Drupal\views\ViewExecutable $view, $display_id, array &$args) {
  if (
$view->id() == 'my_data_export_view' && $display_id == 'data_export_1') {
   
// @see \Drupal\csv_serialization\Encoder\CsvEncoder::extractHeaders().
    // Get the 'rest_export_attachment_1' display.
    /** @var \Drupal\views_data_export\Plugin\views\display\DataExport */
   
$display = $view->getDisplay('rest_export_attachment_1');
   
// Get the fields from the display's options.
   
$fields = $display->getOption('fields');
   
// Set the new field label to be used for the header row.
   
$fields['field_my_field']['label'] = 'New Label';
   
// Update display's options with updated fields.
   
$display->setOption('fields', $fields);
  }
}
?>

Add new comment