3

Sonata-admin-bundle 中有一个标准功能,可以使用 exporter 导出数据;但是如何导出当前实体并用它映射ManyToOne实体呢?

基本上我想要的是下载与 ListFields 中定义的完全相同的数据。

UPD:在docs中,只有 todo

UPD2:我找到了一种解决方案,但我认为它不是最好的:

/**
 * Add some fields from mapped entities; the simplest way;
 * @return array
 */
public function getExportFields() {
    $fieldsArray = $this->getModelManager()->getExportFields($this->getClass());

    //here we add some magic :)
    $fieldsArray[] = 'user.superData';
    $fieldsArray[] = 'user.megaData';

    return $fieldsArray;
}
4

1 回答 1

8

我创建了自己的源迭代器,它继承自 DoctrineORMQuerySourceIterator。

如果方法 getValue 中的值是 Traversable 的数组或实例,我调用方法 getValue 递归来获取每个“Many”实体的值:

protected function getValue($value)
{
    //if value is array or collection, creates string 
    if (is_array($value) or $value instanceof \Traversable) {
        $result = [];
        foreach ($value as $item) {
           $result[] = $this->getValue($item);
        }
        $value = implode(',', $result);
    //formated datetime output    
    } elseif ($value instanceof \DateTime) {
        $value = $this->dateFormater->format($value);
    } elseif (is_object($value)) {
        $value = (string) $value;
    }

    return $value;
}

在您的管理类中,您必须覆盖方法 getDataSourceIterator 以返回您自己的迭代器。

这个

$this->getModelManager()->getExportFields($this->getClass());

返回所有实体项。更好的做法是在方法 getExportFields() 中创建导出项目的显式列表

public function getExportFields()
{       
    return [
        $this->getTranslator()->trans('item1_label_text') => 'entityItem1', 
        $this->getTranslator()->trans('item2_label_text') => 'entityItem2.subItem', 
        //subItem after dot is specific value from related entity
....

数组中的键用于导出表头(这里是翻译的)。

于 2014-01-31T16:45:10.850 回答