2

Using PHP, I want to update a field of Entries type of an existing entry.

Fields of type Text and Number will update with the following code:

$entry = Entry::find()->id($entryId)->one();
$entry->textField = 20; // works
$entry->entriesField = Entry::find()->id($relatedEntryIds)->all(); // doesn't work
Craft::$app->elements->saveElement($entry);

I looked into the source code and it seems to be expecting a craft\elements\db\EntryQuery object but I can't get it to work.

Can anyone please help?

3

Ok this was easy. Tried it at first but didn't work and was successful after another go. All it needed was a array of Entry IDs.

Working code:

$entry = Entry::find()->id($entryId)->one();
$entry->setFieldValue('textField', 20);
$entry->setFieldValue('entriesField', [$relatedEntryId1, $relatedEntryId2]);

Craft::$app->elements->saveElement($entry);
2

As per the docs at https://craftcms.com/docs/3.x/extend/element-types.html#saving-custom-field-values

When saving values on a custom field, always use the setFieldValue() or setFieldValues() methods rather than directly accessing the field handle as a property on the element object. This ensures the value is normalized and marked as dirty for delta saves.

$entry->setFieldValue('testField', 'foo');
$entry->setFieldValue('entriesField', [$relatedEntryId1, $relatedEntryId2]);

Craft::$app->elements->saveElement($entry);
1
  • Thanks. Yes this works with the latest Craft versions but unsure that it was documented in the past. Answer edited.
    – biko
    Sep 15 at 7:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.