2016-01-13 62 views
1

這是我的實體示例代碼。Symfony2 @UniqueEntity自定義奏鳴曲管理類

EntityOne.php

//.... 
use Symfony\Component\Validator\Constraints as Assert; 
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity; 
//.... 

/** 
* EntityOne 
* 
* @ORM\Table() 
* @ORM\Entity(repositoryClass="AppBundle\Entity\EntityOneRepository") 
* @UniqueEntity(
*  fields={"entityTwo", "number"}, 
*  errorPath="number", 
*  message="A entityTwo with this number already exists." 
*) 
*/ 
class EntityOne 
{ 

    //.... 

    /** 
    * @ORM\ManyToOne(targetEntity="EntityTwo", inversedBy="entityOne") 
    * @ORM\JoinColumn(name="entitytwo_id", referencedColumnName="id") 
    */ 
    protected $entityTwo; 

    /** 
    * @var integer 
    * 
    * @ORM\Column(name="number", type="integer") 
    * 
    * @Assert\NotBlank() 
    */ 
    private $number; 

    //.... 

} 

EntityTwo.php

/** 
* EntityTwo 
* 
* @ORM\Table() 
* @ORM\Entity(repositoryClass="AppBundle\Entity\EntityTwoRepository") 
*/ 
class EntityTwo 
{ 

    //.... 

    /** 
    * 
    * @ORM\OneToMany(targetEntity="EntityOne", mappedBy="entityTwo", cascade={"persist"}, orphanRemoval=true) 
    * @ORM\OrderBy({"number" = "ASC"}) 
    */ 
    protected $entityOne; 

    /** 
    * @var integer 
    * 
    * @ORM\Column(name="totals", type="integer") 
    * 
    * @Assert\NotBlank() 
    */ 
    private $totals; 

    //.... 

} 

我使用SonataAdminBundle與定期管理類的實體的一切工作正常。

@UniqueEntity的問題在另一個地方。 在不同的管理員類中,創建一個EntityOne的記錄編號,該編號取決於EntityOne中某個字段的值。

要做到這一點,我做如下:

EntityTwoAdmin.php

class EntityTwoAdmin extends Admin { 

    //.... 

    protected $formOptions = array(
     'cascade_validation' => true   
    ); 

    //.... 

    public function preUpdate($entityTwo) { 

     $numTotals = $entityTwo->getTotals(); 
     $numEntityOneExist = $entityTwo->getEntityOne()->count(); 

     for ($i = $numEntityOneExist; $i <= $numTotals; $i++) { 

      $entityOneNew = new \AppBundle\Entity\EntityOne; 

      $entityOneNew->setNumber($i); 

      $entityTwo->addEntityOne($entityOneNew); 
     } 

    } 
} 

這裏記錄創建不考慮約束驗證。

我不知道我可能會丟失什麼,但肯定是我需要修復的。

有什麼想法?

回答

0

我設法解決它,我不清楚它是最好的方法還是不遵循symfony的最佳實踐。

我分享這裏,對於那些誰可以幫助:

EntityTwoAdmin.php

public function preUpdate($entityTwo) { 

    $numTotals = $entityTwo->getTotals(); 
    $numEntityOneExist = $entityTwo->getEntityOne()->count(); 

    for ($i = $numEntityOneExist; $i <= $numTotals; $i++) { 

     $entityOneNew = new \AppBundle\Entity\EntityOne; 
     $entityOneNew->setNumber($i); 
     $entityOneNew->setEntityTwo($entityTwo); 

     $validator = $this->getConfigurationPool()->getContainer()->get('validator'); 
     $errors = $validator->validate($entityOneNew); 

     if (count($errors) == 0) { 

      $entityTwo->addEntityOne($entityOneNew); 

     } 
    } 

} 
相關問題