Symfony 2 - rearrange form fields

2020-07-10 00:14发布

In our Symfony2 project we have a very complex structure for forms with embedded forms.... Now we got the requirement to bring the output of the form in an specific order.

And here is the problem: We use the form_widget(form) and now we are looking for a solution in the object (e.g. via annotations) or the formbuilder to move a specific field to the end of the form. in symfony 1.4 it was the widget-movefield() function, i guess...

Thx...

8条回答
smile是对你的礼貌
2楼-- · 2020-07-10 01:00

Had same issue today with the form elements ordering.

Ended up with a trait that will override finishView method and reorder items in children property of a FormView:

trait OrderedTrait
{
    abstract function getFieldsOrder();

    public function finishView(FormView $view, FormInterface $form, array $options)
    {
        /** @var FormView[] $fields */
        $fields = [];
        foreach ($this->getFieldsOrder() as $field) {
            if ($view->offsetExists($field)) {
                $fields[$field] = $view->offsetGet($field);
                $view->offsetUnset($field);
            }
        }

        $view->children = $fields + $view->children;

        parent::finishView($view, $form, $options);
    }
}

Then in type implement getFieldsOrder method:

use OrderedTrait;

function getFieldsOrder()
{
    return [
        'first',
        'second',
        'next',
        'etc.',
    ];
}
查看更多
Deceive 欺骗
3楼-- · 2020-07-10 01:10

There's no need to "reorder" fields. All you need to do is to call form_label and/or form_widget for each field individually. Assuming you use Twig you could, for example, do:

<div>{{ form_label(form.firstName) }}</div>
<div>{{ form_widget(form.firstName) }}</div>

<div>{{ form_label(form.lastName) }}</div>
<div>{{ form_widget(form.lastName) }}</div>
查看更多
登录 后发表回答