api-platform / admin

A beautiful and fully-featured administration interface builder for hypermedia APIs
https://api-platform.com/docs/admin/
MIT License
480 stars 130 forks source link

SimpleFormIterator issue when editing resources #485

Open gaspardphilibert opened 1 year ago

gaspardphilibert commented 1 year ago

API Platform version(s) affected: 3.0.2 (also 2.6.8 with last Admin version)

Description
Since react-admin 4.4+, I am not able to dynamically create sub-elements when editing a resource. Let's say I have Book and Author resources, you can create books from the Author edit page thanks to an ArrayInput and a SimpleFormIterator. When I tried to add Books to an Author with the Author edit page, the following error occurred : No resource associated to "".

How to reproduce
Here is an example repo to reproduce my issue : https://github.com/gaspardphilibert/issue-api-platform-admin-simpleformiterator. To experience the bug, you can create an Author with one Book, then edit the Author and try to add another Book. You shouldn't be able to add the second Book.

The reason
Version 4.4.0 of react-admin fixes an issue (https://github.com/marmelab/react-admin/pull/8204) linked to SimpleFormIterator default values when adding a record. It seems that it takes the first array value and reset its fields to make a default value for new elements. Obviously, during the process an empty @id field is also injected. So, when I add a new value in my SimpleFormIterator and save the entity, it sends the array with an item with an empty string @id. Like this for example :

{
    "@context": "/contexts/Author",
    "@id": "/authors/1",
    "@type": "Author",
    "name": "Shakespeare",
    "books": [
        {
            "@id": "/books/1",
            "@type": "Books",
            "name": "Roméo et Juliette"
        },
        {
            "@id": "",
            "@type": "",
            "name": "Macbeth"
        }
    ],
    "id": "/authors/1"
}

Hence the No resource associated to "". error.

Possible Solution
I used the transform property (dirtyFix function in my example repo) on the Edit element to remove the empty @id and it worked well but I am wondering if it's the best solution (I am quite new in the API Platform world, maybe it could be solved at a lower level).

Thanks for your help !

alanpoulain commented 1 year ago

Maybe we should add your "dirty fix" into the InputGuesser? I don't see a better solution.