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? :)

  • 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 Aug 31 '15 at 9:59
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);
        }
    } 
}
  • 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. – André Elvan Aug 31 '15 at 10:07

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.