3

I have a field type that needs to do some processing, based on the data in the element it belongs to, when an element (entry, category, user, etc) is saved, and save it to the field. I'm hooking into onAfterElementSave and my code (simplified) is as follow:

public function onAfterElementSave()
{
    $fieldHandle = $this->model->handle;
    $elementId = $this->element->id;
    $elementType = $this->element->getElementType();
    $elementLocale = $this->element->locale;

    $criteria = craft()->elements->getCriteria($elementType);
    $criteria->id = $elementId;
    $criteria->locale = $elementLocale; 
    $element = $criteria->first();

    if ($element!==null) {
        $myData = $element->title; // just an example
        if ($this->element->$fieldHandle != $myData) {
            $newData = array($fieldHandle => $myData);
            $element->setContent($newData);
            craft()->elements->saveElement($element);
        }
    } 
}

This works fine on existing entries, but when I create new entries, $element is null, so the field isn't updated.

What's going on and how can I fix this? Isn't onAfterElementSave actually after element save? :)

1
  • Looking at the ElementsService it looks like the element have not yet gotten an id, so you won't get any hits searching for it with the ElementCriteria
    – megatrond
    Commented Aug 31, 2015 at 9:59

1 Answer 1

4

You should be using it like this:

public function onAfterElementSave()
{
    $fieldHandle = $this->model->handle;
    if ($this->element!==null) {
        $myData = $this->element->title; // just an example
        if ($this->element->$fieldHandle != $myData) {
            $this->element->getContent()->setAttribute($fieldHandle, $myData);
            craft()->elements->saveElement($this->element);
        }
    } 
}
3
  • Thanks, Bob, that solved it for me. At some point I was sure that $this->element was read-only or something, so I went for the long way around, with the ElementCriteria. Commented Aug 31, 2015 at 10:07
  • What's the equivalent for $this->model->handle in Craft 3? I can't seem to find a way to obtain the handle.
    – Karl
    Commented Oct 22, 2020 at 8:11
  • Just $this->handle Commented Oct 22, 2020 at 9:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.