- π«π·France S3b0uN3t Nantes
Hello,
I also needed to generate a CSV with headers even when there were no results.
I'm providing my code as an example for others who may have this issue.In a
*.modulefile, i declare a hook:/** * Implements hook_views_post_render(). */ function mymodule_views_post_render(ViewExecutable $view, array &$output, CachePluginBase $cache): void { if ($view->id() !== 'my_view_id') { return; } $options = $view->getStyle()->options; // The CSV output is empty when there is no result, // even if a header row is requested. if ( empty($view->result) && isset($options['csv_settings']['output_header']) && $options['csv_settings']['output_header'] ) { $header_row = []; foreach ($view->field as $name => $field) { $header_row[$name] = $field->label(); } // Override output markup with the header row. $output['#markup'] = ViewsRenderPipelineMarkup::create( \Drupal::service('serializer')->serialize([$header_row], reset($options['formats']), ['csv_settings' => ['output_header' => FALSE] + $options['csv_settings']] ) ); } }Don't forget to rename the
mymodulehook function name prefix with your module name and themy_view_idwith your view ID.Regards,