Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
30 commits
Select commit Hold shift + click to select a range
ae5d325
UX FormCollection
stakovicz May 3, 2021
c305f0c
Remove hard coded property_name __name__
stakovicz May 4, 2021
5e6dd84
PHP CS Fixer
stakovicz May 4, 2021
eea2313
First jests
stakovicz May 4, 2021
f651d90
Rename CollectionType > UXCollectionType
stakovicz May 6, 2021
cc02076
Rename CollectionType > UXCollectionType
stakovicz May 6, 2021
dceb2cf
DependencyInjection Clean
stakovicz May 6, 2021
dfb54f8
Fix .gitattributes
stakovicz May 6, 2021
9300cda
Move default values
stakovicz May 7, 2021
ec4342a
Predefined theme or not
stakovicz May 23, 2021
b4f40cd
Update src/FormCollection/README.md
stakovicz May 24, 2021
0584757
Update src/FormCollection/README.md
stakovicz May 24, 2021
abd2b8f
Update src/FormCollection/README.md
stakovicz May 24, 2021
3996f3b
Update src/FormCollection/Resources/views/form_theme_div.html.twig
stakovicz May 24, 2021
aaa6811
Update src/FormCollection/README.md
stakovicz May 24, 2021
4791ff9
Update src/FormCollection/Resources/views/form_theme_table.html.twig
stakovicz May 24, 2021
8539ff9
Split in 4 options
stakovicz May 24, 2021
2d1ed04
Default startIndex value
stakovicz Jun 6, 2021
1e3105d
Update src/FormCollection/Resources/views/form_theme_div.html.twig
stakovicz Jul 21, 2021
0a9cc54
Update src/FormCollection/Resources/views/form_theme_div.html.twig
stakovicz Jul 21, 2021
94be94c
Update src/FormCollection/Resources/views/form_theme_table.html.twig
stakovicz Jul 21, 2021
c805c0e
Update src/FormCollection/Resources/views/form_theme_table.html.twig
stakovicz Jul 21, 2021
e56d04b
Fix coding-style-js
stakovicz Nov 6, 2021
7467cee
Prettier
stakovicz Nov 6, 2021
a8c730c
Merge branch 'symfony:2.x' into main
stakovicz Jan 19, 2022
ecd774a
Merge branch 'symfony:2.x' into main
stakovicz May 7, 2022
25d8306
Rebase and refresh the code
stakovicz May 21, 2022
8e5cd8a
fix TU
stakovicz May 21, 2022
3b110f9
change buttons attr
stakovicz May 21, 2022
c36157c
Merge branch 'symfony:2.x' into main
stakovicz Jun 14, 2022
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
3 changes: 3 additions & 0 deletions src/FormCollection/.gitattributes
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
/.gitattributes export-ignore
/.gitignore export-ignore
/Resources/assets/test export-ignore
32 changes: 32 additions & 0 deletions src/FormCollection/DependencyInjection/FormCollectionExtension.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
<?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\FormCollection\DependencyInjection;

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\UX\FormCollection\Form\UXCollectionType;

/**
* @internal
*/
class FormCollectionExtension extends Extension
{
public function load(array $configs, ContainerBuilder $container)
{
$container
->setDefinition('form.ux_collection', new Definition(UXCollectionType::class))
->addTag('form.type')
->setPublic(false)
;
}
}
77 changes: 77 additions & 0 deletions src/FormCollection/Form/UXCollectionType.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
<?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\FormCollection\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\CollectionType;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormView;
use Symfony\Component\OptionsResolver\Options;
use Symfony\Component\OptionsResolver\OptionsResolver;

