如何在 Sonata Admin 中的嵌入式 Admin 类中获取子对象?

2024-01-06

我试图获取并操作与 SonataAdmin 中的 ImageAdmin 类相关的实际对象(使用 Symfony 2.3)。当仅使用 ImageAdmin 类时,这种方法效果很好。但是当 ImageAdmin 嵌入到另一个 Admin 中时,就会出现严重错误。

当您没有嵌入式管理员时,以下是有效的方法:

class ImageAdmin extends Admin {
    protected $baseRoutePattern = 'image';

    protected function configureFormFields(FormMapper $formMapper) {
        $subject = $this->getSubject();
    }
}

但是,当您使用以下命令将图像管理嵌入到父管理中时:

class PageAdmin extends Admin {
    protected function configureFormFields(FormMapper $formMapper) {
        $formMapper->add('image1', 'sonata_type_admin');
    }
}

然后,当您编辑 id 为 10 的父项目并在 ImageAdmin 中调用 getSubject() 时,您会得到Imageid 10!

换句话说, getSubject() 从 URL 中提取 id,然后调用$this->getModelManager()->find($this->getClass(), $id);,它交叉引用 Parent id 和 Image id。哎呀!


所以...我想做的是能够获取当前 ImageAdmin 实例中正在渲染/编辑的实际对象,无论是直接编辑还是通过嵌入表单进行编辑,然后能够使用它。

也许 getSubject() 是错误的树,但我注意到$this->getCurrentChild()从 ImageAdmin::configureFormFields() 调用时返回 false,即使使用 sonata_type_admin 字段类型嵌入 ImageAdmin 也是如此。我很困惑...

不管怎样,我希望能够以某种我忽略的明显方式获得这个物体,这里有人可以帮助启发我!


感谢 Tautrimas 提供的一些想法,但我设法找到了答案:

在 ImageAdmin 中设置:

protected function configureFormFields(FormMapper $formMapper)
{
    if($this->hasParentFieldDescription()) { // this Admin is embedded
        $getter = 'get' . $this->getParentFieldDescription()->getFieldName();
        $parent = $this->getParentFieldDescription()->getAdmin()->getSubject();
        if ($parent) {
          $image = $parent->$getter();
        } else {
          $image = null;
        }
    } else { // this Admin is not embedded
        $image = $this->getSubject();
    }

    // You can then do things with the $image, like show a thumbnail in the help:
    $fileFieldOptions = array('required' => false);
    if ($image && ($webPath = $image->getWebPath())) {
        $fileFieldOptions['help'] = '<img src="'.$webPath.'" class="admin-preview" />';
    }

    $formMapper
        ->add('file', 'file', $fileFieldOptions)
    ;
}

我很快就会将其发布在即将推出的 SonataAdmin 食谱中!

https://github.com/sonata-project/SonataAdminBundle/issues/1546 https://github.com/sonata-project/SonataAdminBundle/issues/1546

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

如何在 Sonata Admin 中的嵌入式 Admin 类中获取子对象? 的相关文章

随机推荐