/** * Save virtual values after an entity's real values were saved. * * @param \Cake\Event\Event $event The event that was triggered * @param \Cake\Datasource\EntityInterface $entity The entity that was saved * @param \ArrayObject $options Additional options given as an array * @return bool True always */ public function afterSave(Event $event, EntityInterface $entity, ArrayObject $options) { $attrsById = []; $updatedAttrs = []; $valuesTable = TableRegistry::get('Eav.EavValues'); foreach ($this->_toolbox->attributes() as $name => $attr) { if (!$this->_toolbox->propertyExists($entity, $name)) { continue; } $attrsById[$attr->get('id')] = $attr; } if (empty($attrsById)) { return true; // nothing to do } $values = $valuesTable->find()->where(['eav_attribute_id IN' => array_keys($attrsById), 'entity_id' => $this->_toolbox->getEntityId($entity)]); foreach ($values as $value) { $updatedAttrs[] = $value->get('eav_attribute_id'); $info = $attrsById[$value->get('eav_attribute_id')]; $type = $this->_toolbox->getType($info->get('name')); $marshaledValue = $this->_toolbox->marshal($entity->get($info->get('name')), $type); $value->set("value_{$type}", $marshaledValue); $entity->set($info->get('name'), $marshaledValue); $valuesTable->save($value); } foreach ($this->_toolbox->attributes() as $name => $attr) { if (!$this->_toolbox->propertyExists($entity, $name)) { continue; } if (!in_array($attr->get('id'), $updatedAttrs)) { $type = $this->_toolbox->getType($name); $value = $valuesTable->newEntity(['eav_attribute_id' => $attr->get('id'), 'entity_id' => $this->_toolbox->getEntityId($entity)]); $marshaledValue = $this->_toolbox->marshal($entity->get($name), $type); $value->set("value_{$type}", $marshaledValue); $entity->set($name, $marshaledValue); $valuesTable->save($value); } } if ($this->config('cacheMap')) { $this->updateEavCache($entity); } return true; }