3

I am trying to update a custom field on an EntryModel. I'm having half success, and I don't understand why. I've looked at other posts such as this one by Brandon which discuss how to assign these values and I'm still not having any luck.

The EntryModel I'm trying to update is available in my field type in the onAfterElementSave method via $this->element. The handle for the field I want to be updating the value of is available via $this->model->handle.

I have tried using setContentFromPost(), setContent(), getContent()->setAttributes() and they all seem to return the same results.

$fieldHandle = $this->model->handle;

$this->element->setContentFromPost(array(
    $fieldHandle => 'changedValue'
));

// Accessing the value via getContent returns the update value 'changedValue'
$changedValue = $this->element->getContent()->fieldHandle;

// Accessing the value directly returns the 'originalValue'
$originalValue = $this->element->fieldHandle;

Why am I able to successfully update the value for the getContent() method but not when I access it directly on the model?

4

setContentFromPost() performs an operation on the attached ContentModel, not on the element model itself.

When you initialize a BaseElementModel, its content attributes are set from the associated ContentModel. ("Content attributes" means attributes from custom field data, a.k.a. the stuff you'll typically find in the craft_content DB table for a given element instance.)

However, later updating the properties of the content model does not immediately ripple into changing the attributes of the element model: You'll need to re-save the element after you do a setContentFromPost(), and then its magic attributes will reflect your newly set values.

When you setContentFromPost(), you're changing the data that will ultimately gets passed into each FieldType's prepValueFromPost() method. If you need to do additional processing later (after each FieldType has done its thing) — such as saving records in an third-party table during onAfterElementSave — your service can use getContent() to or getContentFromPost() to grab the values it needs, depending on whether you want to access the raw POST data the user submitted, or the values that got returned from each FieldType's prepValue() method.

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.