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;
}
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.
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:
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]),
],
]);
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,
]);