我在 SonataAdminBundle 中有几个实体(问题、文章、新闻),我想将标签连接到这些实体。我通过每个实体与标签实体的多对多关系来实现它。但为此需要创建多个中间连接表,这很不方便。
我发现了一个 bundle FPNTagBundle ,它允许使用额外字段 ResourceType 指定联结表。这正是我所需要的,我在另一个项目中也做过同样的事情。
但是 FPNTagBundle 通过单独的 TagManager 建立通信,并且在 SonataAdmin 中不起作用。
你给我什么建议?如何实现这个任务?
也许不用担心,并留下几个单独的联结表?但是,我仍然会为其他六个实体进行标记...而且我担心在所有标记实体中按标记进行搜索将很难做到 - 它将跨多个表运行。
最佳答案
解决方法在 Saving hooks .
/**
* @return FPN\TagBundle\Entity\TagManager
*/
protected function getTagManager() {
return $this->getConfigurationPool()->getContainer()
->get('fpn_tag.tag_manager');
}
public function postPersist($object) {
$this->getTagManager()->saveTagging($object);
}
public function postUpdate($object) {
$this->getTagManager()->saveTagging($object);
}
public function preRemove($object) {
$this->getTagManager()->deleteTagging($object);
$this->getDoctrine()->getManager()->flush();
}
我的管理类:
protected function configureFormFields(FormMapper $formMapper)
{
$tags = $this->hasSubject()
? $this->getTagManager()->loadTagging($this->getSubject())
: array();
$formMapper
// other fields
->add('tags', 'entity', array('class'=>'AppBundle:Tag', 'choices' => $tags, 'multiple' => true, 'attr'=>array('style'=>'width: 100%;')))
;
}
还有一个known bug在 SonataAdminBundle 中 - 当执行批量删除(在 ListView 中)时,钩子(Hook) preRemove/postRemove 不会运行。我们需要扩展标准 CRUD Controller :
namespace App\AppBundle\Controller;
use Sonata\AdminBundle\Controller\CRUDController as Controller;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Sonata\AdminBundle\Datagrid\ProxyQueryInterface;
class CRUDController extends Controller
{
public function batchActionDelete(ProxyQueryInterface $query)
{
if (method_exists($this->admin, 'preRemove')) {
foreach ($query->getQuery()->iterate() as $object) {
$this->admin->preRemove($object[0]);
}
}
$response = parent::batchActionDelete($query);
if (method_exists($this->admin, 'postRemove')) {
foreach ($query->getQuery()->iterate() as $object) {
$this->admin->postRemove($object[0]);
}
}
return $response;
}
}
关于symfony - 在 Sonata Admin Bundle 中使用标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25323023/