-
-
Notifications
You must be signed in to change notification settings - Fork 394
Add Collection component as form type extension #400
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
base: 2.x
Are you sure you want to change the base?
Changes from all commits
e901026
f0b9542
183c400
e70a60c
dd09371
59e23b9
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,8 @@ | ||
| /.gitattributes export-ignore | ||
| /.gitignore export-ignore | ||
| /.symfony.bundle.yaml export-ignore | ||
| /phpunit.xml.dist export-ignore | ||
| /phpstan.neon.dist export-ignore | ||
| /Resources/assets/test export-ignore | ||
| /Resources/assets/jest.config.js export-ignore | ||
| /Tests export-ignore |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,12 @@ | ||
| /.php_cs.cache | ||
| /.php_cs | ||
| /.phpunit.result.cache | ||
| /composer.phar | ||
| /composer.lock | ||
| /phpunit.xml | ||
| /vendor/ | ||
| /Tests/app/var | ||
| /Tests/app/public/build/ | ||
| node_modules/ | ||
| package-lock.json | ||
| yarn.lock |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,3 @@ | ||
| branches: ["2.x"] | ||
| maintained_branches: ["2.x"] | ||
| doc_dir: "Resources/doc" |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,16 @@ | ||
| # Contributing | ||
|
|
||
| Install the test app: | ||
|
|
||
| $ composer install | ||
| $ cd Tests/app | ||
| $ yarn install | ||
| $ yarn build | ||
|
|
||
| Start the test app: | ||
|
|
||
| $ symfony serve | ||
|
|
||
| ## Run tests | ||
|
|
||
| $ php vendor/bin/simple-phpunit |
| 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 <[email protected]> | ||
| * | ||
| * For the full copyright and license information, please view the LICENSE | ||
| * file that was distributed with this source code. | ||
| */ | ||
|
|
||
| namespace Symfony\UX\Collection; | ||
|
|
||
| use Symfony\Component\HttpKernel\Bundle\Bundle; | ||
|
|
||
| /** | ||
| * @author Kévin Dunglas <[email protected]> | ||
| */ | ||
| final class CollectionBundle extends Bundle | ||
| { | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,37 @@ | ||
| <?php | ||
|
|
||
| /* | ||
| * This file is part of the Symfony package. | ||
| * | ||
| * (c) Fabien Potencier <[email protected]> | ||
| * | ||
| * For the full copyright and license information, please view the LICENSE | ||
| * file that was distributed with this source code. | ||
| */ | ||
|
|
||
| namespace Symfony\UX\Collection\DependencyInjection; | ||
|
|
||
| use Symfony\Component\DependencyInjection\ContainerBuilder; | ||
| use Symfony\Component\HttpKernel\DependencyInjection\Extension; | ||
| use Symfony\UX\Collection\Form\CollectionTypeExtension; | ||
|
|
||
| /** | ||
| * @author Ryan Weaver <[email protected]> | ||
| * | ||
| * @experimental | ||
| */ | ||
| final class CollectionExtension extends Extension | ||
| { | ||
| public function load(array $configs, ContainerBuilder $container) | ||
| { | ||
| $this->registerBasicServices($container); | ||
| } | ||
|
|
||
| private function registerBasicServices(ContainerBuilder $container): void | ||
| { | ||
| $container | ||
| ->register('ux.collection.collection_extension', CollectionTypeExtension::class) | ||
| ->addTag('form.type_extension') | ||
| ; | ||
| } | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,119 @@ | ||
| <?php | ||
|
|
||
| namespace Symfony\UX\Collection\Form; | ||
|
|
||
| use Symfony\Component\Form\AbstractTypeExtension; | ||
| use Symfony\Component\Form\Extension\Core\Type\ButtonType; | ||
| use Symfony\Component\Form\Extension\Core\Type\CollectionType; | ||
| use Symfony\Component\Form\FormBuilderInterface; | ||
| use Symfony\Component\Form\FormInterface; | ||
| use Symfony\Component\Form\FormView; | ||
| use Symfony\Component\OptionsResolver\Options; | ||
| use Symfony\Component\OptionsResolver\OptionsResolver; | ||
|
|
||
| class CollectionTypeExtension extends AbstractTypeExtension | ||
| { | ||
| public static function getExtendedTypes(): iterable | ||
| { | ||
| return [CollectionType::class]; | ||
| } | ||
|
|
||
|
|
||
| public function buildForm(FormBuilderInterface $builder, array $options) | ||
| { | ||
| /** @var FormInterface|null $prototype */ | ||
| $prototype = $builder->getAttribute('prototype'); | ||
|
|
||
| if (!$prototype) { | ||
| return; | ||
| } | ||
|
|
||
| // TODO add button only if `delete_type` is defined and set `delete_type` default to null? | ||
| if ($options['allow_delete']) { | ||
| // add delete button to prototype | ||
| // TODO add toolbar here to allow extension add other buttons | ||
| $prototype->add('deleteButton', $options['delete_type'], $options['delete_options']); | ||
| } | ||
| } | ||
|
|
||
| public function buildView(FormView $view, FormInterface $form, array $options): void | ||
| { | ||
| /** @var FormInterface|null $prototype */ | ||
| $prototype = $form->getConfig()->getAttribute('prototype'); | ||
|
|
||
| if (!$prototype) { | ||
| return; | ||
| } | ||
|
|
||
| if ($options['allow_delete']) { | ||
| // add delete button to rendered elements from the Collection ResizeListener | ||
| foreach ($form as $child) { | ||
| $child->add('deleteButton', $options['delete_type'], $options['delete_options']); | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I get an
I think the solution is to add the buttons in an $builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) use ($options) {
$form = $event->getForm();
foreach ($form as $child) {
$child->add('deleteButton', $options['delete_type'], $options['delete_options']);
}
$form->add('addButton', $options['add_type'], $options['add_options']);
});There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The add button needs to be re-added to the form again on submit because it is removed in the $builder->addEventListener(FormEvents::SUBMIT, function (FormEvent $event) use ($options) {
$form = $event->getForm();
if ($form->has('addButton')) {
return;
}
$form->add('addButton', $options['add_type'], $options['add_options']);
}); |
||
| } | ||
| } | ||
|
|
||
| // TODO add button only if `add_type` is defined and set `add_type` default to null? | ||
| if ($options['allow_add']) { | ||
| // TODO add toolbar here to allow extension add other buttons | ||
| $form->add('addButton', $options['add_type'], $options['add_options']); | ||
| } | ||
| } | ||
|
|
||
| public function finishView(FormView $view, FormInterface $form, array $options): void | ||
| { | ||
| if (!$form->has('addButton')) { | ||
| return; | ||
| } | ||
|
|
||
| $addButton = $form->get('addButton'); | ||
| $form->add('addButton', $options['add_type'], $options['add_options']); | ||
| } | ||
|
|
||
| public function configureOptions(OptionsResolver $resolver) | ||
| { | ||
| $attrNormalizer = function (Options $options, $value) { | ||
| if (!isset($value['data-controller'])) { | ||
| // TODO default be `symfony--ux-collection--collection` or `collection`? | ||
| $value['data-controller'] = 'symfony--ux-collection--collection'; | ||
| } | ||
|
|
||
| $value['data-' . $value['data-controller'] . '-prototype-name-value'] = $options['prototype_name']; | ||
|
|
||
| return $value; | ||
| }; | ||
|
|
||
| $resolver->setDefaults([ | ||
| 'add_type' => ButtonType::class, // TODO add AddButtonType for easier theming and extending | ||
| 'add_options' => [], | ||
| 'delete_type' => ButtonType::class, // TODO add DeleteButtonType for easier theming and extending | ||
| 'delete_options' => [], | ||
| ]); | ||
|
|
||
| $addOptionsNormalizer = function (Options $options, $value) { | ||
| $value['attr'] = \array_merge([ | ||
| 'data-action' => $options['attr']['data-controller'] . '#add', | ||
| ], $value['attr'] ?? []); | ||
|
|
||
| return $value; | ||
| }; | ||
|
|
||
| $deleteOptionsNormalizer = function (Options $options, $value) { | ||
| $value['attr'] = \array_merge([ | ||
| 'data-action' => $options['attr']['data-controller'] . '#delete', | ||
| ], $value['attr'] ?? []); | ||
|
|
||
| return $value; | ||
| }; | ||
|
|
||
| $entryOptionsNormalizer = function (Options $options, $value) { | ||
| $value['row_attr']['data-' . $options['attr']['data-controller'] . '-target'] = 'entry'; | ||
|
|
||
| return $value; | ||
| }; | ||
|
|
||
| $resolver->setNormalizer('attr', $attrNormalizer); | ||
| $resolver->setNormalizer('add_options', $addOptionsNormalizer); | ||
| $resolver->setNormalizer('delete_options', $deleteOptionsNormalizer); | ||
| $resolver->addNormalizer('entry_options', $entryOptionsNormalizer); | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,19 @@ | ||
| Copyright (c) 2021 Kévin Dunglas | ||
|
|
||
| Permission is hereby granted, free of charge, to any person obtaining a copy | ||
| of this software and associated documentation files (the "Software"), to deal | ||
| in the Software without restriction, including without limitation the rights | ||
| to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
| copies of the Software, and to permit persons to whom the Software is furnished | ||
| to do so, subject to the following conditions: | ||
|
|
||
| The above copyright notice and this permission notice shall be included in all | ||
| copies or substantial portions of the Software. | ||
|
|
||
| THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
| IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
| FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
| AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
| LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
| OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN | ||
| THE SOFTWARE. |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,11 @@ | ||
| # Symfony UX Collection | ||
|
|
||
| **This repository is a READ-ONLY sub-tree split**. See | ||
| https://github.com/symfony/ux to create issues or submit pull requests. | ||
|
|
||
| ## Resources | ||
|
|
||
| - [Documentation](https://symfony.com/bundles/ux-collection/current/index.html) | ||
| - [Report issues](https://github.com/symfony/ux/issues) and | ||
| [send Pull Requests](https://github.com/symfony/ux/pulls) | ||
| in the [main Symfony UX repository](https://github.com/symfony/ux) |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,70 @@ | ||
| import { Controller } from '@hotwired/stimulus'; | ||
|
|
||
| class default_1 extends Controller { | ||
| constructor() { | ||
| super(...arguments); | ||
| this.index = 0; | ||
| this.controllerName = 'collection'; | ||
| } | ||
| connect() { | ||
| this.controllerName = this.context.scope.identifier; | ||
| this._dispatchEvent('collection:connect'); | ||
| } | ||
| add() { | ||
| const prototypeHTML = this.element.dataset.prototype; | ||
| if (!prototypeHTML) { | ||
| throw new Error('A "data-prototype" attribute was expected on data-controller="' + this.controllerName + '" element.'); | ||
| } | ||
| const collectionNamePattern = this.element.id.replace(/_/g, '(?:_|\\[|]\\[)'); | ||
| const newEntry = this._textToNode(prototypeHTML | ||
| .replace(this.prototypeNameValue + 'label__', this.index.toString()) | ||
| .replace(new RegExp(`(${collectionNamePattern}(?:_|]\\[))${this.prototypeNameValue}`, 'g'), `$1${this.index.toString()}`)); | ||
| this._dispatchEvent('collection:pre-add', { | ||
| entry: newEntry, | ||
| index: this.index, | ||
| }); | ||
| const entries = []; | ||
| this.element.querySelectorAll(this.itemSelectorValue | ||
| ? this.itemSelectorValue.replace('%controllerName%', this.controllerName) | ||
| : ':scope > [data-' + this.controllerName + '-target="entry"]:not([data-controller] > *)').forEach(entry => { | ||
| entries.push(entry); | ||
| }); | ||
| if (entries.length > 0) { | ||
| entries[entries.length - 1].after(newEntry); | ||
| } | ||
| else { | ||
| this.element.prepend(newEntry); | ||
| } | ||
| this._dispatchEvent('collection:add', { | ||
| entry: newEntry, | ||
| index: this.index, | ||
| }); | ||
| this.index++; | ||
| } | ||
| delete(event) { | ||
| const clickTarget = event.target; | ||
| const entry = clickTarget.closest('[data-' + this.controllerName + '-target="entry"]'); | ||
| this._dispatchEvent('collection:pre-delete', { | ||
| entry: entry, | ||
| }); | ||
| entry.remove(); | ||
| this._dispatchEvent('collection:delete', { | ||
| entry: entry, | ||
| }); | ||
| } | ||
| _textToNode(text) { | ||
| const template = document.createElement('template'); | ||
| text = text.trim(); | ||
| template.innerHTML = text; | ||
| return template.content.firstChild; | ||
| } | ||
| _dispatchEvent(name, payload = {}) { | ||
| this.element.dispatchEvent(new CustomEvent(name, { detail: payload, bubbles: true })); | ||
| } | ||
| } | ||
| default_1.values = { | ||
| prototypeName: String, | ||
| itemSelector: String, | ||
| }; | ||
|
|
||
| export { default_1 as default }; |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| module.exports = require('../../../../jest.config.js'); |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,24 @@ | ||
| { | ||
| "name": "@symfony/ux-collection", | ||
| "description": "Support for collection embedding with Symfony Form", | ||
| "license": "MIT", | ||
| "main": "dist/controller.js", | ||
| "module": "dist/controller.js", | ||
| "version": "1.0.0", | ||
| "symfony": { | ||
| "controllers": { | ||
| "collection": { | ||
| "main": "dist/controller.js", | ||
| "webpackMode": "eager", | ||
| "fetch": "eager", | ||
| "enabled": true | ||
| } | ||
| } | ||
| }, | ||
| "peerDependencies": { | ||
| "@hotwired/stimulus": "^3.0.0" | ||
| }, | ||
| "devDependencies": { | ||
| "@hotwired/stimulus": "^3.0.0" | ||
| } | ||
| } |
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
when i use this code with a simple form type this throws: "You cannot add children to a simple form. Maybe you should set the option "compound" to true?"
I'm not sure that it's a good idea to force a complex form just for frontend functionality. It seems more logical to me to put the delete button only in the template (like the maker bundle does with the submit button https://github.com/symfony/maker-bundle/blob/main/src/Resources/skeleton/crud/templates/_form.tpl.php )
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Using not the button of the form theme make theming a lot harder. And I really recommend when possible use the button which is rendered by the form theme. So it works out of the box with the different form themes and don't require special form themes again for every css framework.