如何生成自定义CSV导出?

时间:2017-03-01 01:49:24

标签: php silverstripe

我有一个名为EventPage的页面,我通过模型管理员管理。还使用目录管理器:https://github.com/littlegiant/silverstripe-catalogmanager

问题是我需要能够导出所有过期事件(以及所有字段)。

我在'EndDate' => 'Date',上有一个EventPage字段。

所以我想只在我的CSV导出中显示EventPages,其中EndDate是GreaterThanOrEqual到今天的日期,例如Expired。

以下内容会生成一个CSV导出按钮,但目前它正在导出所有字段,因为我想过滤它,所以我们只显示过期的事件。

我该怎么做?

<?php

class EventAdmin extends CatalogPageAdmin {

    public $showImportForm = false;

    private static $managed_models = array(
        'EventPage',
        'EventCategory',
        'EventSubmission',
    );

    private static $url_segment = 'events';

    private static $menu_title = 'Events';


    public function getEditForm($id = null, $fields = null) {

        $form = parent::getEditForm($id, $fields);

        $gridFieldName = 'EventPage';
        $gridField = $form->Fields()->fieldByName($gridFieldName);

        if ($gridField) {
            $gridField->getConfig()->addComponent(new GridFieldExportButton());
        }

        return $form;
    }


}

3 个答案:

答案 0 :(得分:3)

我们可以创建自定义导出按钮,以在导出项目列表之前对其进行过滤。

首先,我们创建一个扩展GridFieldExportExpiredEventsButton的{​​{1}}。这是当前SilverStripe 3.5 GridFieldExportButton函数的完整副本,但在generateExportFileData列表中添加了filterByCallback,以过滤具有$items的项目。

EndDate < date('Y-m-d')

我们添加的用于过滤导出项的额外行是:

class GridFieldExportExpiredEventsButton extends GridFieldExportButton {

    public function getHTMLFragments($gridField) {
        $button = new GridField_FormAction(
            $gridField,
            'export',
            'Export expired events',
            'export',
            null
        );
        $button->setAttribute('data-icon', 'download-csv');
        $button->addExtraClass('no-ajax action_export');
        $button->setForm($gridField->getForm());
        return array(
            $this->targetFragment => '<p class="grid-csv-button">' . $button->Field() . '</p>',
        );
    }

    public function generateExportFileData($gridField) {
        $separator = $this->csvSeparator;
        $csvColumns = $this->getExportColumnsForGridField($gridField);
        $fileData = '';
        $member = Member::currentUser();

        if($this->csvHasHeader) {
            $headers = array();

            // determine the CSV headers. If a field is callable (e.g. anonymous function) then use the
            // source name as the header instead
            foreach($csvColumns as $columnSource => $columnHeader) {
                $headers[] = (!is_string($columnHeader) && is_callable($columnHeader)) ? $columnSource : $columnHeader;
            }

            $fileData .= "\"" . implode("\"{$separator}\"", array_values($headers)) . "\"";
            $fileData .= "\n";
        }

        //Remove GridFieldPaginator as we're going to export the entire list.
        $gridField->getConfig()->removeComponentsByType('GridFieldPaginator');

        $items = $gridField->getManipulatedList();

        $items = $items->filterByCallback(function($item) {
            // The following line modifies what items are filtered. Change this to change what items are filtered
            return $item->EndDate < date('Y-m-d');
        });

        // @todo should GridFieldComponents change behaviour based on whether others are available in the config?
        foreach($gridField->getConfig()->getComponents() as $component){
            if($component instanceof GridFieldFilterHeader || $component instanceof GridFieldSortableHeader) {
                $items = $component->getManipulatedData($gridField, $items);
            }
        }

        foreach($items->limit(null) as $item) {
            if(!$item->hasMethod('canView') || $item->canView($member)) {
                $columnData = array();

                foreach($csvColumns as $columnSource => $columnHeader) {
                    if(!is_string($columnHeader) && is_callable($columnHeader)) {
                        if($item->hasMethod($columnSource)) {
                            $relObj = $item->{$columnSource}();
                        } else {
                            $relObj = $item->relObject($columnSource);
                        }

                        $value = $columnHeader($relObj);
                    } else {
                        $value = $gridField->getDataFieldValue($item, $columnSource);

                        if($value === null) {
                            $value = $gridField->getDataFieldValue($item, $columnHeader);
                        }
                    }

                    $value = str_replace(array("\r", "\n"), "\n", $value);
                    $columnData[] = '"' . str_replace('"', '""', $value) . '"';
                }

                $fileData .= implode($separator, $columnData);
                $fileData .= "\n";
            }

            if($item->hasMethod('destroy')) {
                $item->destroy();
            }
        }

        return $fileData;
    }
}

更改此项以更改导出的项目列表。我将此设置为仅返回过去具有return $item->EndDate < date('Y-m-d'); 的项目。根据需要进行更改。

然后我们将此导出按钮添加到事件模型admin中的网格字段:

EndDate

答案 1 :(得分:1)

这最初是两个答案......

限制字段

您是否看过GridFieldExportButton课程? 构造函数

    /**
 * @param string $targetFragment The HTML fragment to write the button into
 * @param array $exportColumns The columns to include in the export
 */
public function __construct($targetFragment = "after", $exportColumns = null) {
    $this->targetFragment = $targetFragment;
    $this->exportColumns = $exportColumns;
}

所以你应该能够将$exportColumns作为参数传递。

在您的代码中

        if ($gridField) {
        $gridField->getConfig()->addComponent(new GridFieldExportButton("after", ["field1", "field2"]));
    }

或 - 更好的解决方案

您可以在EventPage上定义摘要字段

private static $summary_fields = ["FIeld1", "Field2"];

然后确保你的同花顺,它应该用作田地。

过滤要在CSV中导出的项目

所以在这种情况下,我认为你应该创建一个扩展GridFieldExportButton(可能称为EventPageCSVExportButton或其他东西)的新类,并覆盖你想要的方法。在你的情况下,它可能是generateExportFileData(),只需在循环中检查并排除你不想要的数据。

然后在EventAdmin中使用该新类。

答案 2 :(得分:0)

您是否看过GridFieldExportButton课程? 构造函数

    /**
 * @param string $targetFragment The HTML fragment to write the button into
 * @param array $exportColumns The columns to include in the export
 */
public function __construct($targetFragment = "after", $exportColumns = null) {
    $this->targetFragment = $targetFragment;
    $this->exportColumns = $exportColumns;
}

所以你应该能够将$exportColumns作为参数传递。

在您的代码中

        if ($gridField) {
        $gridField->getConfig()->addComponent(new GridFieldExportButton("after", ["field1", "field2"]));
    }

或 - 更好的解决方案

您可以在EventPage上定义摘要字段

private static $summary_fields = ["FIeld1", "Field2"];

然后确保你的同花顺,它应该用作田地。