Skip to content

[Form] Add FormFlow for multistep forms management #60212

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: 7.4
Choose a base branch
from

Conversation

yceruto
Copy link
Member

@yceruto yceruto commented Apr 13, 2025

Q A
Branch? 7.4
Bug fix? no
New feature? yes
Deprecations? no
Issues -
License MIT

Alternative to

Inspired on @silasjoisten's work and @craue's CraueFormFlowBundle, thank you!

FormFlow

This PR introduces FormFlow, a kind of super component built on top of the existing Form architecture. It handles the definition, creation, and handling of multistep forms, including data management, submit buttons, and validations across steps.

formflow

Demo app: https://github.com/yceruto/formflow-demo

AbstractFlowType

Just like AbstractType defines a single form based on the FormType, AbstractFlowType can be used to define a multistep form based on FormFlowType.

class UserSignUpType extends AbstractFlowType
{
    /**
     * @param FormFlowBuilderInterface $builder
     */
    public function buildForm(FormBuilderInterface $builder, array $options): void
    {
        $builder->addStep('personal', UserSignUpPersonalType::class);
        $builder->addStep('professional', UserSignUpProfessionalType::class);
        $builder->addStep('account', UserSignUpAccountType::class);

        $builder->add('navigator', FlowNavigatorType::class);
    }

    public function configureOptions(OptionsResolver $resolver): void
    {
        $resolver->setDefaults([
            'data_class' => UserSignUp::class,
            'step_property_path' => 'currentStep', // declared in UserSignUp::$currentStep
        ]);
    }
}

The step name comes from the first param of addStep(), which matches the form name, like this:

  • The personal form of type UserSignUpPersonalType will be the step personal,
  • The professional form of type UserSignUpProfessionalType will be the step professional,
  • and so on.

When the form is created, the currentStep value determines which step form to build, only the matching one, from the steps defined above, will be built.

Controller

Use the existent createForm() in your controller to create a FormFlow instance.

class UserSignUpController extends AbstractController
{
    #[Route('/signup')]
    public function __invoke(Request $request): Response
    {
        $flow = $this->createForm(UserSignUpType::class, new UserSignUp())
            ->handleRequest($request);

        if ($flow->isSubmitted() && $flow->isValid() && $flow->isFinished()) {
            // do something with $form->getData()

            return $this->redirectToRoute('app_signup_success');
        }

        return $this->render('signup/flow.html.twig', [
            'form' => $flow->getStepForm(),
        ]);
    }
}

This follows the classic form creation and handling pattern, with 2 key differences:

  • The check $flow->isFinished() to know if the finish flow button was clicked,
  • The $flow->getStepForm() call, which creates the a new step form, when necessary, based on the current state.

Don’t be misled by the $flow variable name, it’s just a Form descendant with FormFlow capabilities.

Important

The form data will be stored across steps, meaning the initial data set during the FormFlow creation won't match the one returned by $form->getData() at the end. Therefore, always use $form->getData() when the flow finishes.

FlowButtonType

A FlowButton is a regular submit button with a handler (a callable). It mainly handles step transitions but can also run custom logic tied to your form data.

There are 4 built-in FlowButton types:

  • FlowResetType: sends the FormFlow back to the initial state (will depend on the initial data),
  • FlowNextType: moves to the next step,
  • FlowPreviousType: goes to a previous step,
  • FlowFinishType: same as reset but also marks the FormFlow as finished.

You can combine these options of these buttons for different purposes, for example:

  • A skip button using the FlowNextType and clear_submission = true moves the FormFlow forward while clearing the current step,
  • A back_to button using the FlowPreviousType and a view value (step name) returns to a specific previous step,

Built-in flow buttons will have a default handler, but you can define a custom handler for specific needs. The handler option uses the following signature:

function (UserSignUp $data, FlowButtonInterface $button, FormFlowInterface $flow) {
    // $data is the current data bound to the form the button belongs to,
    // $button is the flow button clicked,
    // $flow is the FormFlow that the button belongs to, $flow->moveNext(), $flow->movePrevious(), ...
}

Important

By default, the callable handler is executed when the form is submitted, passes validation, and just before the next step form is created during $flow->getStepForm(). To control it manually, check if $flow->getClickedButton() is set and call $flow->getClickedButton()->handle() after $flow->handleRequest($request) where needed.

FlowButtonType also comes with other 2 options:

  • clear_submission: If true, it clears the submitted data. This is especially handy for skip and previous buttons, or anytime you want to empty the current step form submission.
  • include_if: null if you want to include the button in all steps (default), an array of steps, or a callable that’s triggered during form creation to decide whether the flow button should be included in the current step form. This callable will receive the FlowCursor instance as argument.

