好的,我最终设法让这个工作。我无法从使用$parentAssociationMapping
CommentAdmin 类的属性中受益,因为评论的父实体是 Thread 实体的具体实例,而在这种情况下,父“管理员”类是一个故事(通过故事线)。另外,当我对其他类型的实体实施评论时,这将需要保持动态。
首先,我必须配置我的 StoryAdmin(以及任何其他将 CommentAdmin 作为子级的管理类)来调用 addChild 方法:
acme_story.admin.story:
class: Acme\Bundle\StoryBundle\Admin\StoryAdmin
tags:
- { name: sonata.admin, manager_type: orm, group: content, label: Stories }
arguments: [null, Acme\Bundle\StoryBundle\Entity\Story, AcmeStoryBundle:StoryAdmin]
calls:
- [ addChild, [ @acme_comment.admin.comment ] ]
- [ setSecurityContext, [ @security.context ] ]
这允许我从故事管理员链接到子管理员部分,在我的情况下是从侧面菜单,如下所示:
protected function configureSideMenu(MenuItemInterface $menu, $action, Admin $childAdmin = null)
{
// ...other side menu stuff
$menu->addChild(
'comments',
array('uri' => $admin->generateUrl('acme_comment.admin.comment.list', array('id' => $id)))
);
}
然后,在我的 CommentAdmin 类中,我必须根据父对象(例如本例中的 StoryThread)访问相关的 Thread 实体并将其设置为过滤器参数。如果父实体与父管理员相同,这基本上是使用$parentAssociationMapping
属性自动完成的,如果您不使用继承映射,很可能会发生这种情况。这是来自 CommentAdmin 的所需代码:
/**
* @param \Sonata\AdminBundle\Datagrid\DatagridMapper $filter
*/
protected function configureDatagridFilters(DatagridMapper $filter)
{
$filter->add('thread');
}
/**
* @return array
*/
public function getFilterParameters()
{
$parameters = parent::getFilterParameters();
return array_merge($parameters, array(
'thread' => array('value' => $this->getThread()->getId())
));
}
public function getNewInstance()
{
$comment = parent::getNewInstance();
$comment->setThread($this->getThread());
$comment->setAuthor($this->securityContext->getToken()->getUser());
return $comment;
}
/**
* @return CommentableInterface
*/
protected function getParentObject()
{
return $this->getParent()->getObject($this->getParent()->getRequest()->get('id'));
}
/**
* @return object Thread
*/
protected function getThread()
{
/** @var $threadRepository ThreadRepository */
$threadRepository = $this->em->getRepository($this->getParentObject()->getThreadEntityName());
return $threadRepository->findOneBy(array(
$threadRepository->getObjectColumn() => $this->getParentObject()->getId()
));
}
/**
* @param \Doctrine\ORM\EntityManager $em
*/
public function setEntityManager($em)
{
$this->em = $em;
}
/**
* @param \Symfony\Component\Security\Core\SecurityContextInterface $securityContext
*/
public function setSecurityContext(SecurityContextInterface $securityContext)
{
$this->securityContext = $securityContext;
}