不清楚Symfony表单错误“此值已被使用”

时间:2016-02-11 10:24:23

标签: forms symfony

我使用Symfony 2.7.3并且我有以下表单(“app_cargo_source”):

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('country', 'choice', [
            'choices' => $this->worldManager->getCountriesByRegionIds([1, 2]),
            'choice_label' => 'name',
            'choice_value' => 'id',
            'label' => false,
            // *this line is important* see docs for choice type
            'choices_as_values' => true
        ])

       // ...
    ;

    // ...
}

表单以另一种形式使用(app_cargo):

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('source', 'app_cargo_source')
        // ...
    ;

    // ...
}
第一种形式的

“choices”字段是WorldCountry对象的数组,它们是按区域id从数据库中选择的。以下是Profiler中阵列的图片:

enter image description here

WorldCountry和WorldRegion具有单向的ManyToOne关系。

问题,当我在国家/地区字段中选择国家/地区并提交表单时,我会收到国家/地区字段的以下错误:

enter image description here

为什么会发生这种情况,为什么Symfony会尝试为区域分配值?

P.S。如果需要更多信息,请告诉我。

1 个答案:

答案 0 :(得分:1)

右键!似乎问题在于WorldCountry实体中区域字段的唯一性。我的WorldRegion实体正在关注:

/**
 * WorldRegion
 *
 * @ORM\Table(name="world_region")
 * @ORM\Entity(repositoryClass="AppBundle\Repository\WorldRegionRepository")
 *
 * @UniqueEntity(fields={"code"}, message="Region code must be unique")
 */
class WorldRegion
{
    /**
     * @var integer
     *
     * @ORM\Column(name="region_id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     * @Assert\NotBlank()
     *
     * @ORM\Column(name="region_code", type="string", length=5,
     *  unique = true, nullable=false)
     */
    protected $code;

    // ...
}

和WorldCountry:

/**
 * WorldCountry
 *
 * @ORM\Table(name="world_country")
 * @ORM\Entity(repositoryClass="AppBundle\Repository\WorldCountryRepository")
 *
 * @UniqueEntity(fields={"iso2"})
 * @UniqueEntity(fields={"iso3"})
 * @UniqueEntity(fields={"region"}) // This line should be removed!
 */
class WorldCountry
{
    /**
     * @var integer
     *
     * @ORM\Column(name="country_id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var WorldRegion
     *
     * @ORM\ManyToOne(targetEntity="WorldRegion",
     *  cascade={"all"}
     * )
     * @ORM\JoinColumn(name="region_id", referencedColumnName="region_id")
     */
    protected $region;

    // ...
}

如所见WorldCountry对区域字段有唯一约束。在这种情况下,它是逻辑错误。因为ManyToOneWorldCountry的数据库表中说明了国家/地区是唯一的,但是地区 - 不是。但我使用@UniqueEntity声称区域也应该是唯一的。因此,应从@UniqueEntity(fields={"region"})实体中删除注释WorldCountry

P.S。如果我能改进我的答案,请告诉我。

相关问题