如何更改symfony表单元素的顺序?

xoshrz7s  于 2023-05-01  发布在  其他
关注(0)|答案(3)|浏览(125)

我有一个简单的表单MyForm1

class MyForm1 extends Symfony\Component\Form\AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        parent::buildForm($builder, $options);

        $builder->add('field1', TextType::class, [
            'label' => 'Field1'
        ])

        $builder->add('save', SubmitType::class, [
            'label' => 'Save',
        ]);
    }
}

并形成从MyForm1继承的MyForm2

class MyForm2 extends MyForm1
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        parent::buildForm($builder, $options);

        $builder->add('field2', TextType::class, [
            'label' => 'Field2'
        ])
    }
}

和模板

{{ form(form) }}

当我显示MyForm2时,save按钮显示在field2之前。如何更改元素的顺序?我知道我可以删除并再次添加此按钮。或者为模板中的每个元素调用render函数。但我只想为元素设置渲染索引。假设它会花更少的时间。这可能吗?
谢谢

mzillmmw

mzillmmw1#

在我看来,表单字段的顺序与视图有关,而与模型无关。因此,您应该在视图中逐个字段地手动显示表单。

{{ form_start(form) }}
   {{ form_row(form.field1)
   {{ form_row(form.field2)
   {{ form_row(form.save)
{{ form_end(form) }}
des4xlb0

des4xlb02#

class MyForm1 extends Symfony\Component\Form\AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        parent::buildForm($builder, $options);

        $this->buildFields($builder, $options);

        $builder->add('save', SubmitType::class, [
            'label' => 'Save',
        ]);
    }

    public function buildFields(FormBuilderInterface $builder, array $options)
    {
        $builder->add('field1', TextType::class, [
            'label' => 'Field1'
        ])
    }
}

class MyForm2 extends MyForm1
{
    // You can actually completely skip this method
    /*public function buildForm(FormBuilderInterface $builder, array $options)
    {
        parent::buildForm($builder, $options);
    }*/

    public function buildFields(FormBuilderInterface $builder, array $options)
    {
        parent::buildFields(FormBuilderInterface $builder, array $options);
        $builder->add('field2', TextType::class, [
            'label' => 'Field2'
        ]);
    }
}

如果需要,还可以以相同的方式添加buildSubmit

sy5wg1nm

sy5wg1nm3#

由于Symfony 5.3,您可以在任何表单字段上使用priority属性来驱动呈现顺序。

相关问题