I was wondering how I would go about creating a CSV export from the admin.
I currently have a simple module in admin which holds a mass of user data. I would like to add a button next to the create which will export this data into a CSV file. How would I tackle this in FUEL?
Thanks
Comments
Add a custom button to your list_actions, example:
'list_actions' => array('controller/method' => 'Export')
Then in your controller do what you need get the records and push the csv for download:
header("Cache-Control: private"); header("Content-type: text/csv"); header("Content-Disposition: attachment; filename=\"".uniqid().'.csv'."\""); header("Content-type: application/x-msdownload"); echo $this->output; exit();
https://github.com/daylightstudio/FUEL-CMS/tree/1.0
I will have to checkout the beta version, it seems that many new features have been added.
<?php require_once('module.php'); class Enquiries extends Module { function __construct() { parent::__construct(); } function export() { // get all the records $query = $this->db->query("SELECT * FROM fuel_enquiries ORDER by 'surname' ASC"); $result = $query->result_array(); //print_r($result); foreach($result as $row) { header("Cache-Control: private"); header("Content-type: text/csv"); header("Content-Disposition: attachment; filename=\"".uniqid().'.csv'."\""); header("Content-type: application/x-msdownload"); echo $row['date'].''.$row['id'].','.$row['first_name'].','.$row['surname'].','.$row['company'].','.$row['email'].','.$row['telephone'].','.$row['sector'].','.$row['enquiry'].','; } exit(); } }
How would I tackle this?
If your schema matches the format you want for your file you can just use:
$output = $this->dbutil->csv_from_result($query, ',');
Otherwise I'd rewrite what you have there with:
require_once('module.php'); class Enquiries extends Module { function __construct() { parent::__construct(); } function export() { $result = $this->db ->order_by('surname', 'asc') ->get('fuel_enquiries') ->result_array(); foreach ($result as $row) { $output[] = $row['date'].$row['id'].','.$row['first_name'].','.$row['surname'].','.$row['company'].','. $row['email'].','.$row['telephone'].','.$row['sector'].','.$row['enquiry'].','; } header("Cache-Control: private"); header("Content-type: text/csv"); header("Content-Disposition: attachment; filename=\"".uniqid().'.csv'."\""); header("Content-type: application/x-msdownload"); echo join($output); exit(); } }
Your first two fields in your example are missing a comma between, not sure if an error, I didn't add in the above.