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

Draft
wants to merge 1 commit into
base: 7.4
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,13 @@
use Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException;
use Symfony\Component\DependencyInjection\ParameterBag\ContainerBagInterface;
use Symfony\Component\Form\Extension\Core\Type\FormType;
use Symfony\Component\Form\Flow\FormFlowBuilderInterface;
use Symfony\Component\Form\Flow\FormFlowInterface;
use Symfony\Component\Form\Flow\FormFlowTypeInterface;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormFactoryInterface;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormTypeInterface;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpFoundation\Exception\SessionNotFoundException;
use Symfony\Component\HttpFoundation\JsonResponse;
Expand Down Expand Up @@ -345,6 +349,8 @@ protected function createAccessDeniedException(string $message = 'Access Denied.

/**
* Creates and returns a Form instance from the type of the form.
*
* @return ($type is class-string<FormFlowTypeInterface> ? FormFlowInterface : FormInterface)
*/
protected function createForm(string $type, mixed $data = null, array $options = []): FormInterface
{
Expand Down
5 changes: 5 additions & 0 deletions src/Symfony/Bundle/FrameworkBundle/Resources/config/form.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
use Symfony\Component\Form\Extension\DependencyInjection\DependencyInjectionExtension;
use Symfony\Component\Form\Extension\HtmlSanitizer\Type\TextTypeHtmlSanitizerExtension;
use Symfony\Component\Form\Extension\HttpFoundation\HttpFoundationRequestHandler;
use Symfony\Component\Form\Extension\HttpFoundation\Type\FormFlowTypeSessionDataStorageExtension;
use Symfony\Component\Form\Extension\HttpFoundation\Type\FormTypeHttpFoundationExtension;
use Symfony\Component\Form\Extension\Validator\Type\FormTypeValidatorExtension;
use Symfony\Component\Form\Extension\Validator\Type\RepeatedTypeValidatorExtension;
Expand Down Expand Up @@ -123,6 +124,10 @@
->args([service('form.type_extension.form.request_handler')])
->tag('form.type_extension')

->set('form.type_extension.form.flow.session_data_storage', FormFlowTypeSessionDataStorageExtension::class)
->args([service('request_stack')->ignoreOnInvalid()])
->tag('form.type_extension')

->set('form.type_extension.form.request_handler', HttpFoundationRequestHandler::class)
->args([service('form.server_params')])

Expand Down
4 changes: 2 additions & 2 deletions src/Symfony/Bundle/FrameworkBundle/composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@
"symfony/dom-crawler": "^6.4|^7.0",
"symfony/dotenv": "^6.4|^7.0",
"symfony/polyfill-intl-icu": "~1.0",
"symfony/form": "^6.4|^7.0",
"symfony/form": "^7.4",
"symfony/expression-language": "^6.4|^7.0",
"symfony/html-sanitizer": "^6.4|^7.0",
"symfony/http-client": "^6.4|^7.0",
Expand Down Expand Up @@ -88,7 +88,7 @@
"symfony/dotenv": "<6.4",
"symfony/dom-crawler": "<6.4",
"symfony/http-client": "<6.4",
"symfony/form": "<6.4",
"symfony/form": "<7.4",
"symfony/json-streamer": ">=7.4",
"symfony/lock": "<6.4",
"symfony/mailer": "<6.4",
Expand Down
5 changes: 5 additions & 0 deletions src/Symfony/Component/Form/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
CHANGELOG
=========

7.4
---

* Add `FormFlow` component for multistep forms management

7.3
---

Expand Down
3 changes: 3 additions & 0 deletions src/Symfony/Component/Form/Extension/Core/CoreExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,9 @@ protected function loadTypes(): array
new Type\TelType(),
new Type\ColorType($this->translator),
new Type\WeekType(),
new Type\FormFlowActionType(),
new Type\FormFlowNavigatorType(),
new Type\FormFlowType($this->propertyAccessor),
];
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\Form\Extension\Core\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Flow\ActionButtonInterface;
use Symfony\Component\Form\Flow\ActionButtonTypeInterface;
use Symfony\Component\Form\Flow\FormFlowCursor;
use Symfony\Component\Form\Flow\FormFlowInterface;
use Symfony\Component\OptionsResolver\Exception\MissingOptionsException;
use Symfony\Component\OptionsResolver\Options;
use Symfony\Component\OptionsResolver\OptionsResolver;

/**
* An action-based submit button for a form flow.
*
* @author Yonel Ceruto <open@yceruto.dev>
*/
class FormFlowActionType extends AbstractType implements ActionButtonTypeInterface
{
public function configureOptions(OptionsResolver $resolver): void
{
$resolver->define('action')
->info('The action name of the button')
->default('')
->allowedTypes('string');

$resolver->define('handler')
->info('A callable that will be called when this button is clicked')
->default(function (Options $options) {
if (!\in_array($options['action'], ['back', 'next', 'finish', 'reset'], true)) {
throw new MissingOptionsException(\sprintf('The option "handler" is required for the action "%s".', $options['action']));
}

return function (mixed $data, ActionButtonInterface $button, FormFlowInterface $flow): void {
match (true) {
$button->isBackAction() => $flow->moveBack($button->getViewData()),
$button->isNextAction() => $flow->moveNext(),
$button->isFinishAction(), $button->isResetAction() => $flow->reset(),

Check failure on line 48 in src/Symfony/Component/Form/Extension/Core/Type/FormFlowActionType.php

View workflow job for this annotation

GitHub Actions / Psalm

ParadoxicalCondition

src/Symfony/Component/Form/Extension/Core/Type/FormFlowActionType.php:48:25: ParadoxicalCondition: Condition (<expr>) contradicts a previously-established condition (!<expr>) (see https://psalm.dev/089)
};
};
})
->allowedTypes('callable');

$resolver->define('include_if')
Copy link
Contributor

Choose a reason for hiding this comment

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

nice

Copy link
Member Author

@yceruto yceruto Apr 24, 2025

Choose a reason for hiding this comment

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

I've improved it a bit more for better DX, so now we have three allowed values:

  1. null if you want to include the button in all defined steps,
  2. an array with the names of the steps where the button will be included, (most used)
  3. a callable for more advanced inclusion logic.

->info('Decide whether to include this button in the current form')
->default(function (Options $options) {
return match ($options['action']) {
'back' => fn (FormFlowCursor $cursor): bool => $cursor->canMoveBack(),
'next' => fn (FormFlowCursor $cursor): bool => $cursor->canMoveNext(),
'finish' => fn (FormFlowCursor $cursor): bool => $cursor->isLastStep(),
default => null,
};
})
->allowedTypes('null', 'array', 'callable')
->normalize(function (Options $options, mixed $value) {
if (\is_array($value)) {
return fn (FormFlowCursor $cursor): bool => \in_array($cursor->getCurrentStep(), $value, true);
}

return $value;
});

$resolver->define('clear_submission')
->info('Whether the submitted data will be cleared when this button is clicked')
->default(function (Options $options) {
return 'reset' === $options['action'] || 'back' === $options['action'];
})
->allowedTypes('bool');

$resolver->setDefault('validate', function (Options $options) {
return !$options['clear_submission'];
});

$resolver->setDefault('validation_groups', function (Options $options) {
return $options['clear_submission'] ? false : null;
});
}

public function getParent(): string
{
return SubmitType::class;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\Form\Extension\Core\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

/**
* A navigator type that defines default actions to interact with a form flow.
*
* @author Yonel Ceruto <open@yceruto.dev>
*/
class FormFlowNavigatorType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$builder->add('back', FormFlowActionType::class, [
Copy link
Contributor

Choose a reason for hiding this comment

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

what bout "previous" ? generally it goes with "next"
or rename other "forward" ?

Copy link
Member Author

Choose a reason for hiding this comment

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

I don’t have a strong opinion on that. I personally prefer the shorter version, and users can change it using the label option anyway. Let’s see what others think.

'action' => 'back',
]);

$builder->add('next', FormFlowActionType::class, [
'action' => 'next',
]);

$builder->add('finish', FormFlowActionType::class, [
'action' => 'finish',
]);
}

public function configureOptions(OptionsResolver $resolver): void
{
$resolver->setDefaults([
'label' => false,
'mapped' => false,
'priority' => -100,
]);
}
}
119 changes: 119 additions & 0 deletions src/Symfony/Component/Form/Extension/Core/Type/FormFlowType.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\Form\Extension\Core\Type;

use Symfony\Component\Form\Flow\AbstractFlowType;
use Symfony\Component\Form\Flow\DataAccessor\PropertyPathStepAccessor;
use Symfony\Component\Form\Flow\DataAccessor\StepAccessorInterface;
use Symfony\Component\Form\Flow\DataStorage\DataStorageInterface;
use Symfony\Component\Form\Flow\DataStorage\NullDataStorage;
use Symfony\Component\Form\Flow\FormFlowInterface;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormView;
use Symfony\Component\OptionsResolver\Exception\MissingOptionsException;
use Symfony\Component\OptionsResolver\Options;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\PropertyAccess\PropertyAccess;
use Symfony\Component\PropertyAccess\PropertyAccessorInterface;
use Symfony\Component\PropertyAccess\PropertyPath;
use Symfony\Component\PropertyAccess\PropertyPathInterface;

/**
* A multistep form.
Copy link
Contributor

Choose a reason for hiding this comment

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

a question about naming:

you describe this as a form multistep
but the class is named form flow

its feels weird at first read

Copy link
Member Author

Choose a reason for hiding this comment

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

They mean the same to me... I’m just phrasing it differently to make the idea clearer. What is the weird part?

*
* @author Yonel Ceruto <open@yceruto.dev>
*/
class FormFlowType extends AbstractFlowType
{
public function __construct(
private ?PropertyAccessorInterface $propertyAccessor = null,
) {
$this->propertyAccessor ??= PropertyAccess::createPropertyAccessor();
}

/**
* {@inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$builder->setDataStorage($options['data_storage'] ?? new NullDataStorage());
$builder->setStepAccessor($options['step_accessor']);
}

/**
* {@inheritdoc}
*/
public function buildView(FormView $view, FormInterface $form, array $options): void
{
$view->vars['cursor'] = $cursor = $form->getCursor();

$index = 0;
$position = 1;
foreach ($form->getConfig()->getSteps() as $name => $step) {
$isSkipped = $step->isSkipped($form->getViewData());

$stepVars = [
'name' => $name,
'index' => $index++,
'position' => $isSkipped ? -1 : $position++,
'is_current_step' => $name === $cursor->getCurrentStep(),
'can_be_skipped' => null !== $step->getSkip(),
'is_skipped' => $isSkipped,
];

$view->vars['steps'][$name] = $stepVars;

if (!$isSkipped) {
$view->vars['visible_steps'][$name] = $stepVars;
}
}
}

public function configureOptions(OptionsResolver $resolver): void
{
$resolver->define('data_storage')
->default(null)
->allowedTypes('null', DataStorageInterface::class);

$resolver->define('step_accessor')
->default(function (Options $options) {
if (!isset($options['step_property_path'])) {
throw new MissingOptionsException('Option "step_property_path" is required.');
}

return new PropertyPathStepAccessor($this->propertyAccessor, $options['step_property_path']);
})
->allowedTypes(StepAccessorInterface::class);

$resolver->define('step_property_path')
->info('Required if the default step_accessor is being used')
->allowedTypes('string', PropertyPathInterface::class)
->normalize(function (Options $options, string|PropertyPathInterface $value): PropertyPathInterface {
return \is_string($value) ? new PropertyPath($value) : $value;
});

$resolver->define('auto_reset')
->info('Whether the FormFlow will be reset automatically when it is finished')
->default(true)
->allowedTypes('bool');

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

public function getParent(): string
{
return FormType::class;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ protected function loadTypeExtensions(): array
{
return [
new Type\FormTypeHttpFoundationExtension(),
new Type\FormFlowTypeSessionDataStorageExtension(),
];
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\Form\Extension\HttpFoundation\Type;

use Symfony\Component\Form\AbstractTypeExtension;
use Symfony\Component\Form\Extension\Core\Type\FormFlowType;
use Symfony\Component\Form\Flow\DataStorage\SessionDataStorage;
use Symfony\Component\Form\Flow\FormFlowBuilderInterface;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\HttpFoundation\RequestStack;

class FormFlowTypeSessionDataStorageExtension extends AbstractTypeExtension
{
public function __construct(
private readonly ?RequestStack $requestStack = null,
) {
}

/**
* @param FormFlowBuilderInterface $builder
*/
public function buildForm(FormBuilderInterface $builder, array $options): void

Check failure on line 31 in src/Symfony/Component/Form/Extension/HttpFoundation/Type/FormFlowTypeSessionDataStorageExtension.php

View workflow job for this annotation

GitHub Actions / Psalm

MoreSpecificImplementedParamType

src/Symfony/Component/Form/Extension/HttpFoundation/Type/FormFlowTypeSessionDataStorageExtension.php:31:52: MoreSpecificImplementedParamType: Argument 1 of Symfony\Component\Form\Extension\HttpFoundation\Type\FormFlowTypeSessionDataStorageExtension::buildForm has the more specific type 'Symfony\Component\Form\Flow\FormFlowBuilderInterface', expecting 'Symfony\Component\Form\FormBuilderInterface' as defined by Symfony\Component\Form\AbstractTypeExtension::buildForm (see https://psalm.dev/140)

Check failure on line 31 in src/Symfony/Component/Form/Extension/HttpFoundation/Type/FormFlowTypeSessionDataStorageExtension.php

View workflow job for this annotation

GitHub Actions / Psalm

MoreSpecificImplementedParamType

src/Symfony/Component/Form/Extension/HttpFoundation/Type/FormFlowTypeSessionDataStorageExtension.php:31:52: MoreSpecificImplementedParamType: Argument 1 of Symfony\Component\Form\Extension\HttpFoundation\Type\FormFlowTypeSessionDataStorageExtension::buildForm has the more specific type 'Symfony\Component\Form\Flow\FormFlowBuilderInterface', expecting 'Symfony\Component\Form\FormBuilderInterface' as defined by Symfony\Component\Form\FormTypeExtensionInterface::buildForm (see https://psalm.dev/140)
{
if (null === $this->requestStack || null !== $options['data_storage']) {
return;
}

$key = \sprintf('_sf_formflow.%s_%s', strtolower(str_replace('\\', '_', $builder->getType()->getInnerType()::class)), $builder->getName());
$builder->setDataStorage(new SessionDataStorage($key, $this->requestStack));
}

public static function getExtendedTypes(): iterable

Check failure on line 41 in src/Symfony/Component/Form/Extension/HttpFoundation/Type/FormFlowTypeSessionDataStorageExtension.php

View workflow job for this annotation

GitHub Actions / Psalm

InvalidReturnType

src/Symfony/Component/Form/Extension/HttpFoundation/Type/FormFlowTypeSessionDataStorageExtension.php:41:48: InvalidReturnType: The declared return type 'array<array-key, string>' for Symfony\Component\Form\Extension\HttpFoundation\Type\FormFlowTypeSessionDataStorageExtension::getExtendedTypes is incorrect, got 'Generator<int, Symfony\Component\Form\Extension\Core\Type\FormFlowType::class, mixed, void>' (see https://psalm.dev/011)
{
yield FormFlowType::class;
}
}
Loading
Loading