New in Symfony 5.3: Form Field Sorting

Symfony 5.3 is backed by JoliCode. JoliCode is a team of passionate developers and open-source lovers, with a strong expertise in PHP & Symfony technologies. They can help you build your projects using state-of-the-art practices.

Contributed by
Yonel Ceruto
in #40690.

Symfony forms render their fields in the same order that you define them. This might cause issues when adding/removing fields dynamically in complex forms (e.g. a field added via form events can end up being rendered after the form submit button).

That’s why in Symfony 5.3 you can sort form fields to control the order in which they are rendered. To do so, use the new priority option, which is a positive or negative integer with a default value of 0. Fields with higher priorities are rendered first (and fields with same priority are rendered in their original order):

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
// src/Form/Type/TaskType.php
namespace App\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\DateType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;

class TaskType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options): void
    {
        $builder
            ->add('task', TextType::class, ['priority' => 150])
            ->add('dueDate', DateType::class)
            ->add('save', SubmitType::class, [
                'priority' => $options['show_first'] ? 1000 : -1000,
            ])
        ;
    }
}
Help the Symfony project!

As with any Open-Source project, contributing code or documentation is the most common way to help, but we also have a wide range of sponsoring opportunities.

Comments

Very nice ! This was a very awaited feature 😍
Oh nice, thanks for this one !
Awesome
That's great, Thank you 🥳🥳🥳
That's so funny. Just today I searched for that feature, because I have a multi form input for a SINGLE_TABLE inheritance entity. And my submit button was suddenly in the middle of the form.

Now it works like a charm. Thank you much!
Chinese translation of this article (本文中文翻译): https://phpzlc.gitee.io/blog/12.html
Login with SymfonyConnect to post a comment