Yii v2 snippet guide

Comparing #226 with #227

Revision #227 was created by rackycz rackycz on Aug 21, 2020, 6:45:28 PM.

Export to CSV

Content

[...]
I will describe how to easily export GridView into CSV so that filers and sorting is kept. I do not use any extentions which are so famous today.
Note that GridView is not needed, I just want to show the most complicated situation.

Let's say you have page on URL user/index and it contains GridView where you can list and filter users.

> Note: In class yii\data\Sort, in method getAttributeOrders(), is the sorting parameter take
mn from Yii::$app->getRequest() so the name of the sorted column must be in the URL you are using at the moment. This is why sorting might not work if you want to run UserSearch->search() manually without any GET parameters available in Yii::$app->request->queryParams.

The basic method for exporting DataProvider is here:
[...]
// Plus column names in format:
// ID;Username;Email etc based on your column names
$rows [] = chr(0xEF) . chr(0xBB) . chr(0xBF) .
InvoiceUser::getCsvHeader();

foreach ($dataProvider->models as $m) {
// Method getCsvRow() returns CSV row with values. Example:
// 1;petergreen;peter.green@gmail.com ...
$row = trim($m->getCsvRow());
[...]