sonata-project / SonataAdminBundle

The missing Symfony Admin Generator
https://docs.sonata-project.org/projects/SonataAdminBundle
MIT License
2.11k stars 1.26k forks source link

Impossible to add a new item on collection of child admin having same name as one of parent's field #7955

Closed fgueguen closed 1 year ago

fgueguen commented 1 year ago

Environment

A bug observed on a 3.107.3 version of the admin bundle, still present on 4.X version, not tested on 5.X.

Sonata packages

show

``` $ composer show --latest 'sonata-project/*' sonata-project/admin-bundle 3.107.3 4.20.0 The missing Symfony Admin Generator sonata-project/block-bundle 4.14.0 4.19.0 Symfony SonataBlockBundle sonata-project/cache 2.0.1 2.2.0 Cache library Package sonata-project/cache is abandoned, you should avoid using it. No replacement was suggested. sonata-project/datagrid-bundle 3.5.0 3.5.0 Symfony SonataDatagridBundle Package sonata-project/datagrid-bundle is abandoned, you should avoid using it. No replacement was suggested. sonata-project/doctrine-extensions 1.17.0 1.18.1 Doctrine2 behavioral extensions sonata-project/doctrine-orm-admin-bundle 3.35.3 4.8.0 Integrate Doctrine ORM into the SonataAdminBundle sonata-project/exporter 2.8.0 2.13.0 Lightweight Exporter library sonata-project/form-extensions 1.17.1 1.18.0 Symfony form extensions sonata-project/formatter-bundle 4.7.0 5.0.1 Symfony SonataFormatterBundle sonata-project/twig-extensions 1.10.0 1.12.0 Sonata twig extensions sonata-project/user-bundle 4.15.0 5.4.0 Symfony SonataUserBundle ```

Symfony packages

show

