这是我的实体示例代码。
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 :(得分: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);
}
}
}