<p>I'm probably missing something here, but can't you just query for the entry model
and only modify the field you want to change?</p>

<pre><code>$criteria = craft()-&gt;elements-&gt;getCriteria(ElementType::Entry);
$criteria-&gt;id = 1;
$entries = $criteria-&gt;first();

if ($entry)
{
    $entry-&gt;setContentFromPost(array(
        'fieldToChange' =&gt; 'newValue'
    ));

    // Validate the entry model here if necessary

    craft()-&gt;entries-&gt;saveEntry($entry);
}
</code></pre>

CC BY-SA 3.0
2015-08-24T03:06:09.817Z
I've updated my original post as a response to see if this would still work.
divinemonkey
CC BY-SA 3.0
2015-08-24T06:59:37.343Z
Yes, should really be the same. Have a look at the full gist I created for you https://gist.github.com/carlcs/ef4664ceb281db7068fd. Test that code and tell me if you're still getting errors in the log! :)
carlcs
CC BY-SA 3.0
2015-08-24T09:48:33.143Z
Unfortunately I am still getting the same error.
`2015/08/24 09:42:43 [warning] [application] Craft\ContentModel->productCategory failed validation: Product Category cannot be blank.`
I am tempted to remove it has a required field currently. Seems the easiest solution.
divinemonkey
CC BY-SA 3.0
2015-08-24T09:56:56.530Z
And it did validate / saved without errors from the CP when you created that entry? Is there a category selected at all for that entry?
carlcs
CC BY-SA 3.0
2015-08-24T10:06:43.600Z
The webhook did complete with no errors, no stock update in the backend though and the Craft log receives that error. Yes, it is defined as Hardware.
divinemonkey
CC BY-SA 3.0
2015-08-24T10:25:05.777Z
Hey @divinemonkey, I'd try to leave out the extra validation, as field validation should happen anyways. See [updated gist](https://gist.github.com/carlcs/ef4664ceb281db7068fd).
carlcs
CC BY-SA 3.0
2015-08-24T11:17:42.193Z
`2015/08/24 11:16:44 [warning] [application] Craft\ContentModel->productCategory failed validation: Product Category cannot be blank.
2015/08/24 11:16:44 [error] [application] Could not updated the entry (ID: 44).`
divinemonkey
CC BY-SA 3.0
2015-08-24T11:19:19.923Z
Your code looks a lot better than what I had originally. It does work when I set the Category to not required, but still not playing nice when it is. Every other required field doesn't have an issue, it is only Category. I'm well and truly stumped.
divinemonkey
CC BY-SA 3.0
2015-08-23T15:26:56.130Z
2015-08-23T15:26:56.130Z
carlcs
<p><strong>Update - Craft 3</strong></p>

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

<p>You no longer need to apply a workaround to get the expected behavior.</p>

<hr>

<p><strong>Original - Craft 2</strong></p>

<p>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 <code>null</code>:</p>



<pre class="lang-php prettyprint-override"><code>$entry-&gt;setContentFromPost(array(
    'myCategoriesField' =&gt; null
    // ...
));
</code></pre>

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

<pre class="lang-php prettyprint-override"><code>$entry-&gt;setContentFromPost(array(
    'myCategoriesField' =&gt; $entry-&gt;myCategoriesField-&gt;ids()
    // ...
));
</code></pre>

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

CC BY-SA 3.0
2015-08-24T14:08:47.727Z
Ideally I don't want to change at all as it's already set. I only want to change the stock level and leave everything else as is, but having the Category as a required field is not letting me do that.
divinemonkey
CC BY-SA 3.0
2015-08-24T14:19:32.770Z
@divinemonkey Just updated your question and my answer after getting some clarification on it from carlcs.
Brandon Kelly
CC BY-SA 3.0
2015-08-25T09:28:03.287Z
Got it. All working now. Thanks, and to you also @carlcs
divinemonkey
CC BY-SA 3.0
2015-12-15T13:17:15.630Z
@BrandonKelly Is there a way to easily re-populate all the existing content an entry already has, without knowing exactly what fields it has? I'm trying to make a generic function that can be used across sections and would prefer not to have to manually specify all required relational fields, but do a single function call to cover every possible case.
Mike Pierce
CC BY-SA 3.0
2015-12-15T15:58:08.013Z
@MikePierce Yes, by checking the fields in the entry’s field layout, via `$entry->getFieldLayout()->getFields()`.
Brandon Kelly
CC BY-SA 3.0
2015-12-16T10:05:45.903Z
@BrandonKelly Sorry, not sure I follow you...? How does that help me exactly?
Mike Pierce
CC BY-SA 4.0
2015-08-24T13:18:01.897Z
2019-05-31T20:35:04.963Z
2019-05-31T20:35:04.963Z
Brandon Kelly
<p>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.</p>

