Zamiast tworzyć odrębną metodę obsługi eksportu można przełączać kontekst za pomocą rozszerzenia .csv
Instalacja pluginu: tutaj
/condig/routes.php
$routes->setExtensions(['json', 'pdf', 'csv']);
ProjectsController.php – index() – przygotowanie zbioru
$query = $this->Projects->find()->contain(...)->where(...);
Rozpoznanie .csv i przełączenie klasy
if($this->getRequest()->is('csv')) {
$query = $query->order(['date' => 'DESC'])->all();
$header = ['Lp', 'Manager', 'Numer', 'Produkt', 'Klient', 'Temat', 'Termin realizacji', 'Wartość'];
$exports = [];
foreach($query as $ind => $exp)
{
$exports[$ind]['id'] = ++$ind;
$exports[$ind]['manager'] = $exp->has('manager') ? $exp->manager->full_name : '-';
$exports[$ind]['numer'] = $exp->inicjal.'/'.$exp->id;
$exports[$ind]['produkt'] = $exp->has('product') ? $exp->product->name : '-';
$exports[$ind]['klient'] = $exp->has('company') ? $exp->company->name : '-';
$exports[$ind]['temat'] = $exp->name;
$exports[$ind]['termin'] = $exp->plan_date;
$exports[$ind]['wartosc'] = number_format($exp->price, 2, '.', '');
}
// Wymuszenie zapisania rezultatu z DB z określoną nazwą
$new_response = $this->getResponse()->withDownload('projekty-'.date('d-m-YTHi').'.csv');
$this->setResponse($new_response);
// Konfiguracja pluginu
$this->viewBuilder()->setClassName('CsvView.Csv');
$this->set('_header', $header);
$this->set('_dataEncoding', 'UTF-8');
$this->set('_csvEncoding', 'CP1250');
$this->set(compact('exports'));
$this->set('_serialize', 'exports');
return;
}
dalsza część metody index() – do wyświetlania na stronie – bez .csv
$projects = $this->paginate($query);
$this->set(compact('projects'));
$managers = $this->Projects->Managers->find('list');
$products = $this->Projects->Products->find('list');
$statuses = $this->Projects->Statuses->find('list');
Skrypt export.js obsługujący kliknięcie w link #export
$("#export").on('click', function() {
// Jeśli url nie kończy się index np. /projects
if(!/index/.test(url.pathname)) {
url.pathname += '/index'; // dodaje /index
}
url.pathname += '.csv'; // dodaje .csv
location.href = url.href; // wywołuje export
// Przywraca możliwość wyszukiwania bez exportu - ucinamy .csv (index zostaje)
setTimeout(function(){
url.pathname = url.pathname.replace('.csv', '');
}, 2000);
return false; // wstrzymuje kliknięcie odnośnika a
});