Skip to main content

This site requires you to update your browser. Your browsing experience maybe affected by not having the most up to date version.

We've moved the forum!

Please use forum.silverstripe.org for any new questions (announcement).
The forum archive will stick around, but will be read only.

You can also use our Slack channel or StackOverflow to ask for help.
Check out our community overview for more options to contribute.

Customising the CMS /

Moderators: martimiz, Sean, Ed, biapar, Willr, Ingo, swaiba

Save CSV file from Task


Go to End


1423 Views

Avatar
Vix

Community Member, 60 Posts

29 April 2016 at 8:43pm

I need to create a task for a cron job that exports data to a csv file, saves it and then emails it to a given email address. What I have done so far is...

if(!empty($data)){
				//create CSV
				$filename = 'ProductsOrdered-'.$today.'.csv';
				$separator = $this->csvSeparator;
				$csvColumns = array('ProductID', 'Product Title', 'MYOB Code', 'Order Date', 'Quantity', 'Total Value');
				$fileData = '';

				if($this->csvHasHeader) {
					$headers = array();
		
					// determine the CSV headers. If a field is callable (e.g. anonymous function) then use the
					// source name as the header instead
					foreach($csvColumns as $columnSource => $columnHeader) {
						$headers[] = (!is_string($columnHeader) && is_callable($columnHeader)) ? $columnSource : $columnHeader;
					}
		
					$fileData .= "\"" . implode("\"{$separator}\"", array_values($headers)) . "\"";
					$fileData .= "\n";
				}
				$items = $data;
				
				foreach($items as $item) {
					
						$columnData = array();
		
						foreach($item as $e) {
							
							$value = str_replace(array("\r", "\n"), "\n", $e);
							$columnData[] = '"' . str_replace('"', '""', $value) . '"';
						}
		
						$fileData .= implode($separator, $columnData);
						$fileData .= "\n";
						
				}
				
				$csv = SS_HTTPRequest::send_file($fileData, $filename, 'text/csv');
				$f = new File();
				$f->ClassName = 'File';
				$f->Name = $filename;
				$f->Title = $filename;
				$f->Filename = 'assets/Uploads/Reports'.$filename;
				$f->write();
				//email the report
				$to = 'email@somewhere.com.au';
				$subject = 'Products Ordered Yesterday';
				$from = 'email@somewhere.com.au';
				$email = new Email($from, $to, $subject);
				$email->setTemplate('ReportEmail');
				$email->attachFile('/assets/Uploads/Reports/'.$filename.'');
				$email->send();
			}

Which I have mostly borrowed from the GridFieldExportButton class. Unfortunately it is not working. The file neither downloads automatically or saves in the assets folder. The data is def not empty as I can print it out to the screen, its just not doing anything.

Any pointers would be fabulous.