Skip to content
Open
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 @@ -252,6 +252,9 @@ private function addFormSection(ArrayNodeDefinition $rootNode, callable $enableI
->info('Form configuration')
->{$enableIfStandalone('symfony/form', Form::class)}()
->children()
->booleanNode('use_attribute')
->defaultTrue()
->end()
->arrayNode('csrf_protection')
->treatFalseLike(['enabled' => false])
->treatTrueLike(['enabled' => true])
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Finder\Finder;
use Symfony\Component\Finder\Glob;
use Symfony\Component\Form\Attribute\AsFormType;
use Symfony\Component\Form\Form;
use Symfony\Component\Form\FormTypeExtensionInterface;
use Symfony\Component\Form\FormTypeGuesserInterface;
Expand Down Expand Up @@ -849,6 +850,14 @@ private function registerFormConfiguration(array $config, ContainerBuilder $cont
$container->setParameter('form.type_extension.csrf.enabled', false);
}

if ($config['form']['use_attribute']) {
Copy link
Member

Choose a reason for hiding this comment

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

Using attributes is already opt-in as you have to add the attribute to a class that is autoconfigured. I understand the benefit of this new configuration in avoiding the declaration of unnecessary services, but it would be simpler for users of the framework if they did not need to activate this option.
Unnecessary service (form.metadata.attribute_loader) can be removed in the compiler pass.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Maybe switch to enable by default instead of disable by default in src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Configuration.php to keep the possibility to disable, WDYF?

Copy link
Contributor

Choose a reason for hiding this comment

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

If no form.metadata.form_type tags exist, the services in the CompilerPass can be removed, eliminating the need for the use_attribute configuration.

$loader->load('form_metadata.php');

$container->registerAttributeForAutoconfiguration(AsFormType::class, static function (ChildDefinition $definition) {
$definition->addResourceTag('form.metadata.form_type');
});
}

if (!ContainerBuilder::willBeAvailable('symfony/translation', Translator::class, ['symfony/framework-bundle', 'symfony/form'])) {
$container->removeDefinition('form.type_extension.upload.validator');
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -336,6 +336,7 @@
[], // All type extensions are stored here by FormPass
[], // All type guessers are stored here by FormPass
service('debug.file_link_formatter')->nullOnInvalid(),
[], // All metadata form types are stored here by FormPass
])
->tag('console.command')

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<?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\DependencyInjection\Loader\Configurator;

use Symfony\Component\Form\Metadata\Loader\AttributeLoader;

return static function (ContainerConfigurator $container) {
$container->services()
->set('form.metadata.attribute_loader', AttributeLoader::class)

->alias('form.metadata.default_loader', 'form.metadata.attribute_loader')
;
};
Original file line number Diff line number Diff line change
Expand Up @@ -728,6 +728,7 @@ protected static function getBundleDefaultConfig()
'field_attr' => ['data-controller' => 'csrf-protection'],
'token_id' => null,
],
'use_attribute' => true,
],
'esi' => ['enabled' => false],
'ssi' => ['enabled' => false],
Expand Down
34 changes: 34 additions & 0 deletions src/Symfony/Component/Form/Attribute/AsFormType.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
<?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\Attribute;

/**
* Register a model class (e.g. DTO, entity, model, etc...) as a FormType.
*
* @author Benjamin Georgeault <git@wedgesama.fr>
*/
#[\Attribute(\Attribute::TARGET_CLASS)]
class AsFormType
Copy link
Member

Choose a reason for hiding this comment

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

I don't like the name AsFormType as it looks like it will register the service as a form type (tagging it as form.type), while it has a totally different behavior (it defines that class as providing metadata to configure a form type, not as being a form type)

Copy link
Contributor Author

@WedgeSama WedgeSama Sep 29, 2025

Choose a reason for hiding this comment

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

What do you think of:

  1. AsFormMetadata
  2. FormMetadata
  3. AsForm

I have a preference for the 1. And if you have ideas 🙏

Copy link
Contributor

Choose a reason for hiding this comment

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

IMO even if it is not a Form type per se, it is used as a form type. same goes for AsController. It marks the class a controller when in fact it is the methods

Copy link
Contributor Author

Choose a reason for hiding this comment

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

@stof WDYT of answers?

{
/**
* @param array<string, mixed> $options
*/
public function __construct(
private readonly array $options = [],
) {
}

public function getOptions(): array
{
return $this->options;
}
}
54 changes: 54 additions & 0 deletions src/Symfony/Component/Form/Attribute/Type.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
<?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\Attribute;

