在Sonata Admin Bundle中处理多个例外情况

时间:2012-10-17 06:11:56

标签: symfony sonata-admin

我有2个表与ManyToOne关系。

class Parent
{
  /**
     * @var integer $id
     *
     * @ORM\Column(name="id", type="integer", nullable=false)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    private $id;

    /**
     *
     * @ORM\OneToMany(cascade={"persist"},targetEntity="Child", mappedBy="parent")
     */

    private $child;

  // getters and setters
}

class child{

     /**
     * @var integer $id
     *
     * @ORM\Column(name="id", type="integer", nullable=false)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    private $id;

    /**
     * @var Parent
     *
     * @ORM\ManyToOne(cascade={"persist"},targetEntity="Parent")
     * @ORM\JoinColumns({
     * @ORM\JoinColumn(name="parent_id", referencedColumnName="id")
     * })
     *
     */
    private $parent;

   // getters and setters

}
  1. 现在如何处理父表的一行被删除时生成的异常?

  2. 如何在Sonata Admin Generator表单中显示消息?

  3. 提前致谢

1 个答案:

答案 0 :(得分:3)

1:现在如何处理父表的一行被删除时生成的异常?

Sol:以下步骤可以解决问题

  1. OverRide由sonata admin bundle提供的CRUDController。确保重写的CRUDController与原始CRUDController位于同一位置。 ie.YourProject / AdminBundle /控制器/ CRUDController.php

  2. 将deleteAction和batchActionDelete从原始控制器复制到Overridden控制器。即

    public function deleteAction($ id)     {

        $id     = $this->get('request')->get($this->admin->getIdParameter());
    
        $object = $this->admin->getObject($id);
    
       if (!$object) {
            throw new NotFoundHttpException(sprintf('unable to find the object with id : %s', $id));
        }
    
        if (false === $this->admin->isGranted('DELETE', $object)) {
            throw new AccessDeniedException();
        }
    
        if ($this->getRequest()->getMethod() == 'DELETE') {
    
         try {
    
                $this->admin->delete($object);
    
                $this->get('session')->setFlash('sonata_flash_success', 'flash_delete_success');
    
            } catch (\Exception $e) {
    
                $this->get('session')->setFlash('sonata_flash_error', sprintf('Cannot Delete because it has Dependeny'));
            }
             return new RedirectResponse($this->admin->generateUrl('list'));
           }
    
        return $this->render($this->admin->getTemplate('delete'), array(
            'object' => $object,
            'action' => 'delete'
        ));
    }
    
  3. try catch块应该处理其余部分。

  4. 2.如何在Sonata Admin Generator表单中显示消息?

    sol:缓存块中的消息将以奏鸣曲管理包形式显示

    try {
    
                        $this->admin->delete($object);
    
                        $this->get('session')->setFlash('sonata_flash_success', 'flash_delete_success');
    
                    } catch (\Exception $e) {
    
                        $this->get('session')->setFlash('sonata_flash_error', sprintf('Cannot Delete because it has Dependeny'));
                    }
    

    注意。确保导入所有必要的文件