a2lix/auto-form-bundle
Composer 安装命令:
composer require a2lix/auto-form-bundle
包简介
Automate form building
README 文档
README
Stop writing boilerplate form code. This bundle provides a single, powerful AutoType form type that automatically generates a complete Symfony form from any PHP class.
Note
If you need to manage form translations, please see the A2lix TranslationFormBundle, which is designed to work with this bundle.
Tip
A complete demonstration is also available at a2lix/demo.
Installation
Use Composer to install the bundle:
composer require a2lix/auto-form-bundle
Basic Usage
The simplest way to use AutoType is directly in your controller. It will generate a form based on the properties of the entity or DTO you pass it.
// ... class TaskController extends AbstractController { public function new(Request $request): Response { $task = new Task(); // Any entity or DTO $form = $this ->createForm(AutoType::class, $task) ->add('save', SubmitType::class) ->handleRequest($request) ; // ... } }
How It Works
AutoType reads the properties of the class you provide in the data_class option. For each property, it intelligently configures a corresponding form field. This gives you a solid foundation that you can then customize in two main ways:
- Form Options: Pass a configuration array directly when you create the form.
- PHP Attributes: Add
#[AutoTypeCustom]attributes directly to the properties of your entity or DTO.
Options passed directly to the form will always take precedence over attributes.
Customization via Form Options
This is the most flexible way to configure your form. Here is a comprehensive example:
// ... class TaskController extends AbstractController { public function new(Request $request, FormFactoryInterface $formFactory): Response { $product = new Product(); // Any entity or DTO $form = $formFactory->createNamed('product', AutoType::class, $product, [ // 1. Optional define which properties should be excluded from the form. // Use '*' for an "exclude-by-default" strategy. 'children_excluded' => ['id', 'internalRef'], // 2. Optional define which properties should be rendered as embedded forms. // Use '*' to embed all relational properties. 'children_embedded' => static fn (mixed $current) => [...$current, 'category', 'tags'], // 3. Optional customize, override, or add fields. 'children' => [ // Override an existing property with new options 'description' => [ 'child_type' => TextareaType::class, // Force a specific form type 'label' => 'Product Description', // Standard form options 'priority' => 10, ], // Add a field that does not exist on the DTO/entity 'terms_and_conditions' => [ 'child_type' => CheckboxType::class, 'mapped' => false, 'priority' => -100, ], // Completely replace a field's builder with a callable 'price' => function(FormBuilderInterface $builder, array $propAttributeOptions): FormBuilderInterface { // The callable receives the main builder and any options from a potential attribute. // It must return a new FormBuilderInterface instance. return $builder->create('price', MoneyType::class, ['currency' => 'EUR']); }, // Add a new field to the form 'save' => [ 'child_type' => SubmitType::class, ], ], // 4. Optional final modifications on the complete form builder. 'builder' => function(FormBuilderInterface $builder, array $classProperties): void { // This callable runs after all children have been added. if (isset($classProperties['code'])) { $builder->remove('code'); } }, ])->handleRequest($request); // ... } }
Customization via #[AutoTypeCustom] Attribute
For a more declarative approach, you can place the configuration directly on the properties of your DTO or entity. This keeps the form configuration co-located with your data model.
use A2lix\AutoFormBundle\Form\Attribute\AutoTypeCustom; use Symfony\Component\Form\Extension\Core\Type\TextareaType; class Product { #[AutoTypeCustom(excluded: true)] public private(set) int $id; public ?string $name = null; #[AutoTypeCustom(type: TextareaType::class, options: ['attr' => ['rows' => 5]])] public ?string $description = null; #[AutoTypeCustom(embedded: true)] public Category $category; }
Conditional Fields with Groups
You can conditionally include fields based on groups, similar to how Symfony's validation_groups work. This is useful for having different versions of a form (e.g., a "creation" version vs. an "edition" version).
To enable this, pass a children_groups option to your form. This option specifies which groups of fields should be included.
$form = $this->createForm(AutoType::class, $product, [ 'children_groups' => ['product:edit'], ]);
You can then assign fields to one or more groups using either form options or attributes.
Via Form Options
Use the child_groups option within the children configuration:
// ... 'children' => [ 'name' => [ 'child_groups' => ['product:edit', 'product:create'], ], 'stock' => [ 'child_groups' => ['product:edit'], ], ], // ...
In this example, if children_groups is set to ['product:edit'], both name and stock will be included. If it's set to ['product:create'], only name will be included.
Via #[AutoTypeCustom] Attribute
Use the groups property on the attribute:
use A2lix\AutoFormBundle\Form\Attribute\AutoTypeCustom; class Product { #[AutoTypeCustom(groups: ['product:edit', 'product:create'])] public ?string $name = null; #[AutoTypeCustom(groups: ['product:edit'])] public ?int $stock = null; }
If no children_groups option is provided to the form, all fields are included by default, regardless of whether they have groups assigned.
Advanced Recipes
Creating a Compound Field with inherit_data
You can use a callable in the children option to create complex fields that map to the parent object, which is useful for things like date ranges.
'children' => [ '_' => function (FormBuilderInterface $builder): FormBuilderInterface { return $builder ->create('validity_range', FormType::class, ['inherit_data' => true]) ->add('startsAt', DateType::class, [/* ... */]) ->add('endsAt', DateType::class, [/* ... */]); }, ]
Global Configuration
While not required, you can configure the bundle globally. For example, you can define a list of properties to always exclude.
Create a configuration file in config/packages/a2lix_auto_form.yaml:
a2lix_auto_form: # Exclude 'id' and 'createdAt' properties from all AutoType forms by default children_excluded: [id, createdAt]
License
This package is available under the MIT license.
a2lix/auto-form-bundle 适用场景与选型建议
a2lix/auto-form-bundle 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 3.93M 次下载、GitHub Stars 达 87, 最近一次更新时间为 2015 年 11 月 25 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「symfony」 「form」 「automation」 「magic」 「field」 「auto」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 a2lix/auto-form-bundle 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 a2lix/auto-form-bundle 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 a2lix/auto-form-bundle 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
The bundle for easy using json-rpc api on your project
Diese Contao 4 Erweiterung stellt Google reCAPTCHA V2 in Form eines neuen Formularfeldes im Formulargenerator bereit. This extension provides Google reCAPTCHA V2 in the form of a new form field in the form generator of Contao Open Source CMS.
Command-line utility for Vtiger CRM.
Historical accounting for contacts
A Laravel Filament Forms slug field.
Bundle Symfony DaplosBundle
统计信息
- 总下载量: 3.93M
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 87
- 点击次数: 25
- 依赖项目数: 10
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2015-11-25