映射实体的 SonataAdminBundle Exporter 问题 [英] SonataAdminBundle Exporter issue with mapped entities

查看:10
本文介绍了映射实体的 SonataAdminBundle Exporter 问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

There is a standard feature in sonata-admin-bundle to export data using exporter; But how to make export current entity AND mapped ManyToOne entity with it?

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

Basically what I want, is to download exactly same data as defined in ListFields.

UPD:在 docs 中,只有待办事项

UPD: In docs, there is only todo

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

UPD2: I've found one solution, but I do not think it is the best one:

/**
 * 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;
}

推荐答案

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

I created own source iterator inherited from DoctrineORMQuerySourceIterator.

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

If value in method getValue is array or instance of Traversable i call method getValue recursive to get value for each "Many" entity:

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 以返回您自己的迭代器.

In your admin class you must override method getDataSourceIterator to return your own iterator.

这个

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

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

returns all entity items. Better practice is to create explicit list of exported items in method 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
....

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

Key in array is used for export table headers (here is traslated).

这篇关于映射实体的 SonataAdminBundle Exporter 问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