/**
* @final
* @experimental
*/
class UXCollectionType extends AbstractType
{
public function getParent()
{
return CollectionType::class;
}

public function configureOptions(OptionsResolver $resolver)
{
$defaultButtonAddOptions = [
'label' => 'Add',
'class' => '',
];
$defaultButtonDeleteOptions = [
'label' => 'Remove',
'class' => '',
];
Copy link
Member

Choose a reason for hiding this comment

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

I'd also like a label_html option which is set to a boolean (defaults to false). If true, we would render the label "not escaped" (i.e. raw). Basically, we're trying to accomplish this: https://symfony.com/blog/new-in-symfony-5-1-form-improvements#allow-html-contents-in-form-labels

This would allow, for example, FontAwesome icons to be used with the buttons.

$resolver->setDefaults([
'button_add_options' => $defaultButtonAddOptions,
'button_delete_options' => $defaultButtonDeleteOptions,
]);

$resolver->setAllowedTypes('button_add_options', 'array');
$resolver->setAllowedTypes('button_delete_options', 'array');

$resolver->setNormalizer('button_add_options', function (Options $options, $value) use ($defaultButtonAddOptions) {
$value['label'] = $value['label'] ?? $defaultButtonAddOptions['label'];
$value['class'] = $value['class'] ?? $defaultButtonAddOptions['class'];

return $value;
});
$resolver->setNormalizer('button_delete_options', function (Options $options, $value) use ($defaultButtonDeleteOptions) {
$value['label'] = $value['label'] ?? $defaultButtonDeleteOptions['label'];
$value['class'] = $value['class'] ?? $defaultButtonDeleteOptions['class'];

return $value;
});
Copy link
Member

Choose a reason for hiding this comment

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

I think we should set 'by_reference' => true to override the parent CollectionType. Forgetting this is a big "WTF" moment. And so, since we're introducing this field new, let's use this "better" default setting.

}

public function finishView(FormView $view, FormInterface $form, array $options)
{
parent::finishView($view, $form, $options);

$view->vars['button_add_options'] = $options['button_add_options'];
$view->vars['button_delete_options'] = $options['button_delete_options'];
$view->vars['prototype_name'] = $options['prototype_name'];
}

public function getBlockPrefix()
{
return 'ux_collection';
}
}
22 changes: 22 additions & 0 deletions src/FormCollection/FormCollectionBundle.php
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 <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\UX\FormCollection;

use Symfony\Component\HttpKernel\Bundle\Bundle;

/**
* @final
* @experimental
*/
class FormCollectionBundle extends Bundle
{
}
19 changes: 19 additions & 0 deletions src/FormCollection/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
Copyright (c) 2020-2021 Fabien Potencier

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.
190 changes: 190 additions & 0 deletions src/FormCollection/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,190 @@
# UX Form Collection
Copy link
Member

Choose a reason for hiding this comment

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

We're now doing this as an index.rst file. So, it just needs to move, then convert to RST

Copy link
Author

Choose a reason for hiding this comment

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

I don't see any RST files in the other parts 🤨. They are all in .md

Copy link
Contributor

Choose a reason for hiding this comment

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

Your branch may be a little out-of-date, see eg. https://github.com/symfony/ux/tree/2.x/src/Chartjs/Resources/doc

Copy link
Author

Choose a reason for hiding this comment

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

Thanks, I had not looked in this file 😬


Symfony UX Form collection is a Symfony bundle providing light UX for collection
Copy link
Member

Choose a reason for hiding this comment

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

Suggested change
Symfony UX Form collection is a Symfony bundle providing light UX for collection
Symfony UX Form collection is a Symfony bundle providing JavaScript-powered "add" and "remove"
buttons to your `CollectionType` fields.

It'd be GREAT to have a little screenshot :)

in Symfony Forms.

## Installation

UX Form Collection requires PHP 7.2+ and Symfony 4.4+.

Install this bundle using Composer and Symfony Flex:

```sh
composer require symfony/ux-form-collection

# Don't forget to install the JavaScript dependencies as well and compile
yarn install --force
yarn encore dev
```

Also make sure you have at least version 2.0 of [@symfony/stimulus-bridge](https://github.com/symfony/stimulus-bridge)
in your `package.json` file.

## Use predefined theme

You need to select the right theme from the one you are using:
Copy link
Member

Choose a reason for hiding this comment

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

Suggested change
You need to select the right theme from the one you are using:
First, choose a form theme to use for styling your collection type:


```yaml
# config/packages/twig.yaml
twig:
# For bootstrap for example
form_themes: ['@FormCollection/form_theme_div.html.twig']
Copy link
Member

Choose a reason for hiding this comment

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

I think we should only have one form theme (form_theme_div.html.twig). If we DID have a 2nd form theme, I would make it a bootstrap theme so that the user could instantly get something nice-looking inside of Bootstrap... but I'm not sure that's necessary because it's really easy to add btn btn-primary classes to the buttons from within the form.

Anyways, if the user needs to heavily customize their buttons, let's let them create their own form theme to override our's. Also, I think we should prevent the user from needing to do this step at all. We can automatically add this form theme for them:

public function prepend(ContainerBuilder $container)
{
// Register the Dropzone form theme if TwigBundle is available
$bundles = $container->getParameter('kernel.bundles');
if (!isset($bundles['TwigBundle'])) {
return;
}
$container->prependExtensionConfig('twig', ['form_themes' => ['@Dropzone/form_theme.html.twig']]);
}
(don't forget the PrependExtensionInterface.

```

There are 2 predefined themes available:

- `@FormCollection/form_theme_div.html.twig`
- `@FormCollection/form_theme_table.html.twig`

[Check the Symfony doc](https://symfony.com/doc/4.4/form/form_themes.html) for the different ways to set themes in Symfony.

## Use a custom form theme
Copy link
Member

Choose a reason for hiding this comment

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

Let's move this section down, below Usage. And we can call it: Customizing how the Field Renders.


Consider your `BlogFormType` form set up and with a comments field that is a `CollectionType`, you can
render it in your template:

```twig
{% macro commentFormRow(commentForm) %}
Copy link
Contributor

Choose a reason for hiding this comment

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

Why a macro instead of a "real" form theme?

Copy link
Author

Choose a reason for hiding this comment

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

It's @weaverryan's idea. It is easier and more flexible to implement.

<div
class="col-4"
data-symfony--ux-form-collection--collection-target="entry"
Copy link
Member

Choose a reason for hiding this comment

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

We should show {{ stimulus_controller() }} here, and {{ stimulus_action() }} and `{{ stimulus_target() }} in the other places.

>
{{ form_errors(commentForm) }}
{{ form_row(commentForm.content) }}
{{ form_row(commentForm.otherField) }}

<button type="button" data-action="symfony--ux-form-collection--collection#delete">
Remove
Copy link
Contributor

Choose a reason for hiding this comment

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

Why not use option text from the FormType?

Copy link
Contributor

Choose a reason for hiding this comment

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

Suggested change
Remove
{{ button_delete_text|trans }}

</button>
</div>
{% endmacro %}

<div
class="row"
data-controller="symfony--ux-form-collection--collection"
data-prototype="{{ _self.commentFormRow(form.comments.vars.prototype)|e }}"
>
{% for commentForm in form.comments %}
{{ _self.commentFormRow(commentForm) }}
{% endfor %}

<button type="button" data-action="symfony--ux-form-collection--collection#add">
Add Another
Copy link
Contributor

Choose a reason for hiding this comment

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

Why not use option text from the FormType?

Copy link
Contributor

Choose a reason for hiding this comment

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

Suggested change
Add Another
{{ button_add_text|trans }}

</button>
</div>
```

## Usage

The most common usage of Form Collection is to use it as a replacement of
the native CollectionType class:

```php
// ...
use Symfony\UX\FormCollection\Form\UXCollectionType;

class BlogFormType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
// ...
->add('comments', UXCollectionType::class, [
Copy link
Member

Choose a reason for hiding this comment

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

To be as helpful as possible, I think we need to show the user a simple CommentType class. And then, use that here with 'entry_type' => CommentType::class`.

Overall, this is how my example looks locally - I think these options are helpful to all show!

'allow_add' => true,
'allow_delete' => true,
'entry_type' => FileType::class,
// ideally UXCollectionType can set this for us
'by_reference' => false,
'entry_options' => [
    // hides the "0", "1", "2" labels on the embedded forms
    'label' => false,
],
'button_add_options' => [
    'label' => '<span class="fa fa-plus"></span>',
    'label_html' => true,
    'class' => 'btn btn-secondary btn-sm'
],
'button_delete_options' => [
    'label' => '<span class="fa fa-times"></span>',
    'label_html' => true,
    'class' => 'btn btn-danger btn-sm'
],

// ...
'button_add_options' => [
'label' => 'Add', // Default text for the add button (used by predefined theme)
'class' => 'btn btn-outline-primary', // Add HTML classes to the add button (used by predefined theme)
],
'button_delete_options' => [
'label' => 'Remove', // Default text for the delete button (used by predefined theme)
'class' => 'btn btn-outline-secondary', // Add HTML classes to the add button (used by predefined theme)
],
])
// ...
;
}

// ...
}
```

You can display it using Twig as you would normally with any form:

```twig
{# edit.html.twig #}

{{ form_start(form) }}
{# ... #}
{{ form_row(comments) }}
Copy link
Contributor

Choose a reason for hiding this comment

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

Suggested change
{{ form_row(comments) }}
{{ form_row(form.comments) }}

{# ... #}
{{ form_end(form) }}
```
Copy link
Member

Choose a reason for hiding this comment

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

Somewhere, we need to mention that, in order for this to work, they likely need orphanRemoval and cascade=['persist'] on their entities. This is what my field looks like:

#[ORM\OneToMany(mappedBy: 'directory', targetEntity: File::class, orphanRemoval: true, cascade: ['persist'])]
private $files;


### Extend the default behavior

Symfony UX Form Collection allows you to extend its default behavior using a custom Stimulus controller:

```js
// mycollection_controller.js

import { Controller } from 'stimulus';

export default class extends Controller {
connect() {
this.element.addEventListener('collection:pre-connect', this._onPreConnect);
this.element.addEventListener('collection:connect', this._onConnect);
this.element.addEventListener('collection:pre-add', this._onPreAdd);
this.element.addEventListener('collection:add', this._onAdd);
this.element.addEventListener('collection:pre-delete', this._onPreDelete);
this.element.addEventListener('collection:delete', this._onDelete);
}

disconnect() {
// You should always remove listeners when the controller is disconnected to avoid side effects
this.element.removeEventListener('collection:pre-connect', this._onPreConnect);
this.element.removeEventListener('collection:connect', this._onConnect);
}

_onPreConnect(event) {
// The collection is not yet connected
console.log(event.detail.allowAdd); // Access to the allow_add option of the form
console.log(event.detail.allowDelete); // Access to the allow_delete option of the form
}

_onConnect(event) {
// Same as collection:pre-connect event
}

_onPreAdd(event) {
console.log(event.detail.index); // Access to the curent index will be added
console.log(event.detail.element); // Access to the element will be added
}

_onAdd(event) {
// Same as collection:pre-add event
}

_onPreDelete(event) {
console.log(event.detail.index); // Access to the index will be removed
console.log(event.detail.element); // Access to the elemnt will be removed
}

_onDelete(event) {
// Same as collection:pre-delete event
}
}
```

Then in your render call, add your controller as an HTML attribute:

```php
$builder
// ...
->add('comments', UXCollectionType::class, [
// ...
'attr' => [
// Change the controller name
'data-controller' => 'mycollection'
]
]);
```
4 changes: 4 additions & 0 deletions src/FormCollection/Resources/assets/.babelrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"presets": ["@babel/env"],
"plugins": ["@babel/plugin-proposal-class-properties"]
}
Loading