【发布时间】: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