``` $ composer show --latest 'symfony/*' symfony/acl-bundle v2.3.0 v2.3.0 Symfony AclBundle symfony/asset v4.4.40 v5.4.13 Manages URL generation and versioning of web assets such as CSS stylesheets, JavaScript files and image files symfony/browser-kit v4.4.37 v5.4.11 Simulates the behavior of a web browser, allowing you to make requests, click on links and submit forms programmatically symfony/cache v4.4.41 v5.4.13 Provides an extended PSR-6, PSR-16 (and tags) implementation symfony/cache-contracts v2.5.1 v2.5.2 Generic abstractions related to caching symfony/config v4.4.41 v5.4.11 Helps you find, load, combine, autofill and validate configuration values of any kind symfony/console v4.4.41 v5.4.14 Eases the creation of beautiful and testable command line interfaces symfony/css-selector v4.4.37 v5.4.11 Converts CSS selectors to XPath expressions symfony/debug v4.4.41 v4.4.44 Provides tools to ease debugging PHP code Package symfony/debug is abandoned, you should avoid using it. Use symfony/error-handler instead. symfony/debug-bundle v4.4.37 v5.4.11 Provides a tight integration of the Symfony VarDumper component and the ServerLogCommand from MonologBridge into the Symfony full-stack framework symfony/dependency-injection v4.4.41 v5.4.13 Allows you to standardize and centralize the way objects are constructed in your application symfony/deprecation-contracts v2.5.1 v2.5.2 A generic function and convention to trigger deprecation notices symfony/doctrine-bridge v4.4.41 v5.4.14 Provides integration for Doctrine with various Symfony components symfony/dom-crawler v4.4.42 v5.4.12 Eases DOM navigation for HTML and XML documents symfony/dotenv v4.4.37 v5.4.5 Registers environment variables from a .env file symfony/error-handler v4.4.41 v5.4.14 Provides tools to manage errors and ease debugging PHP code symfony/event-dispatcher v4.4.37 v5.4.9 Provides tools that allow your application components to communicate with each other by dispatching events and listening to them symfony/event-dispatcher-contracts v1.1.12 v2.5.2 Generic abstractions related to dispatching event symfony/expression-language v4.4.41 v5.4.14 Provides an engine that can compile and evaluate expressions symfony/filesystem v4.4.39 v5.4.13 Provides basic utilities for the filesystem symfony/finder v4.4.41 v5.4.11 Finds files and directories via an intuitive fluent interface symfony/flex v1.18.7 v1.19.3 Composer plugin for Symfony symfony/form v4.4.41 v5.4.13 Allows to easily create, process and reuse HTML forms symfony/framework-bundle v4.4.41 v5.4.14 Provides a tight integration between Symfony components and the Symfony full-stack framework symfony/http-client v4.4.41 v5.4.14 Provides powerful methods to fetch HTTP resources synchronously or asynchronously symfony/http-client-contracts v2.5.1 v2.5.2 Generic abstractions related to HTTP clients symfony/http-foundation v4.4.41 v5.4.14 Defines an object-oriented layer for the HTTP specification symfony/http-kernel v4.4.41 v5.4.14 Provides a structured process for converting a Request into a Response symfony/inflector v4.4.37 v5.4.11 Converts words between their singular and plural forms (English only) Package symfony/inflector is abandoned, you should avoid using it. Use EnglishInflector from the String component instead. symfony/intl v4.4.41 v5.4.14 Provides a PHP replacement layer for the C intl extension that includes additional data from the ICU library symfony/mailer v4.4.41 v5.4.13 Helps sending emails symfony/maker-bundle v1.39.0 v1.43.0 Symfony Maker helps you create empty commands, controllers, form classes, tests and more so you can forget about writing boilerplate code. symfony/mime v4.4.41 v5.4.14 Allows manipulating MIME messages symfony/monolog-bridge v4.4.37 v5.4.10 Provides integration for Monolog with various Symfony components symfony/monolog-bundle v3.7.1 v3.8.0 Symfony MonologBundle symfony/options-resolver v4.4.37 v5.4.11 Provides an improved replacement for the array_replace PHP function symfony/phpunit-bridge v5.4.8 v6.1.6 Provides utilities for PHPUnit, especially user deprecation notices management symfony/polyfill-intl-grapheme v1.25.0 v1.26.0 Symfony polyfill for intl's grapheme_* functions symfony/polyfill-intl-icu v1.25.0 v1.26.0 Symfony polyfill for intl's ICU-related data and classes symfony/polyfill-intl-idn v1.25.0 v1.26.0 Symfony polyfill for intl's idn_to_ascii and idn_to_utf8 functions symfony/polyfill-intl-normalizer v1.25.0 v1.26.0 Symfony polyfill for intl's Normalizer class and related functions symfony/polyfill-mbstring v1.25.0 v1.26.0 Symfony polyfill for the Mbstring extension symfony/polyfill-php72 v1.25.0 v1.26.0 Symfony polyfill backporting some PHP 7.2+ features to lower PHP versions symfony/polyfill-php73 v1.25.0 v1.26.0 Symfony polyfill backporting some PHP 7.3+ features to lower PHP versions symfony/polyfill-php80 v1.25.0 v1.26.0 Symfony polyfill backporting some PHP 8.0+ features to lower PHP versions symfony/polyfill-php81 v1.25.0 v1.26.0 Symfony polyfill backporting some PHP 8.1+ features to lower PHP versions symfony/polyfill-uuid v1.25.0 v1.26.0 Symfony polyfill for uuid functions symfony/process v4.4.41 v5.4.11 Executes commands in sub-processes symfony/property-access v4.4.41 v5.4.11 Provides functions to read and write from/to an object or array using a simple string notation symfony/property-info v4.4.40 v5.4.14 Extracts information about PHP class' properties using metadata of popular sources symfony/proxy-manager-bridge v4.4.39 v5.4.6 Provides integration for ProxyManager with various Symfony components symfony/psr-http-message-bridge v2.1.2 v2.1.3 PSR HTTP message bridge symfony/routing v4.4.41 v5.4.11 Maps an HTTP request to a set of configuration variables symfony/security v4.4.41 v4.4.47 Provides a complete security system for your web application symfony/security-acl v3.3.1 v3.3.2 Symfony Security Component - ACL (Access Control List) symfony/security-bundle v4.4.41 v5.4.11 Provides a tight integration of the Security component into the Symfony full-stack framework symfony/serializer v4.4.41 v5.4.14 Handles serializing and deserializing data structures, including object graphs, into array structures or other formats like XML and JSON. symfony/service-contracts v2.5.1 v2.5.2 Generic abstractions related to writing services symfony/stopwatch v4.4.38 v5.4.13 Provides a way to profile code symfony/string v5.4.8 v5.4.14 Provides an object-oriented API to strings and deals with bytes, UTF-8 code points and grapheme clusters in a unified way symfony/templating v4.4.37 v5.4.11 Provides all the tools needed to build any kind of template system symfony/translation v4.4.41 v5.4.14 Provides tools to internationalize your application symfony/translation-contracts v2.5.1 v2.5.2 Generic abstractions related to translation symfony/twig-bridge v4.4.41 v5.4.14 Provides integration for Twig with various Symfony components symfony/twig-bundle v4.4.41 v5.4.8 Provides a tight integration of Twig into the Symfony full-stack framework symfony/validator v4.4.41 v5.4.14 Provides tools to validate values symfony/var-dumper v4.4.41 v5.4.14 Provides mechanisms for walking through any arbitrary PHP variable symfony/var-exporter v4.4.41 v5.4.10 Allows exporting any serializable PHP data structure to plain PHP code symfony/web-link v4.4.37 v5.4.3 Manages links between resources symfony/web-profiler-bundle v4.4.41 v5.4.14 Provides a development tool that gives detailed information about the execution of any request symfony/webpack-encore-bundle v1.14.1 v1.16.0 Integration with your Symfony app & Webpack Encore! symfony/workflow v4.4.41 v5.4.11 Provides tools for managing a workflow or finite state machine symfony/yaml v4.4.37 v5.4.14 Loads and dumps YAML files ```

