Problem/Motivation
Creating an entity (node) in the system using an image for a field will select the wrong image if a file other than an image was inserted in the system before the image.
Steps to reproduce
1. Insert a media type "Document" in Drupal using Content > Media > Add media
2. Go to Content > Files. You will notice 2 new files: the file you just created (FID 1) and a generic.png file (FID 2).
3. Insert an image using Content > Media > Add media
4. Go to Content > Media and check the MID of the image (mouse over the "edit" link). The image MID is 2. Go to Content > Files and check the FID of the image (mouse over the "Used in" link). The image has FID 3. This desync of MID / FID causes a lot of issues with the JSON:API.
5. Connect to the database and retrieve the UUID of the inserted file SELECT * FROM file_managed WHERE fid = 3;
6. Modify the article content type. Add a Reference > Media labelled "Preview" (field_preview).
7. Insert a node using the JSON:API, with the UUID of the inserted image:
{
'data': {
'type': 'node--article',
'attributes': {
'title': 'Article title',
'status': 1
},
'relationships': {
'field_preview': {
'data': {
'type': 'file--file',
'id': '30997b47-d065-4e52-980e-28a7b8ee5e9e'
}
}
}
}
}
Instead of using the image with the UUID specified, Drupal resolve the MID of the specified image (which is 2), find the file with the FID that matched the MID of the image (FID 2 is the generic.png file that was automatically inserted by Drupal) and associate the generic.png image as preview image to the article.
The JSON:API confuses MID and FID.
Proposed resolution
Make sure the JSON:API does not assume MID is the same as FID.
Remaining tasks
Find where in the code the MID / FID confusion happens, and fix it.
Release notes snippet
(will insert more info later if needed)
Comments
Comment #2
gaellafond commentedComment #3
gaellafond commentedComment #4
gaellafond commentedComment #5
gaellafond commentedI believe the issue might be due to the insertion of a "file--file" for a "Reference > Media" field type. I can not find any example of a JSON:API query which insert a media, so I have no way of verifying this.
[EDIT] I just found an example in Drupal source code:
tests/src/Functional/MediaTest.php. It uses a type I haven't seen beforemedia_type--media_type. But, image input are done with typefile--file. I tried withmedia_type--media_typebut that didn't work. I'm not sure if I'm doing something wrong or if there is indeed a bug in Drupal. Documentation regarding this is pretty hard to find.Comment #6
gaellafond commentedI solve it.
I could not find any example nor documentation. It was a game of try and failure.
I ended up asking GPT-4. It suggested to try with
'type' => 'media--image'. That works.I guess the issue now is... why Drupal doesn't give an error when I use
file--file?