我有两个实体类:产品和价格。产品价格很高。这些关系被定义为(只显示了相关代码):
Product.php
public function __construct()
{
$this->prices = new ArrayCollection();
}
/**
* @var Collection|Price[]
* @ORM\OneToMany(targetEntity="Price", mappedBy="product", cascade={"persist", "remove"})
*/
private Collection $prices;
/**
* @return Collection|Price[]
*/
public function getPrices()
{
return $this->prices;
}
/**
* @param Collection|Price[] $prices
*/
public function setPrices(Collection $prices) : void
{
$this->prices = $prices;
}Price.php
/**
* @ORM\ManyToOne(targetEntity="Product", inversedBy="prices")
*/
private Product $product;
public function getProduct() : Product
{
return $this->product;
}
public function setProduct(?Product $product) : self
{
$this->product = $product;
return $this;
}ProductType::buildForm()
$builder
->add('prices', EntityType::class, [
'class' => Price::class,
'multiple' => true,
'constraints' => [
new NotNull(),
],
]);ProductController::add()
public function add(Request $request, EntityManagerInterface $manager) : Response
{
$form = $this->container->get('form.factory')->createNamed('', ProductType::class);
$form->handleRequest($request);
if (! $form->isSubmitted() || !$form->isValid()) {
return $this->handleView($this->view($form, Response::HTTP_BAD_REQUEST));
}
/** @var Product $product */
$product = $form->getData();
$manager->persist($product);
$manager->flush();
return $this->respond($product, Response::HTTP_CREATED);
}请求JSON
{
"name": "added",
"prices": [
{
"currency": "EUR",
"value": 100
},
{
"currency": "PLN",
"value": 400
}
],
"description": "test desc"
}JSON响应
{
"code": 400,
"message": "Validation Failed",
"errors": {
"children": {
"name": {},
"description": {},
"prices": {
"errors": [
"Not valid"
]
}
}
}
}具体而言,问题在于价格--通过空价格数组可以毫无错误地创建产品。我用FOSRestBundle。
我在谷歌上搜索了很多小时,但没有成功。我刚接触过Symfony,所以我很可能错过了一些显而易见的东西:)
发布于 2021-08-31 19:37:55
问题出现在ProductType类中。
而不是:
$builder
->add('prices', EntityType::class, [
'class' => Price::class,
'multiple' => true,
'constraints' => [
new NotNull(),
],
]);应该用
$builder
->add('prices', CollectionType::class, [
'entry_type' => PriceType::class,
'allow_add' => true,
'constraints' => [
new NotNull(),
],
]);答案找到这里
https://stackoverflow.com/questions/68968200
复制相似问题