What happened?
Description
I'm trying to programmatically create an entry link in a Link field. The first thing I tried is to set the type to entry and the value to the ID of the target entry:
$target = Entry::find()->id(123)->one();
$entry->setFieldValue('myLinkField', [
'type' => 'entry',
'value' => $target->id,
]);
But that doesn't work. Had a look at the source code, I also tried to set ['entry' => $target->id], that doesn't work either. The only way I found that works is to reverse-engineer the entry reference tag format that's used by the field and use that:
$entry->setFieldValue('myLinkField', [
'type' => 'entry',
'value' => sprintf('{entry:%1$s@1:url}', $target->id),
]);
But that's very awkward and relies on undocumented internal behaviour that might change at any point.
Expected behavior
Setting the value to an entry ID (first example) should create a link to that entry's ID.
Actual behavior
I have to match the storage format used by the field internally exactly, or my link isn't saved correctly.
Slightly off-topic, but it would be super helpful if the documentation for Craft fields included examples for how to set values programmatically. At the moment it's a combination of trial and error and code diving.
Craft CMS version
5.5.3
PHP version
No response
Operating system and version
No response
Database type and version
No response
Image driver and version
No response
Installed plugins and versions
What happened?
Description
I'm trying to programmatically create an entry link in a Link field. The first thing I tried is to set the
typetoentryand thevalueto the ID of the target entry:But that doesn't work. Had a look at the source code, I also tried to set
['entry' => $target->id], that doesn't work either. The only way I found that works is to reverse-engineer the entry reference tag format that's used by the field and use that:But that's very awkward and relies on undocumented internal behaviour that might change at any point.
Expected behavior
Setting the
valueto an entry ID (first example) should create a link to that entry's ID.Actual behavior
I have to match the storage format used by the field internally exactly, or my link isn't saved correctly.
Slightly off-topic, but it would be super helpful if the documentation for Craft fields included examples for how to set values programmatically. At the moment it's a combination of trial and error and code diving.
Craft CMS version
5.5.3
PHP version
No response
Operating system and version
No response
Database type and version
No response
Image driver and version
No response
Installed plugins and versions