So I’m using the Contentful Management PHP SDK, however I can’t seem to find how to link an entry to a many-referenced field, when I’m creating a new entry.
I’ve tried the following, but to no avail:
->setField(‘address’, ‘en-AU’, new \Contentful\Core\Api\Link($addressEntry->getId(), ‘Entry’))
I’m by far not a PHP expert, but if you want to set a many-referenced field, shouldn’t you set the field to an array, containing the link you created? Or am I missing something here?
As a note, all resources in the CMA SDK provide a asLink() method, which creates the correct link object. It’s the same as in your code, it’s just a handy shortcut.
Hey @davide I was able to attach an entry to the field, however now that I’d like to update it after the fact that it’s been published, how would I go about adding another entry without overwriting the current linked entry?
To add another entry to the list, you should simply treat it as an array. setField doesn’t (and can’t) know what type of field it’s working with, so it doesn’t provide this automatically, but it can be easily worked around:
// This will return an array of Link objects
$list = $entry->getField('address', 'en-AU');
// Just append another Link object at the end of the array
$list[] = $anotherAddressEntry->asLink();
// And re-set it as the field value
$entry->setField('address', 'en-US', $list);
// Finally, call the API to persist the changes
$entry->update();
The PHP CMA SDK allows you to generate entry classes based on content types, you might build some abstractions on top of the basic setField/getField methods, and end up with something like this:
// In regular code
$entry->appendAddress('en-AU', $address);
// And in the custom entry class
/**
* @param string $locale
* @param Contentful\Core\Api\Link|Contentful\Management\Resource\Entry $address
*/
public function appendAddress($locale, $address)
{
if ($address instanceof \Contentful\Management\Resource\Entry) {
$address = $address->asLink();
}
$addresses = $this->getField('address', $locale);
$addresses[] = $address;
$this->setField('address', $locale, $addresses);
}
This way you get a workflow similar to what ORMs provide, and better encapsulate the logic.