Reputation: 747
This is a continuation of an issue I was having earlier where a link needed to be inserted into a SilverStripe GridField for each item.
Now the idea is that instead of a link there will be a custom action to initiate the download so there needs to be a custom GridFieldAction. I found out how to do it by looking at the GridFieldDeleteAction class, and mixing what I found there with information from the GridFieldExportButton class. The result almost works but the file is passed directly to the CMS tab's div element instead of being downloaded through the browser's download manager. This has to be because the data is being passed back using ajax, but how do I stop if from doing that? GridFieldExportButton is able to do this, so my class should too, dagnabbit!
/**
*
* @param GridField $gridField
* @param DataObject $record
* @param string $columnName
* @return string - the HTML for the column
*/
public function getColumnContent($gridField, $record, $columnName) {
$field = GridField_FormAction::create($gridField, 'downloadFile'.$record->ID, "Download", "downloadfile",
array('RecordID' => $record->ID));
return $field->Field();
}
/**
* Handle the actions and apply any changes to the GridField
*
* @param GridField $gridField
* @param string $actionName
* @param mixed $arguments
* @param array $data - form data
* @return void
*/
public function handleAction(GridField $gridField, $actionName, $arguments, $data) {
if($actionName == 'downloadfile') {
$item = $gridField->getList()->byID($arguments['RecordID']);
if(!$item) {
return;
}
$filename = $item->Document()->fileName;
if(substr($filename, 0, 1) != '/') $filename = "/$filename";
$filename = Director::baseFolder( ) . $filename;//$_SERVER['DOCUMENT_ROOT']
if( file_exists($filename) ){
$fileData = file_get_contents($filename);
return SS_HTTPRequest::send_file($fileData, $item->Document()->Name);
}else{
error_log("CMS Download Failed: ($filename) not found in GFDownloadAction::handleAction. Freak out in 10 ... 9 ... 8 ...", 0);
}
}
}
Upvotes: 2
Views: 267
Reputation: 747
The answer presented itself even as I posted the question. in GetColumnContent a GridField_FormAction Object is being created.
In GridFieldExportButton there is an innocent-looking line where a button receives an extra css class called -- don't laugh -- 'no ajax' The button is also a GridField_FormAction.
in GetColumnContent added this line:
$field->addExtraClass('no-ajax');
Works perfectly.
Upvotes: 3