so I'm creating an e-commerce website using symfony and twig. Right now The client can enter manually the quantity he wants of a specific product, but i want that quantity to not exceed the stock we have of that product. So for example if we have 5 chairs, i want him to choose between 1 and 5. For that i created a dropdown :
<div >
<select name="quantity" data-placeholder="Select your quantity">
{% for i in 1..produit.stock %}
<option value="{{ i }}">{{ i }}</option>
{% endfor %}
</select>
</div>
I want to use the selected value to put it inside a form,, or maybe find another way to set the quantity asked without using the form or even just change the way the form looks because right now it only takes input. Should i generate another form ?
Hopefully i was clear.
Here's what my formType looks like :
class ContenuPanierType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$builder->add('quantite');
}
public function configureOptions(OptionsResolver $resolver): void
{
$resolver->setDefaults([
'data_class' => ContenuPanier::class,
]);
}
}
and here's a bit of code from the controller that creates a cart, add the products and all the information regarding it (quantity, user it belongs to, date)
if(is_null($updateContenuPanier)) {
$contenuPanier = new ContenuPanier();
$contenuPanier->setDate(new Datetime());
$contenuPanier->setPanier($panier);
$contenuPanier->setProduit($produit);
$contenuPanier->setQuantite($request->get("contenu_panier")["quantite"]);
}
CodePudding user response:
Have a look at Form Input Types here. You can specify the options. This field in particular will vary for each product (Product A = 5 in stock, Product B = 10 in stock).
I doubt a select field is the best here, maybe just use a simple <input type="number">
, but that's just my thought on this.
$builder->add('quantite', ChoiceType::class, [
'choices' => [ // instead of this, do a loop to create your options
'Apple' => 1,
'Banana' => 2,
'Durian' => 3,
],
)
```
CodePudding user response:
This can be done with the ChoiceType
. You just need to determine your maximum allowed value and configure the appropriate options.
public function buildForm(FormBuilderInterface $builder, array $options): void
{
// access the entity
$entity = $builder->getData();
// your custom logic to determine the maximum allowed integer value based on $entity
$max = $entity->getStockOnHandMethodName();
$builder->add('quantite', ChoiceType::class, [
'choices' => range(1, $max),
'choice_label' => function ($choice) {
// use the value for the label text
return $choice;
},
// prevent empty placeholder option
'placeholder' => false,
]);
}
I'm almost certain you will still need to verify that the submitted quantity is still valid in your controller action which handles the form submission.