/**
* Add an AsFormType class property as a FormType's field.
*
* @author Benjamin Georgeault <git@wedgesama.fr>
*/
#[\Attribute(\Attribute::TARGET_PROPERTY)]
class Type
{
/**
* @param class-string|null $type the FormType class name to use for this field
* @param array<string, mixed> $options your form options
* @param string|null $name change the form view field's name
*/
public function __construct(
private ?string $type = null,
private array $options = [],
private ?string $name = null,
) {
}

/**
* @return array<string, mixed>
*/
public function getOptions(): array
{
return $this->options;
}

/**
* @return class-string|null
*/
public function getType(): ?string
{
return $this->type;
}

public function getName(): ?string
{
return $this->name;
}
}
6 changes: 4 additions & 2 deletions src/Symfony/Component/Form/Command/DebugCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ public function __construct(
private array $extensions = [],
private array $guessers = [],
private ?FileLinkFormatter $fileLinkFormatter = null,
private array $metadataTypes = [],
) {
parent::__construct();
}
Expand Down Expand Up @@ -95,6 +96,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int
$object = null;
$options['core_types'] = $this->getCoreTypes();
$options['service_types'] = array_values(array_diff($this->types, $options['core_types']));
$options['metadata_types'] = $this->metadataTypes;
if ($input->getOption('show-deprecated')) {
$options['core_types'] = $this->filterTypesByDeprecated($options['core_types']);
$options['service_types'] = $this->filterTypesByDeprecated($options['service_types']);
Expand Down Expand Up @@ -150,7 +152,7 @@ private function getFqcnTypeClass(InputInterface $input, SymfonyStyle $io, strin
if (0 === $count = \count($classes)) {
$message = \sprintf("Could not find type \"%s\" into the following namespaces:\n %s", $shortClassName, implode("\n ", $this->namespaces));

$allTypes = array_merge($this->getCoreTypes(), $this->types);
$allTypes = array_merge($this->getCoreTypes(), $this->types, $this->metadataTypes);
if ($alternatives = $this->findAlternatives($shortClassName, $allTypes)) {
if (1 === \count($alternatives)) {
$message .= "\n\nDid you mean this?\n ";
Expand Down Expand Up @@ -238,7 +240,7 @@ private function findAlternatives(string $name, array $collection): array
public function complete(CompletionInput $input, CompletionSuggestions $suggestions): void
{
if ($input->mustSuggestArgumentValuesFor('class')) {
$suggestions->suggestValues(array_merge($this->getCoreTypes(), $this->types));
$suggestions->suggestValues(array_merge($this->getCoreTypes(), $this->types, $this->metadataTypes));

return;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ protected function describeDefaults(array $options): void
{
$data['builtin_form_types'] = $options['core_types'];
$data['service_form_types'] = $options['service_types'];
$data['metadata_form_types'] = $options['metadata_types'];
if (!$options['show_deprecated']) {
$data['type_extensions'] = $options['extensions'];
$data['type_guessers'] = $options['guessers'];
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,11 @@ protected function describeDefaults(array $options): void
$this->output->listing(array_map($this->formatClassLink(...), $options['service_types']));
}

if ($options['metadata_types']) {
$this->output->section('Metadata form types');
$this->output->listing(array_map($this->formatClassLink(...), $options['metadata_types']));
}

if (!$options['show_deprecated']) {
if ($options['extensions']) {
$this->output->section('Type extensions');
Expand Down
33 changes: 32 additions & 1 deletion src/Symfony/Component/Form/DependencyInjection/FormPass.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,11 @@
use Symfony\Component\DependencyInjection\Compiler\PriorityTaggedServiceTrait;
use Symfony\Component\DependencyInjection\Compiler\ServiceLocatorTagPass;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\Form\Extension\Metadata\Type\MetadataType;
use Symfony\Component\Form\Metadata\FormMetadataInterface;

/**
* Adds all services with the tags "form.type", "form.type_extension" and
Expand Down Expand Up @@ -46,6 +49,7 @@ private function processFormTypes(ContainerBuilder $container): Reference
{
// Get service locator argument
$servicesMap = [];
$metadataTypeMap = [];
$namespaces = ['Symfony\Component\Form\Extension\Core\Type' => true];
$csrfTokenIds = [];

Expand All @@ -61,10 +65,37 @@ private function processFormTypes(ContainerBuilder $container): Reference
}
}

foreach ($container->getDefinitions() as $id => $definition) {
if (!$definition->hasTag('form.metadata.form_type')) {
continue;
}

if ($definition->isAbstract()) {
throw new InvalidArgumentException(\sprintf('The resource "%s" tagged "form.metadata.form_type" must not be abstract.', $id));
}

$className = $container->getDefinition($id)->getClass();
$formTypeId = $id.'.form_type';
$metadataId = $id.'.metadata';

$container->setDefinition($metadataId, new Definition(FormMetadataInterface::class))
->setFactory([new Reference('form.metadata.default_loader'), 'load'])
->addArgument($className)
->addTag('form.metadata');

$container->setDefinition($formTypeId, new Definition(MetadataType::class))
->addArgument(new Reference($metadataId))
->addTag('form.metadata_type', ['class_name' => $className]);

$metadataTypeMap[$className] = new Reference($formTypeId);
$namespaces[substr($className, 0, strrpos($className, '\\'))] = true;
}

if ($container->hasDefinition('console.command.form_debug')) {
$commandDefinition = $container->getDefinition('console.command.form_debug');
$commandDefinition->setArgument(1, array_keys($namespaces));
$commandDefinition->setArgument(2, array_keys($servicesMap));
$commandDefinition->setArgument(6, array_keys($metadataTypeMap));
}

if ($csrfTokenIds && $container->hasDefinition('form.type_extension.csrf')) {
Expand All @@ -75,7 +106,7 @@ private function processFormTypes(ContainerBuilder $container): Reference
}
}

return ServiceLocatorTagPass::register($container, $servicesMap);
return ServiceLocatorTagPass::register($container, [...$servicesMap, ...$metadataTypeMap]);
}

private function processFormTypeExtensions(ContainerBuilder $container): array
Expand Down
21 changes: 21 additions & 0 deletions src/Symfony/Component/Form/Exception/MetadataException.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<?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\Exception;

/**
* Thrown when an error occurred during Metadata creation.
*
* @author Benjamin Georgeault <git@wedgesama.fr>
*/
class MetadataException extends LogicException
{
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@

use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormView;
use Symfony\Component\Form\MetadataFormTypeInterface;
use Symfony\Component\Validator\ConstraintViolationInterface;

/**
Expand All @@ -24,10 +25,12 @@ class FormDataExtractor implements FormDataExtractorInterface
{
public function extractConfiguration(FormInterface $form): array
{
$innerType = $form->getConfig()->getType()->getInnerType();

$data = [
'id' => $this->buildId($form),
'name' => $form->getName(),
'type_class' => $form->getConfig()->getType()->getInnerType()::class,
'type_class' => $innerType instanceof MetadataFormTypeInterface ? $innerType->getClassName() : $innerType::class,
'synchronized' => $form->isSynchronized(),
'passed_options' => [],
'resolved_options' => [],
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
<?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\Metadata;

use Symfony\Component\Form\Exception\InvalidArgumentException;
use Symfony\Component\Form\Exception\MetadataException;
use Symfony\Component\Form\Extension\Metadata\Type\MetadataType;
use Symfony\Component\Form\FormExtensionInterface;
use Symfony\Component\Form\FormTypeGuesserInterface;
use Symfony\Component\Form\FormTypeInterface;
use Symfony\Component\Form\Metadata\Loader\LoaderInterface;

/**
* Responsible for instantiating FormType based on a {@see \Symfony\Component\Form\Metadata\FormMetadataInterface}.
*
* @author Benjamin Georgeault <git@wedgesama.fr>
*/
final class MetadataExtension implements FormExtensionInterface
{
/**
* @var array<class-string, FormTypeInterface>
*/
private array $loadedTypes = [];

public function __construct(
private readonly LoaderInterface $loader,
) {
}

public function getType(string $name): FormTypeInterface
{
if (null !== $type = $this->loadedTypes[$name] ?? null) {
return $type;
}

try {
return $this->loadedTypes[$name] = new MetadataType($this->loader->load($name));
} catch (MetadataException $e) {
throw new InvalidArgumentException(\sprintf('Cannot instantiate a "%s" for the given class "%s".', FormTypeInterface::class, $name), previous: $e);
}
}

public function hasType(string $name): bool
{
return ($this->loadedTypes[$name] ?? false) || $this->loader->support($name);
}

public function getTypeExtensions(string $name): array
{
return [];
}

public function hasTypeExtensions(string $name): bool
{
return false;
}

public function getTypeGuesser(): ?FormTypeGuesserInterface
{
return null;
}
}
Loading
Loading