6

I'm trying to update an entry's field value from a Craft plugin. First I was trying to just update the attributes of the entry like so:

$entry->getContent()->setAttributes(array(
  'metaStatus' => 'Declined'
));

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

But that wouldn't work because getContent doesn't return the data needed in order for the EntryModel to pass validation. The next solution was to loop through each of the fields and grab their field value like so:

$fields = array();

foreach($entry->getFieldLayout()->getFields() as $layout) {
  $handle = $layout->getField()->handle;

  $fields[$handle] = $entry->getFieldValue($handle);
}

$fields['metaStatus'] = 'Declined';

$entry->setContent($fields);

craft()->entries->saveEntry($entry); // FAIL

Now I'm having issues with matrix/asset fields validating since they come back as empty. Am I going to have to look for matrix/asset fields in my loop above and correctly format the data? There must be an easier way to do this.

6

I got around this issue by looping through all fields that were of BaseElementFieldType re-setting them to their current value.

$fields = $entry->getFieldLayout()->getFields();

$referentialFields = array();
foreach ($fields as $layoutField) {
  $field = $layoutField->getField();
  if ($field->getFieldType() instanceof BaseElementFieldType) {
    $referentialFields[$field->handle] = $entry->{$field->handle}->ids();
  }
}

$entry->setContentFromPost(array_merge($referentialFields, array(
  'yourField' => 'yourValue'
)));

craft()->entries->saveEntry($entry);
| improve this answer | |
4

You're very close. Try this:

$entry->getContent()->setAttribute('metaStatus', 'Declined');
craft()->entries->saveEntry($entry);
| improve this answer | |
  • Unfortunately it still fails validation – required fields still complain. – Jon Sep 29 '15 at 16:40
  • But is this an entry that has already been saved and has validated? Or is it a new entry? – André Elvan Sep 30 '15 at 7:49
  • It's already been saved, I'm retrieving it like so: $entry = craft()->entries->getEntryById($entryId);. All of the other fields except for the matrix/asset/entry fields are pre-filled with the getContent method so I assume this is just a Craft bug... – Jon Sep 30 '15 at 17:01
3

I'm not completely sure of the technical reasons (I guess something to do with relation fields not have a column in the craft_content table), but you also need to re-save the existing ids for any relation fields (Assets, Entries, Categories, Matrix, etc) before the element can be saved:

$entry->setContentFromPost(array(
    'metaStatus'  => 'Declined',
    'assetsField' => $entry->assetsField->ids(),
    'matrixField' => $entry->matrixField->ids(),
);

craft()->entries->saveEntry($entry);
| improve this answer | |

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.