Skip to content
Draft
Show file tree
Hide file tree
Changes from 1 commit
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
Prev Previous commit
Next Next commit
Implement collection type as form extension
  • Loading branch information
alexander-schranz committed Jul 19, 2022
commit 183c400ad361f13a0d8cf67ae554cb60f59fe332
37 changes: 37 additions & 0 deletions src/Collection/DependencyInjection/CollectionExtension.php
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')
;
}
}
111 changes: 111 additions & 0 deletions src/Collection/Form/CollectionTypeExtension.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
<?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']);
Copy link

@connorhu connorhu Jul 4, 2023

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?"

$builder->add('fields', CollectionType::class, [
            'entry_type' => ChoiceType::class,

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 )

Copy link
Contributor Author

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.

}
}

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']);
Copy link

@ihmels ihmels Aug 5, 2022

Choose a reason for hiding this comment

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

I get an AlreadySubmittedException when the form is submitted and shown again (e. g. due to validation errors).

You cannot add children to a submitted form.

I think the solution is to add the buttons in an FormEvents::PRE_SET_DATA event listener in buildForm():

$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']);
});

Copy link

@ihmels ihmels Aug 5, 2022

Choose a reason for hiding this comment

The 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 ResizeFormListener.

$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 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,
'add_options' => [],
'delete_type' => ButtonType::class,
'delete_options' => [],
]);

$addOptionsNormalizer = function (Options $options, $value) {
$value['block_name'] = 'add_button';
$value['attr'] = \array_merge([
'data-action' => $options['attr']['data-controller'] . '#add',
], $value['attr'] ?? []);

return $value;
};

$deleteOptionsNormalizer = function (Options $options, $value) {
$value['block_name'] = 'delete_button';
$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);
}
}
120 changes: 54 additions & 66 deletions src/Collection/Resources/assets/dist/controller.js
Original file line number Diff line number Diff line change
@@ -1,82 +1,70 @@
import { Controller } from '@hotwired/stimulus';

const DEFAULT_ITEMS_SELECTOR = ':scope > :is(div, fieldset)';
var ButtonType;
(function (ButtonType) {
ButtonType[ButtonType["Add"] = 0] = "Add";
ButtonType[ButtonType["Delete"] = 1] = "Delete";
})(ButtonType || (ButtonType = {}));
class default_1 extends Controller {
constructor() {
super(...arguments);
this.index = 0;
this.controllerName = 'collection';
}
connect() {
this.connectCollection(this.element);
this.controllerName = this.context.scope.identifier;
this._dispatchEvent('collection:connect');
}
connectCollection(parent) {
parent.querySelectorAll('[data-prototype]').forEach((el) => {
const collectionEl = el;
const items = this.getItems(collectionEl);
collectionEl.dataset.currentIndex = items.length.toString();
this.addAddButton(collectionEl);
this.getItems(collectionEl).forEach((itemEl) => this.addDeleteButton(collectionEl, itemEl));
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,
});
}
getItems(collectionElement) {
return collectionElement.querySelectorAll(collectionElement.dataset.itemsSelector || DEFAULT_ITEMS_SELECTOR);
}
createButton(collectionEl, buttonType) {
var _a;
const attributeName = `${ButtonType[buttonType].toLowerCase()}ButtonTemplateId`;
const buttonTemplateID = (_a = collectionEl.dataset[attributeName]) !== null && _a !== void 0 ? _a : this[`${attributeName}Value`];
if (buttonTemplateID && 'content' in document.createElement('template')) {
const buttonTemplate = document.getElementById(buttonTemplateID);
if (!buttonTemplate)
throw new Error(`template with ID "${buttonTemplateID}" not found`);
const fragment = buttonTemplate.content.cloneNode(true);
if (1 !== fragment.children.length)
throw new Error('template with ID "${buttonTemplateID}" must have exactly one child');
return fragment.firstElementChild;
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);
}
const button = document.createElement('button');
button.type = 'button';
button.textContent = buttonType === ButtonType.Add ? 'Add' : 'Delete';
return button;
else {
this.element.prepend(newEntry);
}
this._dispatchEvent('collection:add', {
entry: newEntry,
index: this.index,
});
this.index++;
}
addItem(collectionEl) {
const currentIndex = collectionEl.dataset.currentIndex;
collectionEl.dataset.currentIndex++;
const collectionNamePattern = collectionEl.id.replace(/_/g, '(?:_|\\[|]\\[)');
const prototype = collectionEl.dataset.prototype
.replace('__name__label__', currentIndex)
.replace(new RegExp(`(${collectionNamePattern}(?:_|]\\[))__name__`, 'g'), `$1${currentIndex}`);
const fakeEl = document.createElement('div');
fakeEl.innerHTML = prototype;
const itemEl = fakeEl.firstElementChild;
this.connectCollection(itemEl);
this.addDeleteButton(collectionEl, itemEl);
const items = this.getItems(collectionEl);
items.length ? items[items.length - 1].insertAdjacentElement('afterend', itemEl) : collectionEl.prepend(itemEl);
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,
});
}
addAddButton(collectionEl) {
const addButton = this.createButton(collectionEl, ButtonType.Add);
addButton.onclick = (e) => {
e.preventDefault();
this.addItem(collectionEl);
};
collectionEl.appendChild(addButton);
_textToNode(text) {
const template = document.createElement('template');
text = text.trim();
template.innerHTML = text;
return template.content.firstChild;
}
addDeleteButton(collectionEl, itemEl) {
const deleteButton = this.createButton(collectionEl, ButtonType.Delete);
deleteButton.onclick = (e) => {
e.preventDefault();
itemEl.remove();
};
itemEl.appendChild(deleteButton);
_dispatchEvent(name, payload = {}) {
this.element.dispatchEvent(new CustomEvent(name, { detail: payload, bubbles: true }));
}
}
default_1.values = {
addButtonTemplateId: "",
disableAddButton: false,
deleteButtonTemplateId: "",
disableDeleteButton: false,
prototypeName: String,
itemSelector: String,
};

export { default_1 as default };
Loading