How to set linked entry for a many-reference a field?

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’))

Hey Timothy

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? :thinking:

Best,
Stephan

1 Like

Hey Timothy,

Stephan’s comment is on point, if the field is many-referenced, then you simply have to set the value as an array of link objects:

$entry->setField('address', 'en-AU', [$addressEntry->asLink()]);

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.

Davide

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?

Happy to know it worked!

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();

Perhaps you might be interested in this: https://www.contentful.com/developers/docs/php/tutorials/generating-entry-classes-based-on-content-types-management-sdk/

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.

Let me know if this works!

Davide