I would like to export all selected items from the items-view of my component.
To do so I modified my view and inserted a new button to the
JToolBarHelper::custom('items.exportcsv', 'download', '', 'COM_BESTIA_EXPORT', true);
I also modified the controller:
/**
* exportcsv function.
*
* @access public
* @return void
*/
public function exportcsv()
{
$jinput = JFactory::getApplication()->input;
$ids = $jinput->get('cid', '', 'array');
$modelitems = $this->getModel();
$array = array();
foreach($ids as $id)
{
$item = $modelitems->getItem($id);
$array[$item->id]['itemid'] = $item->itemid;
}
$csv = ArrayHelper::exportArrayToCSV($array, "items-report");
$this->setRedirect('index.php?option=bestia&view=items', false);
}
Now I created a function in a helper function to create the download:
/**
* exportArrayToCSV function.
*
* @access public
* @static
* @param mixed $array
* @return void
*/
public static function exportArrayToCSV($array, $filename, $delimiter=";")
{
$config = JFactory::getConfig();
$tmppath = $config->get('tmp_path');
$keys = array_keys($array);
if(is_dir($tmppath))
{
$filename = "$filename.csv";
$filepath = "$tmppath/$filename";
$file = new SplFileObject($filepath, 'w');
$file->fputcsv(array_keys($array[$keys[0]]),$delimiter);
foreach ($array as $fields)
{
$file->fputcsv($fields,$delimiter);
}
if(file_exists($filepath))
{
header ( 'Content-Description: File Transfer' );
header ( 'Content-Type: application/force-download' );
header ( 'Content-Type: application/octet-stream' );
header ( 'Content-Disposition: attachment; filename=' . $filename );
header ( 'Expires: 0' );
header ( 'Cache-Control: must-revalidate' );
header ( 'Pragma: public' );
header ( 'Content-Length: ' . filesize ($filepath) );
ob_clean();
flush();
readfile ($filepath);
unlink($filepath);
exit();
}
else return false;
}
else return false;
}
This also works fine.
But I am facing a strange behaviour: If I download a CSV and change the filter after downloading in the search bar like this:
The file is downloaded again.
I think the problem is somewhere around here:
ob_clean();
flush();
readfile ($filepath);
unlink($filepath);
exit();
But I do not know how to solve it.
this.form.task = '';
You can simply go like this. Likethis.form.inputName