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

时间:2016-12-18 20:17:17

标签: forms symfony

我有简单的格式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',
        ]);
    }
}

并从MyForm2

继承表格MyForm1
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按钮。我怎样才能改变元素的顺序?我知道我可以删除并再次添加此按钮。或者为模板中的每个元素调用渲染函数。但我想只为元素设置渲染索引。假设它将花费更少的时间。有可能吗?

由于

2 个答案:

答案 0 :(得分:3)

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

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

答案 1 :(得分:3)

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