PHP version

$ php -v
PHP 7.4.2 (cli) (built: Feb  1 2020 19:47:36) ( NTS )
Copyright (c) The PHP Group
Zend Engine v3.4.0, Copyright (c) Zend Technologie

Subject

This issue is related to the retrieving of a form fragment when adding an element to a collection (call to /admin/core/append-form-field-element on "Add new"):

When an admin embeds another one, and these admins both have a collection using the same name, it becomes impossible to add an element to the collection of the child admin.

For example, let's say we have a Content entity with the $metadata and $tags (collection) properties. $metadata is a relation to a Metadata entity which also defines a $tags collection. We then embed the MetadataAdmin into the ContentAdmin and handle the "tags" fields of these admins as Sonata collections.

When the user clicks on "Add new" to add a tag to the content, the form to add a new tag is correctly retrieved and displayed. Adding a content tag is thus possible. When the user clicks on "Add new" to add a tag to the metadata of the content, the form to add a new tag is not returned in the response.

The code

Entities

The Content entity, defining the $tags collection and a OneToOne to Metadata:

<?php

namespace App\Entity;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 */
class Content
{
    /**
     * @ORM\Id
     * @ORM\GeneratedValue
     * @ORM\Column(type="integer")
     */
    private ?int $id = null;

    /**
     * @ORM\OneToOne(targetEntity="Metadata", cascade={"persist", "remove"}, orphanRemoval=true)
     */
    private ?Metadata $metadata = null;

    /**
     * @ORM\OneToMany(targetEntity="Tag", cascade={"persist"}, mappedBy="content")
     */
    private Collection $tags;

    public function __construct()
    {
        $this->tags = new ArrayCollection();
    }

    public function getId(): ?int
    {
        return $this->id;
    }

    public function getMetadata(): ?Metadata
    {
        return $this->metadata;
    }

    public function setMetadata(?Metadata $metadata)
    {
        $this->metadata = $metadata;
    }

    public function getTags(): Collection
    {
        return $this->tags;
    }

    public function addTag(Tag $tag)
    {
        $this->tags[] = $tag;
        $tag->setContent($this);

        return $this;
    }

    public function removeTag(Tag $tag)
    {
        $this->tags->removeElement($tag);
    }
}

Like the Content entity, the Metadata entity has a property $tags which defines a collection:

<?php

namespace App\Entity;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 */
class Metadata
{
    /**
     * @ORM\Id
     * @ORM\GeneratedValue
     * @ORM\Column(type="integer")
     */
    private ?int $id = null;

    /**
     * @ORM\OneToMany(targetEntity="Tag", cascade={"persist"}, mappedBy="metadata")
     */
    private Collection $tags;

    public function __construct()
    {
        $this->tags = new ArrayCollection();
    }

    public function getId(): ?int
    {
        return $this->id;
    }

    public function getTags(): Collection
    {
        return $this->tags;
    }

    public function addTag(Tag $tag)
    {
        $this->tags[] = $tag;
        $tag->setMetadata($this);

        return $this;
    }

    public function removeTag(Tag $tag)
    {
        $this->tags->removeElement($tag);
    }
}

To keep it simple, both the $tags of Content and Metadata targets the same Tag entity, but it could be two different entities, it doesn't matter.

show Tag entity

```php label; } public function getLabel(): ?string { return $this->label; } public function setLabel(?string $label) { $this->label = $label; } public function getContent(): ?Content { return $this->content; } public function setContent(?Content $content) { $this->content = $content; } public function getMetadata(): ?Metadata { return $this->metadata; } public function setMetadata(?Metadata $metadata) { $this->metadata = $metadata; } } ```

Admins

The ContentAdmin embeds the MetadataAdmin by using an AdminType, and it uses a Sonata CollectionType for its "tags" field:


use Sonata\AdminBundle\Form\Type\AdminType;
use Sonata\Form\Type\CollectionType;

final class ContentAdmin extends AbstractAdmin
{
    protected function configureFormFields(FormMapper $form): void
    {
        $form
            ->with('Content')
                ->add('tags', CollectionType::class, [ 
                    'by_reference' => false,
                ], [
                    'edit' => 'inline',
                    'inline' => 'table',
                ])
            ->end()
            ->with('Metadata')
                ->add('metadata', AdminType::class, [
                    'label' => false,
                ], [
                    'edit' => 'inline',
                    'inline' => 'table',
                ])
            ->end();
    }

