SonataAdminBundle Exporter 与映射实体的问题

2023-12-11

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

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

UPD: In docs,只有待办事项

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

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

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

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

$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
....

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

SonataAdminBundle Exporter 与映射实体的问题 的相关文章

随机推荐