|
5 | 5 | [](https://packagist.org/packages/a2lix/auto-form-bundle) |
6 | 6 | [](https://packagist.org/packages/a2lix/auto-form-bundle) |
7 | 7 | [](https://github.com/a2lix/AutoFormBundle/actions/workflows/ci.yml) |
| 8 | +[](https://codecov.io/gh/a2lix/AutoFormBundle) |
8 | 9 |
|
9 | 10 | 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. |
10 | 11 |
|
@@ -135,6 +136,58 @@ class Product |
135 | 136 | } |
136 | 137 | ``` |
137 | 138 |
|
| 139 | +### Conditional Fields with Groups |
| 140 | + |
| 141 | +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). |
| 142 | + |
| 143 | +To enable this, pass a `children_groups` option to your form. This option specifies which groups of fields should be included. |
| 144 | + |
| 145 | +```php |
| 146 | +$form = $this->createForm(AutoType::class, $product, [ |
| 147 | + 'children_groups' => ['product:edit'], |
| 148 | +]); |
| 149 | +``` |
| 150 | + |
| 151 | +You can then assign fields to one or more groups using either form options or attributes. |
| 152 | + |
| 153 | +#### Via Form Options |
| 154 | + |
| 155 | +Use the `child_groups` option within the `children` configuration: |
| 156 | + |
| 157 | +```php |
| 158 | +// ... |
| 159 | +'children' => [ |
| 160 | + 'name' => [ |
| 161 | + 'child_groups' => ['product:edit', 'product:create'], |
| 162 | + ], |
| 163 | + 'stock' => [ |
| 164 | + 'child_groups' => ['product:edit'], |
| 165 | + ], |
| 166 | +], |
| 167 | +// ... |
| 168 | +``` |
| 169 | + |
| 170 | +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. |
| 171 | + |
| 172 | +#### Via `#[AutoTypeCustom]` Attribute |
| 173 | + |
| 174 | +Use the `groups` property on the attribute: |
| 175 | + |
| 176 | +```php |
| 177 | +use A2lix\AutoFormBundle\Form\Attribute\AutoTypeCustom; |
| 178 | + |
| 179 | +class Product |
| 180 | +{ |
| 181 | + #[AutoTypeCustom(groups: ['product:edit', 'product:create'])] |
| 182 | + public ?string $name = null; |
| 183 | + |
| 184 | + #[AutoTypeCustom(groups: ['product:edit'])] |
| 185 | + public ?int $stock = null; |
| 186 | +} |
| 187 | +``` |
| 188 | + |
| 189 | +If no `children_groups` option is provided to the form, all fields are included by default, regardless of whether they have groups assigned. |
| 190 | + |
138 | 191 | ## Advanced Recipes |
139 | 192 |
|
140 | 193 | ### Creating a Compound Field with `inherit_data` |
|
0 commit comments