首页 > 解决方案 > Symfony 断言回调在管理类中不起作用

问题描述

@Assert\Callback不起作用,我不明白为什么,我做错了什么?我想检查该字段中是否至少有一个值competitionTypes。在项目的其他实体中,验证有效,但不适用于该实体。

实体:

/**
 * @ORM\Table(name="experience_in_competition")
 * @ORM\Entity()
 * @Gedmo\SoftDeleteable(fieldName="deletedAt", timeAware=false)
 */
class ExperienceInCompetition
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @var string
     * @Assert\NotBlank(
     *     message="value is invalid(field must be non empty)",
     *     groups={"KNS-2020-2"}
     *     )
     *
     * @ORM\Column(name="year", type="string", nullable=true)
     */
    protected $year;

    /**
     * @ORM\ManyToMany(targetEntity="NKO\OrderBundle\Entity\Application\KNS\SecondStage2020\CompetitionType")
     * @ORM\JoinTable(name="application_competition_type",
     *     joinColumns={@ORM\JoinColumn(name="application_id", referencedColumnName="id", onDelete="CASCADE")},
     *         inverseJoinColumns={@ORM\JoinColumn(name="competition_type_id", referencedColumnName="id")}
     * )
     */
    protected $competitionTypes;

    public function __construct(string $year)
    {
        $this->setYear($year);
        $this->competitionTypes = new ArrayCollection();
    }

    /**
     * @Assert\Callback
     */
    public function isValidCompetitionType(ExecutionContextInterface $context, $payload)
    {
        if ($this->getCompetitionType()->isEmpty()) {
            $context->buildViolation('value is invalid(field must be non empty)')
                ->atPath('competitionTypes')
                ->addViolation();
        }
    }
}

管理员类:

class ExperienceInCompetitionAdmin extends AbstractAdmin
{
    protected function configureFormFields(FormMapper $formMapper)
    {
        $formMapper
            ->add('year', TextType::class, [
                'label' => 'Год',
                'required' => false,
                'disabled' => true
            ])
            ->add('competitionType', EntityType::class, [
                'class' => CompetitionType::class,
                'label' => 'Конкурс',
                'query_builder' => function (EntityRepository $er) {
                    return $er->createQueryBuilder('u')
                        ->andWhere('u.code = :name')
                        ->setParameters(['name' => ApplicationTypes::KNS_APPLICATION_SECOND_STAGE_2020]);
                },
                'multiple' => true,
            ])
        ;
    }
}

来自该实体的值未经过验证,我尝试将组插入@Assert\Callbackas for field $year,但没有帮助。这种条目也无济于事:

 * @Assert\Count(
 *     min="1",
 *     minMessage="value is invalid(field must be non empty)",
 *     groups={
 *         "KNS-2020-2"
 *     }
 * )

标签: symfonysonata-adminsymfony-3.4symfony-validator

解决方案


推荐阅读