api-platform
api-platform copied to clipboard
loadClassMetadata properties are ignored in GET operations
API Platform version(s) affected: 2.1
Description
Properties or associations added through Doctrine's loadClassMetadata event do not work in GET operations. They work properly in POST/PUT and the value gets stored in the database, but when doing a GET operation the same properties come up as empty.
My suspicion is that maybe data providers get initialized before doctrine listeners are registered, but my knowledge on the internals of API platform is not good enough to try and fix, so I'm writing it here.
How to reproduce
- Create a doctrine listener and bind
loadClassMetadatato it - Create an entity and add a property or an association to it through the listener.
- Run a POST operation to create an object. The created property will work fine and show the correct value. The database will also have the correct value stored.
- Run a GET operation on either the collection or the item. The created property will be null even if the value in the database is correct. Doctrine effectively does not know about the property.
Possible Solution
In my project I worked around the issue by creating a request listener with high priority containing only the following line:
$this->doctrine->getManager()->getMetadataFactory()->getAllMetadata($curClass);
The above code fixes the issue, but it is hacky and seems to slightly degrade performance. I would much prefer if we can find the root of the bug and properly fix the issue.
What are you trying to do with your Doctrine listener ? If you want to hook an action to an event in Api Platform use one of the following event : https://api-platform.com/docs/core/events/#built-in-event-listeners.
I want to add some dynamic ManytoMany associations between my entities. Basically I have a special interface called LinkedEntityInterface and I want all entities that implement it (I have about 10) to be linked to all other entities that implement the same interface. So I use loadClassMetadata to automatically generate these 100 declarations, instead of having to write them by hand.
The code is already used in other parts of the project and works fine outside of API platform, the only issue is the one I mention in the bug.
@adrientiburce Did you figure this out? I am having the same issue, with a dynamically loaded relation via a Doctrine postLoad event, but in ApiPlatform (especially for GraphQL) it turns out to be null.