<p>Here’s the relevant code:</p>

<pre class="lang-php prettyprint-override"><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);
}
</code></pre>

<p>How do I save the entry without losing its existing Categories field value?</p>

<plugin-development><categories><entrymodel>
Categories field is losing its value when programmatically updating other fields’ values
# Categories field is losing its value when programmatically updating other fields’ values

(Asked by: username_0 on 2015-08-23)

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()->entries->getEntryById($entryId);

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

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

How do I save the entry without losing its existing Categories field value?

**Tags:** plugin-development, categories, entrymodel

---

## 2 answers

### Answer by username_2 on 2015-08-24. Score: 5 | Accepted answer

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->setContentFromPost(array(
    'myCategoriesField' => 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->setContentFromPost(array(
    'myCategoriesField' => $entry->myCategoriesField->ids()
    // ...
));

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

> **Comments:**
> **username_0**: Ideally I don't want to change at all as it's already set. I only want to change the stock level and leave everything else as is, but having the Category as a required field is not letting me do that.  
> **username_2**: @divinemonkey Just updated your question and my answer after getting some clarification on it from carlcs.  
> **username_0**: Got it. All working now. Thanks, and to you also @carlcs  
> **username_3**: @BrandonKelly Is there a way to easily re-populate all the existing content an entry already has, without knowing exactly what fields it has? I'm trying to make a generic function that can be used across sections and would prefer not to have to manually specify all required relational fields, but do a single function call to cover every possible case.  
> **username_2**: @MikePierce Yes, by checking the fields in the entry’s field layout, via `$entry->getFieldLayout()->getFields()`.  
> **username_3**: @BrandonKelly Sorry, not sure I follow you...? How does that help me exactly?  

---

### Answer by username_1 on 2015-08-23. Score: 1

I'm probably missing something here, but can't you just query for the entry model
and only modify the field you want to change?
$criteria = craft()->elements->getCriteria(ElementType::Entry);
$criteria->id = 1;
$entries = $criteria->first();

if ($entry)
{
    $entry->setContentFromPost(array(
        'fieldToChange' => 'newValue'
    ));

    // Validate the entry model here if necessary

    craft()->entries->saveEntry($entry);
}

> **Comments:**
> **username_0**: I've updated my original post as a response to see if this would still work.  
> **username_1**: Yes, should really be the same. Have a look at the full gist I created for you https://gist.github.com/carlcs/ef4664ceb281db7068fd. Test that code and tell me if you're still getting errors in the log! :)  
> **username_0**: Unfortunately I am still getting the same error. `2015/08/24 09:42:43 [warning] [application] Craft\ContentModel->productCategory failed validation: Product Category cannot be blank.` I am tempted to remove it has a required field currently. Seems the easiest solution.  
> **username_1**: And it did validate / saved without errors from the CP when you created that entry? Is there a category selected at all for that entry?  
> **username_0**: The webhook did complete with no errors, no stock update in the backend though and the Craft log receives that error. Yes, it is defined as Hardware.  
> **username_1**: Hey @divinemonkey, I'd try to leave out the extra validation, as field validation should happen anyways. See [updated gist](https://gist.github.com/carlcs/ef4664ceb281db7068fd).  
> **username_0**: `2015/08/24 11:16:44 [warning] [application] Craft\ContentModel->productCategory failed validation: Product Category cannot be blank. 2015/08/24 11:16:44 [error] [application] Could not updated the entry (ID: 44).`  
> **username_0**: Your code looks a lot better than what I had originally. It does work when I set the Category to not required, but still not playing nice when it is. Every other required field doesn't have an issue, it is only Category. I'm well and truly stumped.  

---