Other Building Blocks

FlowCursor

This immutable value object holds all defined steps and the current one. You can access it via $flow->getCursor() or as a FormView variable in Twig to build a nice step progress UI.

FlowNavigatorType

The built-in FlowNavigatorType provides 3 default flow buttons: previous, next, and finish. You can customize or add more if needed. Here’s an example of adding a “skip” button to the professional step we defined earlier:

class UserSignUpNavigatorType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options): void
    {
        $builder->add('skip', FlowNextType::class, [
            'clear_submission' => true,
            'include_if' => ['professional'], // the step names where the button will appear
        ]);
    }

    public function getParent(): string
    {
        return FlowNavigatorType::class;
    }
}

Then use UserSignUpNavigatorType instead.

Data Storage

FormFlow handles state across steps, so the final data includes everything collected throughout the flow. By default, it uses SessionDataStorage (unless you’ve configured a custom one). For testing, InMemoryDataStorage is also available.

You can also create custom data storage by implementing DataStorageInterface and passing it through the data_storage option in FormFlowType.

Step Accessor

The step_accessor option lets you control how the current step is read from or written to your data. By default, PropertyPathStepAccessor handles this using the form’s bound data and PropertyAccess component. If the step name is managed externally (e.g., by a workflow), you can create a custom StepAccessorInterface adapter and pass it through this option in FormFlowType.

Validation

FormFlow relies on the standard validation system but introduces a useful convention: it sets the current step as an active validation group. This allows step-specific validation rules without extra setup:

final class FormFlowType extends AbstractFlowType  
{
    public function configureOptions(OptionsResolver $resolver): void  
    {
        // ...

        $resolver->setDefault('validation_groups', function (FormFlowInterface $flow) {  
            return ['Default', $flow->getCursor()->getCurrentStep()];  
        });
    }
}

Allowing you to configure the validation groups in your constraints, like this:

class UserSignUp
{
    public function __construct(
        #[Valid(groups: ['personal'])]
        public Personal $personal  = new Personal(),

        #[Valid(groups: ['professional'])]
        public Professional $professional = new Professional(),

        #[Valid(groups: ['account'])]
        public Account $account = new Account(),

        public string $currentStep = 'personal',
    ) {
    }
}

Type Extension

FormFlowType is a regular form type in the Form system, so you can use AbstractTypeExtension to extend one or more of them:

class UserSignUpTypeExtension extends AbstractTypeExtension
{
    /**
     * @param FormFlowBuilderInterface $builder
     */
    public function buildForm(FormBuilderInterface $builder, array $options): void
    {
        $builder->addStep('role', UserSignUpRoleType::class, priority: 1); // added to the beginning cos higher priority
        $builder->removeStep('account');
        if ($builder->hasStep('professional')) {
            $builder->getStep('professional')->setSkip(fn (UserSignUp $data) => !$data->personal->working);
        }
        $builder->addStep('onboarding', UserSignUpOnboardingType::class); // added at the end
    }

    public static function getExtendedTypes(): iterable
    {
        yield UserSignUpType::class;
    }
}

There’s a lot more to share about this feature, so feel free to ask if anything isn’t clear.

Cheers!

@yceruto yceruto added the Form label Apr 13, 2025
@yceruto yceruto requested a review from xabbuh as a code owner April 13, 2025 23:19
@carsonbot carsonbot added this to the 7.3 milestone Apr 13, 2025
@symfony symfony deleted a comment from carsonbot Apr 13, 2025
@yceruto yceruto marked this pull request as draft April 13, 2025 23:25
Copy link
Contributor

@94noni 94noni left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

early raw reviews :)

@connorhu
Copy link
Contributor

Great idea! I've looked at the previous PR and could use it! One question came up: how can I jump back to a specific step without having to press the back button many times?
May the answer is can't by default. I solved this issue by keeping track of which valid step we are at and the url contains the step number (1..n), so I can generate a url for the previous steps, but I dont allow to go to not-yet-valid next steps.
I think I can see the points where I need to customize to achieve this.

@yceruto
Copy link
Member Author

yceruto commented Apr 14, 2025

how can I jump back to a specific step without having to press the back button many times?

Hey! take a look at the testMoveBackToStep() test, it covers this case. It's possible via submit operation or manually using $flow->movePrevious('step') directly.

@yceruto yceruto force-pushed the formflow branch 2 times, most recently from 2f81d34 to cdac9e2 Compare April 15, 2025 00:16
@RafaelKr
Copy link

Hey @yceruto, awesome to see this may become a native part of Symfony Forms!

