Categories field is losing its value when programmatically updating other fields’ values I have a webhook that fetches an entry, modifies one of its custom Text field values and then saves the entry. However there is also a required Categories field on the entry, and when I do this, I get a validation error because the Categories field is blank.

Here’s the relevant code:

$entry = craft()-&gt;entries-&gt;getEntryById($entryId);

$entry-&gt;setContentFromPost(array(
    'myTextField' =&gt; $newValue
));

// Let's see if it saves.
// Field validation should happen automatically
if (craft()-&gt;entries-&gt;saveEntry($entry))
{
    Craft::log('Entry updated (ID: '.$entry-&gt;id.').');
}
else
{
    Craft::log('Could not updated the entry (ID: '.$entry-&gt;id.').', LogLevel::Error);
}


How do I save the entry without losing its existing Categories field value?
Update - Craft 3

This has been fixed. The relational field will retain its original value when an entry is re-saved.

You no longer need to apply a workaround to get the expected behavior.



Original - Craft 2

This is, admittedly, super awkward right now. To prevent a relational field from losing its value when saving an entry, you have to explicitly set its value to null:



$entry-&gt;setContentFromPost(array(
    'myCategoriesField' =&gt; null
    // ...
));


However, this only works for relational fields that aren’t set to Required. If the field is set to Required, you have to just re-set the field to the same element IDs that were already selected:

$entry-&gt;setContentFromPost(array(
    'myCategoriesField' =&gt; $entry-&gt;myCategoriesField-&gt;ids()
    // ...
));


(FWIW, this will stop being awkward in Craft 3, as we done some major refactoring under the hood to fix issues like this.)