Answers.Body: <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>
  
Answers.ContentLicense: CC BY-SA 3.0
Answers.CreationDate: 2015-08-24T03:06:09.817Z
Answers.Text: I've updated my original post as a response to see if this would still work.
Answers.UserDisplayName: divinemonkey
Answers.ContentLicense: CC BY-SA 3.0
Answers.CreationDate: 2015-08-24T06:59:37.343Z
Answers.Text: 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! :)
Answers.UserDisplayName: carlcs
Answers.ContentLicense: CC BY-SA 3.0
Answers.CreationDate: 2015-08-24T09:48:33.143Z
Answers.Text: 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.
Answers.UserDisplayName: divinemonkey
Answers.ContentLicense: CC BY-SA 3.0
Answers.CreationDate: 2015-08-24T09:56:56.530Z
Answers.Text: 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?
Answers.UserDisplayName: carlcs
Answers.ContentLicense: CC BY-SA 3.0
Answers.CreationDate: 2015-08-24T10:06:43.600Z
Answers.Text: 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.
Answers.UserDisplayName: divinemonkey
Answers.ContentLicense: CC BY-SA 3.0
Answers.CreationDate: 2015-08-24T10:25:05.777Z
Answers.Text: 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).
Answers.UserDisplayName: carlcs
Answers.ContentLicense: CC BY-SA 3.0
Answers.CreationDate: 2015-08-24T11:17:42.193Z
Answers.Text: `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).`
Answers.UserDisplayName: divinemonkey
Answers.ContentLicense: CC BY-SA 3.0
Answers.CreationDate: 2015-08-24T11:19:19.923Z
Answers.Text: 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.
Answers.UserDisplayName: divinemonkey
Answers.ContentLicense: CC BY-SA 3.0
Answers.CreationDate: 2015-08-23T15:26:56.130Z
Answers.LastActivityDate: 2015-08-23T15:26:56.130Z
Answers.UserDisplayName: carlcs
Answers.Body: <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>
  
Answers.ContentLicense: CC BY-SA 3.0
Answers.CreationDate: 2015-08-24T14:08:47.727Z
Answers.Text: 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.
Answers.UserDisplayName: divinemonkey
Answers.ContentLicense: CC BY-SA 3.0
Answers.CreationDate: 2015-08-24T14:19:32.770Z
Answers.Text: @divinemonkey Just updated your question and my answer after getting some clarification on it from carlcs.
Answers.UserDisplayName: Brandon Kelly
Answers.ContentLicense: CC BY-SA 3.0
Answers.CreationDate: 2015-08-25T09:28:03.287Z
Answers.Text: Got it. All working now. Thanks, and to you also @carlcs
Answers.UserDisplayName: divinemonkey
Answers.ContentLicense: CC BY-SA 3.0
Answers.CreationDate: 2015-12-15T13:17:15.630Z
Answers.Text: @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.
Answers.UserDisplayName: Mike Pierce
Answers.ContentLicense: CC BY-SA 3.0
Answers.CreationDate: 2015-12-15T15:58:08.013Z
Answers.Text: @MikePierce Yes, by checking the fields in the entry’s field layout, via `$entry->getFieldLayout()->getFields()`.
Answers.UserDisplayName: Brandon Kelly
Answers.ContentLicense: CC BY-SA 3.0
Answers.CreationDate: 2015-12-16T10:05:45.903Z
Answers.Text: @BrandonKelly Sorry, not sure I follow you...? How does that help me exactly?
Answers.UserDisplayName: Mike Pierce
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2015-08-24T13:18:01.897Z
Answers.LastActivityDate: 2019-05-31T20:35:04.963Z
Answers.LastEditDate: 2019-05-31T20:35:04.963Z
Answers.UserDisplayName: Brandon Kelly
Body: <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>
  
Tags: <plugin-development><categories><entrymodel>
Title: Categories field is losing its value when programmatically updating other fields’ values
ThreadText: # 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:
  
  ```php
  $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`:
  
  ```php
  $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:
  
  ```php
  $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**: @username_0 Just updated your question and my answer after getting some clarification on it from username_1.  
  > **username_0**: Got it. All working now. Thanks, and to you also @username_1  
  > **username_3**: @username_2 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**: @username_3 Yes, by checking the fields in the entry’s field layout, via `$entry->getFieldLayout()->getFields()`.  
  > **username_3**: @username_2 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/username_1/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 @username_0, I'd try to leave out the extra validation, as field validation should happen anyways. See [updated gist](https://gist.github.com/username_1/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.  
  
  ---
  
  