I just had a quick look at the implementation and didn't find anything about UploadedFile (yet).
This was one of the big challenges we had to solve with CraueFormFlowBundle in combination with https://rekalogika.dev/file-bundle/file-upload-filepond, especially to make restore work (when going back to show the previously submitted files) and then to handle those if the step is submitted again.

It would be very helpful to have a default way the FormFlow can handle file uploads, but also to have some interface to interact with the full lifecycle of uploaded files, e.g. to decide where and how to store them, how to reference them inside form data, etc.

I think the lifecycle consists of the following steps:

  1. Initial upload. I think it would be best to already store the file(s) to a temporary location on the filesystem and just work with references to them.
    In our case we use the Rekalogika file bundle to directly reference Files with our Doctrine Media Entity (see https://rekalogika.dev/file-bundle/doctrine-entity and https://rekalogika.dev/file-bundle/working-with-entities) and then store the Media entity inside our Form Data.
  2. "Restore" already uploaded file(s) when the user goes back to a step with a file upload field.
  3. Handle resubmit, especially for file inputs with multiple attribute. If the same step is submitted more then once, the following cases need to be handled:
  • keep unchanged files
  • delete files which were removed
  • create newly uploaded files
  1. Final submission. Maybe we want to move files from a temporary location to persistent storage.

Maybe file uploads are not as important for an initial implementation, but it's definitely a use case which should be thought about.

Feel free to ping me if you have any questions. Maybe I could even build a minimal demo of the current implementation we use in our project and share it with you.

@stof
Copy link
Member

stof commented Apr 15, 2025

  1. I think it would be best to already store the file(s) to a temporary location on the filesystem and just work with references to them.

this would be incompatible with apps using a load balancer with several servers, as there is no guarantee that the next request goes to the same server behind the load balancer. Such case require storing uploads in a shared storage (for instance using a S3 bucket or similar storage)

@RafaelKr
Copy link

  1. I think it would be best to already store the file(s) to a temporary location on the filesystem and just work with references to them.

this would be incompatible with apps using a load balancer with several servers, as there is no guarantee that the next request goes to the same server behind the load balancer. Such case require storing uploads in a shared storage (for instance using a S3 bucket or similar storage)

You're very right, thanks for pointing this out. So it's especially important to have the possibility of handling those different cases. Maybe a FileUploadHandlerInterface could be introduced. I don't really like the default handling of CraueFormFlowBundle (storing files as base64 to the session), but also can't come up with a better approach which would be compatible with horizontal scaling.

@yceruto
Copy link
Member Author

yceruto commented Apr 15, 2025

I haven’t checked the file upload yet because I knew it would be a complicated topic, but I think using a custom flow button (as explained above) will give you the flexibility to do custom things on your own.

One option is to create your own next flow button with a dedicated handler where file uploads can be managed. Then, you can keep track of the uploaded files by saving the references in the DTO, which is preserved between steps.

Imagine you have a documents step defined for files uploading. In your navigator form, you can define this new button:

$builder->add('upload', FlowButtonType::class, [
    'handler' => function (MyDto $data, FlowButtonInterface $button, FormFlowInterface $flow) {
        // handle files uploading here ... store them somewhere ... create references ...

        // $data->uploadedFiles = ... save references if we go back ...

        $flow->moveNext();
    },
    'include_if' => ['documents'], // the steps where this button will appear
]);

So, it’s up to you where to store the files, how to reference them in the DTO, and how to render them again if the user goes back to this step, just by looking into $data->uploadedFiles.

@yceruto
Copy link
Member Author

yceruto commented Apr 15, 2025

Think of Flow buttons like mini-controllers with a focused job. The main controller handles the shared logic across all steps, while each action handler takes care of custom operations.

You can even use them for inter-step operations (like in the demo preview, where I showed how to add or remove skill items from a CollectionType). In those cases, the step stays the same, but the bound data gets updated, and the form is rebuilt when $flow->getStepForm() is called again, now with new data and form updated.

This part feels a bit like magic, but it’s a helpful one given how complex multistep forms can be.

@yceruto yceruto force-pushed the formflow branch 9 times, most recently from 1ef730f to 4df48d8 Compare April 24, 2025 14:20
@yceruto
Copy link
Member Author

yceruto commented Jun 14, 2025

As promised, here’s the demo app: https://github.com/yceruto/formflow-demo.

I’d love to see what other use cases you think this feature could support, feel free to share your ideas!

@Spomky
Copy link
Contributor

Spomky commented Jul 2, 2025

Hi @yceruto,

Thank you very much for the demo. I found it really straightforward to understand how to use and customize the form, the steps, and the actions 👍🏽 .

I’ve tested several use cases, and everything works well except for one scenario. I might be missing something, but it seems that the form events on the steps are not being triggered. Specifically, in a flow where the user is first asked to pick a color (choice type), and then to select a gradient based on the chosen color, the gradient step uses a choice type with options depending on the previous selection. Unfortunately, the event responsible for setting these dynamic choices is never called.

I might be misunderstanding how to properly use form events with the form flow, but I wanted to check with you in case there’s a recommended way to handle this scenario.

Other than this issue, everything else is working perfectly.

@yceruto
Copy link
Member Author

yceruto commented Jul 2, 2025

Hi @Spomky, thanks for testing it :)