    // ...
}

The MetadataAdmin uses a Sonata CollectionType for its "tags" field too:


use Sonata\Form\Type\CollectionType;

final class MetadataAdmin extends AbstractAdmin
{
    protected function configureFormFields(FormMapper $form): void
    {
        $form
            ->add('tags', CollectionType::class, [
                'by_reference' => false,
            ], [
                'edit' => 'inline',
                'inline' => 'table',
            ]);
    }

    // ...
}

Analysis

The problem seems to be related to the following condition in AdminHelper::appendFormFieldElement#L201:

if ($childFormBuilder && $admin->hasFormFieldDescription($childFormBuilder->getName())) {

For the two calls on the respective "Add new", $childFormBuilder->getName() returns the same value "tags".

So this condition returns true even for the call related to the embedded admin, because the ContentAdmin has a "tags" field.

But it should not. There is a confusion here between the tags of the ContentAdmin and the tags of the MetadataAdmin. For the call related to the embedded admin, it should pass in the else of the condition, which concerns the nested elements.

Final note

If we change the property $tags in the parent to something else than a collection, there is a 500 errror.

For example, We may have tags as string in Content and still have tags as collection in Metadata. Let's update Content and ContentAdmin accordingly:

<?php
class Content
{
    // ...

    /**
     * @ORM\Column(name="tags", type="string")
     */
    private ?string $tags = null;
}
final class ContentAdmin extends AbstractAdmin
{
    protected function configureFormFields(FormMapper $form): void
    {
        $form
            ->with('Content')
               ->add('tags', TextType::class)
               // ...
    }

With this change the call made on "Add new" on the metadata tags collection returns a 500 on AdminHelper::appendFormFieldElement#L185:

ErrorException:
Warning: Invalid argument supplied for foreach()

  at vendor/sonata-project/admin-bundle/src/Admin/AdminHelper.php:185
  at Sonata\AdminBundle\Admin\AdminHelper->appendFormFieldElement(object(ContentAdmin), object(Content), 's63584152cc90c_metadata_tags')
     (vendor/sonata-project/admin-bundle/src/Action/AppendFormFieldElementAction.php:115)
  at Sonata\AdminBundle\Action\AppendFormFieldElementAction->__invoke(object(Request))
     (vendor/symfony/http-kernel/HttpKernel.php:158)
  at Symfony\Component\HttpKernel\HttpKernel->handleRaw(object(Request), 1)
     (vendor/symfony/http-kernel/HttpKernel.php:80)
  at Symfony\Component\HttpKernel\HttpKernel->handle(object(Request), 1, true)
     (vendor/symfony/http-kernel/Kernel.php:201)
  at Symfony\Component\HttpKernel\Kernel->handle(object(Request))
     (public/index.php:25)
VincentLanglet commented 1 year ago

HI, thanks for the report.

Do you see a way to change the

if ($childFormBuilder && $admin->hasFormFieldDescription($childFormBuilder->getName())) {

code then ?

Or maybe we should find a way to have different name for those formBuilder.

fgueguen commented 1 year ago

By dumping the $childFormBuilder, I see an attribute 'sonata_admin', an array with 'admin' key.

This admin value is different for the two calls. For the call made on the parent, it's the ContentAdmin, for the call on the child it's the MetadataAdmin.

So I guess we can just retrieve this value and compare it to the $admin. If it's the same we are on the parent, else on a nested element, something like :

$childFormBuilderAdmin = $childFormBuilder ? ($childFormBuilder->getAttribute('sonata_admin', [])['admin'] ?? null) : null;
$isMainAdmin = $childFormBuilderAdmin === $admin;

if ($isMainAdmin && $admin->hasFormFieldDescription($childFormBuilder->getName())) {
    // ...

That works on my local project.

VincentLanglet commented 1 year ago

Do you mind starting a PR with those changes ? We'll see if it's the best solution.

Best would be to add a failing functional test, which pass after you change.

fgueguen commented 1 year ago

Sure, I'll provide one as soon as possible

fgueguen commented 1 year ago

I started a fix on the 3.x branch, the version we are currently using on our project. Is it still a working branch or should I propose a fix on 4.x ?

VincentLanglet commented 1 year ago

I started a fix on the 3.x branch, the version we are currently using on our project. Is it still a working branch or should I propose a fix on 4.x ?

We stopped maintaining the 3.x when we releasing the 4.x version. So it's kinda unmaintained for 1 year now. As an example the Ci has tons of failure on https://github.com/sonata-project/SonataAdminBundle/pull/7963 It's better to do this fix on 4.x branch. (And I recommend you to plan a 3 -> 4 migration for you project soon ^^)