php 如何在Symfony上修改表单

uinbv5nw  于 2023-02-03  发布在  PHP
关注(0)|答案(2)|浏览(128)

所以我用symfony和twig创建了一个电子商务网站。现在客户可以手动输入他想要的特定产品的数量,但我希望这个数量不超过我们的库存。所以,如果我们有5把椅子,我希望他在1和5之间选择。为此,我创建了一个下拉列表:

<div class="field select-box">
    <select name="quantity" data-placeholder="Select your quantity">

        {% for i in 1..produit.stock %}
        <option value="{{ i }}">{{ i }}</option>

        {% endfor %}
    </select>
</div>

我想使用所选的值将其放入表单中,或者找到另一种方法来设置所需的数量,而不使用表单,甚至只是更改表单的外观,因为现在它只接受输入。我应该生成另一个表单吗?
希望我说的够清楚。
下面是我的formType的外观:

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

下面是控制器的一些代码,用于创建购物车、添加产品和所有相关信息(数量、所属用户、日期)

if(is_null($updateContenuPanier)) {
            $contenuPanier = new ContenuPanier();
            $contenuPanier->setDate(new Datetime());
            $contenuPanier->setPanier($panier);
            $contenuPanier->setProduit($produit);
            $contenuPanier->setQuantite($request->get("contenu_panier")["quantite"]);
        }
bjg7j2ky

bjg7j2ky1#

这可以通过ChoiceType来实现,您只需要确定最大允许值并配置相应的选项。

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

我 * 几乎 * 肯定您仍然需要验证提交的数量在处理表单提交的控制器操作中仍然有效。

zte4gxcn

zte4gxcn2#

请看表单输入类型here。您可以指定选项。该字段会因产品而异(产品A = 5个库存,产品B = 10个库存)。
我怀疑选择字段在这里是最好的,也许只是使用一个简单的<input type="number">,但这只是我的想法。

$builder->add('quantite', ChoiceType::class, [
    'choices' => [ // instead of this, do a loop to create your options
        'Apple' => 1,
        'Banana' => 2,
        'Durian' => 3,
    ],
)
    ```

相关问题