Hi there,
I’ve been using CsvView for some time now and it’s great for downloading CSV files on demand. I now need to create a cronjob which sends the output from CsvView as an email attachment.
I’ve not yet got my head around how I get CsvView working from a Shell, instead I’m focusing on creating a controller/action which sends CsvView output as an attachment.
I’ve got that working with the following code (CakePHP 2.x):
$this->response->download('enquiries_export.csv');
$_serialize = 'csvData';
$this->viewClass = 'CsvView.Csv';
$this->set(compact('csvData' ,'_serialize', '_header', '_extract'));
$this->autoRender = false;
$response = $this->render();
$email = new CakeEmail();
$email->from($from)
->to($to)
->subject('CSV Export')
->template('bookings_csv')
->emailFormat('text')
->attachments(array(
'bookings.csv' => array(
'data' => $response,
'mimetype' => 'text/csv'
)
))
->theme($this->theme);
}
The only issue with this is when I call this action, it is sending the email AND downloading the CSV file. I there a way to only send the email with the attachment?
Also, any tips on how I can then get CsvView working from a Shell called by a cronjob would be greatly appreciated too.
Thanks, Paul.
As ever, persistence is the key … here’s my working solution
App::uses('CakeRequest', 'Network');
App::uses('CakeResponse', 'Network');
App::uses('MyController', 'Plugin.Controller');
$controller = new MyController(new CakeRequest(), new CakeResponse());
$controller->CsvView = $controller->Components->load('CsvView.CsvView');
$controller->CsvView->startup($controller);
$csvData = $this->Model->find('all', array(
'contain' => array()
));
$_extract = $controller->CsvView->prepareExtractFromFindResults($csvData);
$customHeaders = array(
'Model.field1' => 'Column1',
'Model.field2' => 'Column2',
...,
);
$_header = $controller->CsvView->prepareHeaderFromExtract($_extract, $customHeaders);
$controller->response->download('csv_export.csv');
$_serialize = 'csvData';
$controller->viewClass = 'CsvView.Csv';
$controller->set(compact('csvData' ,'_serialize', '_header', '_extract'));
$controller->autoRender = false;
$response = $controller->render();
$email = new CakeEmail();
$email->from($from)
->to($to)
->subject($subject)
->template('csv_export')
->emailFormat('text')
->attachments(array(
'export.csv' => array(
'data' => $response,
'mimetype' => 'text/csv'
)
))
->theme($controller->theme);
$email->send();
I don’t know if I really needed to do all of the App::uses() calls to get the controller and view logic working so any tips on how to improve this would be greatly appreciated.
Thanks, Paul.