【问题标题】:Symfony validation constraints annotations not workingSymfony 验证约束注释不起作用
【发布时间】:2021-08-11 15:26:51
【问题描述】:

我正在尝试使用注释进行 Symfony 表单验证,但我无法让它工作。无论约束如何,表单始终报告为有效。我在 PHP 7.3 上运行,带有教义/注释 1.13、symfony/validator 5.1 和 Symfony 5.1.5。

这是基本设置:

ProductionDependentCost.php

...
use Symfony\Component\Validator\Constraints as Assert;
...
    /**
     * @var float
     * @ORM\Column(type="float")
     * @Assert\NotNull
     * @Assert\Positive
     */
    private $costPerKW = 0;
...

ProductionDependentCostController.php

...
/**
     * @Route("/plant/{id}/productiondependentcosts", name="update_plant_production_dependent_costs", methods={"POST"})
     */
    public function updatePlantProductionDependentCosts(Plant $plant, Request $request): JsonResponse
    {
        $this->denyAccessUnlessGranted('view', $plant);
        $form = $this->createForm(ProductionDependentCostCollectionType::class, $plant, ['csrf_token_id' => 'vue-token']);
        $form->handleRequest($request);
        if ($form->isSubmitted() && $form->isValid()) {
            $this->em->flush();

            return $this->json('saved!');
        } elseif ($form->isSubmitted()) {
            return $this->json(ErrorUtil::parseErrors($form->getErrors(true)), Response::HTTP_BAD_REQUEST);
        }

        return $this->json('this should not be reached!', Response::HTTP_BAD_REQUEST);
    }
...

config/packages/framework.yaml

framework:
    ...
    validation:
      {
          enable_annotations: true
      }

我有更多的注释约束,但在这个例子中只包括了一个,以免使代码sn-p膨胀。无论我在表单中输入什么(例如 costPerKW 为 -1000),它都会返回“已保存!”。我到处寻找,但似乎找不到解决方案。真希望有人知道这个问题的答案。

表单在 Plant.php 的映射集合字段上使用 CollectionType。集合条目是 ProductionDependentCost.php 的实体,对应的 FormType 使用 costPerKW 的简单映射字段。

【问题讨论】:

  • 您是否使用 javascript 来发布数据?
  • @DirkJ.Faber 是的,但在 phpunit 测试中也是如此

标签: php symfony symfony-forms symfony-validator


【解决方案1】:

我找到了解决问题的方法。 Symfony Forms 不会自动验证集合中的实体。由于我的 ProductionDependentCost 是表单内集合的一部分,因此我必须在我的集合字段中添加“有效”约束:

选项 1:

class Plant
{
...
     /**
     * @var ProductionDependentCost[]|Collection
     * @ORM\OneToMany(targetEntity=ProductionDependentCost::class, mappedBy="plant", orphanRemoval=true, cascade={"persist",
     * "remove"})
     * @Assert\Valid
     */
    private $productionDependentCosts;
...
}

选项 2:

class ProductionDependentCostCollectionType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('productionDependentCosts', CollectionType::class,
            [
                ...
                'constraints' => [
                    new Valid(),
                ],
            ]);
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => Plant::class,
        ]);
    }
}

这将单独验证每个集合实体。

【讨论】:

    猜你喜欢
    • 2015-01-19
    • 2012-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-17
    • 1970-01-01
    • 2013-01-15
    • 1970-01-01
    相关资源
    最近更新 更多