Can you please share the changes that I need to reproduce the issue? Thanks!

@Spomky
Copy link
Contributor

Spomky commented Jul 3, 2025

Hi,

As mentioned in the PR I created to show the issue, I eventually managed to get it working. So to me, this is definitely a very good addition, allowing lots of use cases to be covered.
Also I confirm it works fine with Doctrine entities.

Thank you very much for your work on this! I really appreciate the time and effort you put into it. Approved!

This could be marked as experimental for 7.4 and officially adopted in 8.0.

@OskarStark
Copy link
Contributor

This could be marked as experimental for 7.4 and officially adopted in 8.0.

Unfortunately we cannot introduce experimental features in LTS versions. See https://symfony.com/doc/current/contributing/code/experimental.html

@Spomky
Copy link
Contributor

Spomky commented Jul 3, 2025

Indeed. So let's play with it and we'll see starting from 8.1.

@RafaelKr
Copy link

RafaelKr commented Jul 3, 2025

Would it be possible to already provide it via an experimental "addon" bundle (e.g. symfony/experimental-form-flow) before it's released with the official Symfony Forms component? That way it could already be battle-tested with a current stable release (7.3+ or even earlier).

Waiting until 8.1 (released in May 2026) for a first experimental release seems like a pretty long time to me.

@jmsche
Copy link
Contributor

jmsche commented Jul 3, 2025

If there's a need to mark it as experimental, it could be added as part of 8.0 as experimental, like symfony/string was for version 5.0.

@ker0x
Copy link
Contributor

ker0x commented Jul 3, 2025

@RafaelKr there's already a bundle port of the feature that you can use: https://github.com/yceruto/formflow-bundle

The demo app use it!

@yceruto
Copy link
Member Author

yceruto commented Jul 3, 2025

Absolutely! I'm currently beta testing this feature in two projects using yceruto/formflow-bundle and everything is working good so far. However, It would be fantastic to get feedback from some of the more experienced Form contributors, many come to mind, but I'd love to hear the thoughts of @xabbuh, @weaverryan, @wouterj, @HeahDude and @stof in particular if possible 🙏

Naming conventions, design, DX, etc. there is always room for improvement.

@yceruto yceruto force-pushed the formflow branch 6 times, most recently from 380da70 to 9ba68de Compare July 8, 2025 22:52
@yceruto
Copy link
Member Author

yceruto commented Jul 8, 2025

I received feedback regarding the flow button handler logic, so I simplified it by delegating execution responsibilities directly to the FlowButton class. This allowed me to remove redundant methods and improve overall code clarity.

In general, you don’t need to manually call $flow->getClickedButton()->handle(), as it’s automatically executed during the $flow->getStepForm() process (if the clicked submit button is an FlowButton and hasn’t been handled yet).

However, you might occasionally need to invoke the handler associated with the clicked flow button manually, such as when you want to perform additional logic after its execution but before the new step form:

$flow->handleRequest($request);

$flow->getClickedButton()->handle();

// do something between the current step and the new step form creation...

$flow = $flow->getStepForm();

The related changes are visible here.

@yceruto
Copy link
Member Author

yceruto commented Jul 24, 2025

Hey there! Just one more review & vote and we can merge this into 7.4 😊 Friendly ping to @symfony/mergers.

A quick reminder: there’s a demo app available if you’d like to test it out first. You can also check out the mirrored bundle featuring the same code.

Thanks! 🙌

@yceruto yceruto force-pushed the formflow branch 3 times, most recently from 9cb35db to ab49dc4 Compare July 26, 2025 23:52
@yceruto
Copy link
Member Author

yceruto commented Jul 27, 2025

Thanks @smnandre for your review!

Summary of the latest changes:

  • Renamed back to previous (wherever it makes sense)
  • Improved class naming for Flow button, type, step, builder, cursor, and navigator (now shorter and more concise)
  • Removed the action option from FlowButtonType in favor of dedicated types: FlowResetType, FlowPreviousType, FlowNextType, and FlowFinishType, each with specific options tailored to their respective actions

The description of the PR was also updated to reflect the current state of the code.

It's ready for code review again!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy