I'm using the Contentful API PHP SDK library and through this API am creating a few different Entries which are going to reference each other.
I'm able to create the different entries, I'm able to edit text fields within them, both at the point of creation and after they are created, I can edit the fields. However, what I am not able to do is reference the Entries to one another.
For the purpose of this issue, the two Content Types are: ContentType-A
and ContentType-B
where there is a References
field which can hold 0 or more References (referred to as Components
).
The code that is used looks like this:
// environmentProxy handles create/update
$environment = $this->client->getEnvironmentProxy($spaceId, $environmentId);
// creating ContentType-A Entry
$entry = new Entry('ContentType-A');
$entry->setField('title', 'en-US' , $title);
$environment->create($entry);
// test out if I can edit the previously created entry
// call newly created entry just in case their API is cached
$newlyCreatedEntryA = $environment->getEntry($entry->getId());
$newlyCreatedEntryA->setField('title' , 'en-US' , 'Some new title');
$newlyCreatedEntryA->update(); // I can verify that the entry title changed
// create ContentType-B Entry
$entry = new Entry('ContentType-B');
$entry->setField('title', 'en-US' , 'Content Type B - ' . $title);
$environment->create($entry);
$newlyCreatedEntryB = $environment->getEntry($entry->getId());
// try to reference ContentType-B into Components field in ContentType-A
// THIS IS WHERE I GET AN ERROR
$newlyCreatedEntryA->setField('Components', 'en-US', $newlyCreatedEntryB);
$newlyCreatedEntryA->update();
I receive a 422 error. I've replaced values with the same variables as labeled above to ensure the values are correctly placed.
Client error: `PUT https://api.contentful.com/spaces/{$spaceId}/environments/{$environmentId}/entries/{$newlyCreatedEntryA->getId()}` resulted in a `422 Unprocessable Entity` response:
{
{
"Error",
"id": "InvalidEntry"
},
"message": "Validation error",
Additional checks to see why it might not work:
sleep(5)
in various parts of the script to delay and allow Contentful's systems to get updated.Apparently, the endpoint I was trying to access is not currently supported.
Instead, I came across this article that guided me to look at PATCH
instead of PUT
and I could add entries using Curl
instead.
Relevant helpful instruction/code from the article above:
{
[
{
"op": "add",
"path": "/fields/{fieldName}",
"value": {
"en-US": [
{
"sys": {
"type": "Link",
"linkType": "Entry",
"id": "37e9c2f9ef994cb5"
}
}
]
}
}
]
}
One new thing you would need to remember - if you are using curl is that you will have to keep track of the version you are updating otherwise you can get a version mismatch error.