2

I have a custom entity (ContractSubscription) created in a custom module (amap).
One of its fields (contract_id) is a link to another custom entity (Contract) of the same module.

I created a View to export content of ContractSubscription as a csv file using REST Export.
Among the settings of the view, I have:

  • Path: /amap/contract/export
  • Contextual filters: 'Contract subscription : Contract' (this allows me to view only the subscriptions related to a specific contract)

When I go to mysite/amap/contract/export/2, I have the expected result that I can save locally:

enter image description here

As far as I understand, the name of the result is defined by the actual path when the view is executed, i.e. '2' which is the end of the path (in fact the value of the contextual filter).

I'd like to have something like 'Contract2.csv' instead of '2'.
How can I do that?

1

The HTTP header Content-Disposition will suggest the filename the browser will save as. What's needed here is to make the REST export to add the HTTP header.

It turns out there's an existing issue for the CSV Serialization module. The current patch in the issue will take the last part of the URL after the slash and appends .csv to it (e.g. 2.csv in your example). You could modify the patch to use whatever filename you want to use for your CSV export.

  • I couldn't make the patch work and being new to patching Drupal, I coudn't find why... So I did it another way (see my answer). – gbmapo Apr 1 at 16:20
1

Finally, I did that:
In amap.routing.yml, there is

amap.export_subscriptions:
  path: '/amap/contract/export/{contract}'
  defaults:
    _controller: '\Drupal\amap\Controller\ContractsController::export_subscriptions'

In ContractsController.php, there is

  public function export_subscriptions($contract)
  {
    amap_exportCSV('amap_contracts_subscriptions', 'rest_export_1', $contract); <-- some code to run the View with $contract as Contextual Filter
    $sFileName = 'Contract-'. $contract .'-export.csv';
    $sFileNameWithPath = 'sites/default/files/_private/contracts/' . $sFileName;
    $response = new BinaryFileResponse($sFileNameWithPath);
    $response->setContentDisposition(
      ResponseHeaderBag::DISPOSITION_ATTACHMENT,
      $sFileName
    );
    return $response;
  }

And it works as expected (for any browser including Safari).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.