The contentType
attribute allows you to control how the browser interprets the page output. With this attribute, you can, for example, output some CSV, JSON, or XML content. Using a controller binding, this can be dynamically generated output. This can be useful to generate content to download. The following changes have been made to the FormulaForce application and are included in the code for this chapter:
generateSummaryAsCSV
, to RaceService
getCSVContent
method to RaceSummaryController
racesummaryascsv
Visualforce pageThe new method is added to the existing RaceSummaryController
class, but is only used by the new page. Feel free to review the new Service
method; note that it also uses the ContestantsSelector.selectByRaceIdWithContestantSummary
method introduced in the previous chapter. Here is the new controller method calling it:
public String getCSVContent() { return RaceService.generateSummaryAsCSV(new Set<Id> { standardController.getId() }); }
The RaceService
class contains the logic to generate the CSV file and not the controller class. Although at first you might consider this controller logic, if you think about it from a general data export perspective, there could equally be an API requirement in the future for external developers wanting to automate the CSV export process; thus, placing this logic in the Service layer facilitates this.
The new Visualforce page utilizes the contentType
attribute as follows:
<apex:page standardController="Race__c" extensions="RaceSummaryController" contentType="application/csv#{!Race__c.Name} Race Summary">{!CSVContent} </apex:page>
As this page uses a Standard Controller, a Custom Button can be created; once it has been clicked, instead of the page opening, the browser prompts you to download the file:
Pressing the Download Summary button results in the following prompt to download the resulting CSV file:
You may have noticed in the preceding VisualForce code that the apex:pagecontentType
attribute contained a "#" and some text. If you put a #
symbol after the content type, you can specify a default filename to be presented to the user when the file downloads. Also note that the Visualforce formula can also be used in attribute values, and this is how the Race name appears in the filename. This also allows you to vary contentType
dynamically if required.
While this example works quite well to illustrate the contentType
attribute, it should be noted that the platform-reporting engine also supports CSV exports. As such, if you are considering CSV export facilities, it is worth first considering asking users to leverage reports; thus, they have more freedom to control the output.
3.144.31.163