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