制作一个包含两个单独值的表单类型,您可以使用 symfony 4 添加多次 [英] Making a form type with two separate values in it that you can add several times with symfony 4
问题描述
我是 Symfony 的新手,我想使用 symfony 4 做一些事情.为了简化它,假设我有一个购物篮,我可以在其中添加或删除文章并选择我选择的每篇文章的数量.
I'm new to Symfony and I want to do something using symfony 4. To simplify it, let's say for example I have a shopping basket where I can add or remove articles AND select the amount of each article I've chosen.
所以在教义方面我有三个实体:
So on the doctrine side I have three entities :
class Basket {
protected $id;
protected $name;
}
class Article{
protected $id;
protected $name;
}
class Buying {
//ManyToOne
protected $basket;
//ManyToOne
protected $article;
protected $count;
}
我已经通过手工制作 HTML 并使用一些讨厌的 JS 代码完成了这个表单,但现在我想使用 Symfony 4 的表单来制作它.
I've done this form by making the HTML by hand and using some nasty JS code, but now I'd like to make this using Symfony 4's Forms.
我认为最好的方法是为具有两个字段的购买"实体创建我自己的表单类型,其中一个是包含每篇文章的 Select,另一个是 $count 值,然后有可以根据需要添加尽可能多的购买",但我想不出一种方法来做到这一点,而且文档似乎没有涵盖这种情况.
I thought the best way would be to create my own form type for that "Buying" entity which would have two fields, one of them being a Select containing every articles, and the other being the $count value, and then have the possibility to add as many "Buyings" as I want, but I can't think of a way to do this and the documentation don't seem to cover this kind of case.
推荐答案
为此您需要几种表单类型,并且您可能需要稍微调整一下您的实体.这是它的要点:
You'd need a couple of form types for this and you may need to jiggle your entities a bit. Here's the gist of it:
首先,您需要为购买的每件商品及其数量提供一个.EntityType
会给你select
包含您所有的文章,正是您要查找的内容.
First you need one for each individual item purchased and its count. The EntityType
will give you a select
with all your articles, exactly what you are looking for.
// BuyingType.php
$builder->add('article', EntityType::class, ['class' => Article::class]);
$builder->add('count', NumberType::class, [
'constraints' => [
new Count(['min' => 1]),
],
]);
第二个将是 CollectionType
代表整个篮子.
The second one will be a CollectionType
representing the whole basket.
// BasketType.php
$builder->add('basket', CollectionType::class, [
'entry_type' => BuyingType::class,
'allow_add' => true,
'allow_delete' => true,
]);
这篇关于制作一个包含两个单独值的表单类型,您可以使用 symfony 4 添加多次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!