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

cap*_*ica 5 symfony sonata-admin

我正在尝试获取和操纵与SonataAdmin中的ImageAdmin类相关的实际对象(使用Symfony 2.3).当ImageAdmin类是唯一使用的类时,这很好.但是当ImageAdmin嵌入另一个管理员时,它出现了可怕的错误.

当您没有嵌入式管理员时,这是有效的:

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

    protected function configureFormFields(FormMapper $formMapper) {
        $subject = $this->getSubject();
    }
}
Run Code Online (Sandbox Code Playgroud)

但是当您使用以下方法在ParentAdmin中嵌入ImageAdmin时:

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

然后,当您编辑ID为10的父项并在ImageAdmin中调用getSubject()时,您将获得ID为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也是如此.我很困惑......

无论如何,我希望有可能以一种我忽略的显而易见的方式抓住这个对象,这里有人可以帮助启发我!

cap*_*ica 13

感谢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)
    ;
}
Run Code Online (Sandbox Code Playgroud)

我很快就会在即将推出的SonataAdmin烹饪书中发布这个!

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