Save the updated record

@param \Crud\Event\Subject $subject Event subject
@return bool
512000
protected function _save(Subject $subject)
    {
        $entity = $this->_table()->patchEntity(
            $subject->entity,
            $this->_request()->data,
            $this->saveOptions()
        );
        $subject->set(['entity' => $entity]);

        $this->_trigger('beforeSave', $subject);

        $success = call_user_func(
            [$this->_table(), $this->saveMethod()],
            $entity,
            $this->saveOptions()
        );

        $this->_trigger('afterSave', $subject);

        return $success;
    }
1185653
protected function _post()
    {
        $subject = $this->_subject([
            'entity' => $this->_entity($this->_request()->getData(), $this->saveOptions()),
            'saveMethod' => $this->saveMethod(),
            'saveOptions' => $this->saveOptions()
        ]);

        $event = $this->_trigger('beforeSave', $subject);
        if ($event->isStopped()) {
            return $this->_stopped($subject);
        }

        $saveCallback = [$this->_table(), $subject->saveMethod];
        if (call_user_func($saveCallback, $subject->entity, $subject->saveOptions)) {
            return $this->_success($subject);
        }

        $this->_error($subject);
    }
792035
public function afterSave(Save $event)
    {
        /** @var Entity $entity */
        $entity = $event->getTarget();
        $entity->loadRelations = false;
        $prop = $this->getPropertyName();
        $relPrk = Entity\Manager::getInstance()->get($this->getRelatedEntity())
            ->getEntity()->getPrimaryKey();
        $entPrk = $entity->getPrimaryKey();
        
        if (isset($entity->$prop) && is_array($entity->$prop)) {
            $this->beforeDelete(new Delete(['primaryKey' => $entity->$entPrk]));
            foreach ($entity->$prop as $object) {
                $relVal = $object;
                if ($object instanceof Entity) {
                    $relVal = $object->$relPrk;
                }

                Sql::createSql($entity->getAdapter())
                    ->insert($this->getRelationTable())
                    ->set(
                        [
                            $this->getForeignKey() => $entity->$entPrk,
                            $this->getRelatedForeignKey() => $relVal
                        ]
                    )
                    ->execute();
            }
        }
        $entity->loadRelations = true;
    }
755763
public function update(\Tripod\Mongo\ImpactedSubject $subject)
    {
        $resource = $subject->getResourceId();
        $resourceUri    = $resource[_ID_RESOURCE];
        $context        = $resource[_ID_CONTEXT];

        $this->generateViews(array($resourceUri),$context);
    }
150308
public function update(SubjectInterface $subject)
   {
       if ($subject instanceof ModelInterface) {
           foreach (json_decode(json_encode($subject)) as $key => $value) {
               $this->appendValueTo($this->template, $key, $value);
           }
           return $subject;
       }
   }
1258002
protected function _ensureData(Subject $subject)
    {
        $controller = $this->_controller();
        $action = $this->_action();

        if (method_exists($action, 'viewVar')) {
            $viewVar = $action->viewVar();
        } else {
            $viewVar = 'data';
        }

        if (isset($controller->viewVars[$viewVar])) {
            return;
        }

        $key = $subject->success ? 'success' : 'error';

        $config = $action->getConfig('api.' . $key);

        $data = [];

        if (isset($config['data']['subject'])) {
            $config['data']['subject'] = Hash::normalize((array)$config['data']['subject']);

            $subjectArray = (array)$subject;
            foreach ($config['data']['subject'] as $keyPath => $valuePath) {
                if ($valuePath === null) {
                    $valuePath = $keyPath;
                }

                $keyPath = $this->_expandPath($subject, $keyPath);
                $valuePath = $this->_expandPath($subject, $valuePath);

                $data = Hash::insert($data, $keyPath, Hash::get($subjectArray, $valuePath));
            }
        }

        if (isset($config['data']['entity'])) {
            $config['data']['entity'] = Hash::normalize((array)$config['data']['entity']);

            foreach ($config['data']['entity'] as $keyPath => $valuePath) {
                if ($valuePath === null) {
                    $valuePath = $keyPath;
                }

                if (method_exists($subject->entity, $valuePath)) {
                    $data = Hash::insert($data, $keyPath, call_user_func([$subject->entity, $valuePath]));
                } elseif (isset($subject->entity->{$valuePath})) {
                    $data = Hash::insert($data, $keyPath, $subject->entity->{$valuePath});
                }
            }
        }

        if (isset($config['data']['raw'])) {
            foreach ($config['data']['raw'] as $path => $value) {
                $path = $this->_expandPath($subject, $path);
                $data = Hash::insert($data, $path, $value);
            }
        }

        if (method_exists($action, 'viewVar')) {
            $viewVar = $action->viewVar();
        } else {
            $viewVar = 'data';
        }

        $controller->set($viewVar, $data);
    }
716792
public function unstickSubject(Subject $subject)
    {
        $this->om->startFlushSuite();
        $subject->setIsSticked(false);
        $this->om->persist($subject);
        $this->dispatch(new UnstickSubjectEvent($subject));
        $this->om->endFlushSuite();
    }
398468
public function beforeSave(Save $event)
    {
        $entity = $event->getTarget();
        $property = $this->getPropertyName();
        $field = $this->getForeignKey();
        $data = $event->data;
        if (isset($entity->$property) && !is_null($entity->$property)) {
            /** @var Entity $object */
            $object = $entity->$property;
            $data[$field] = $object;
            $class = $this->getRelatedEntity();
            if ($object instanceof $class) {
                $pmk = $object->getPrimaryKey();
                $data[$field] = $object->$pmk;
            }
            $event->data = $data;
        }
    }
1067851
public function emit($event)
    {
        if (!empty($this->subjects[$event])) {

            /** @var \SplSubject $subject */
            foreach($this->subjects[$event] as $subject) {
                $subject->notify();
            }
        }
    }
506847
public function save()
    {
        $objectHash = spl_object_hash($this);
        if (array_key_exists($objectHash, self::$saved)) {
            return true;
        }

        self::$saved[$objectHash] = true;

        $data = [];
        $validation = [];
        $one2many = AttributeType::ONE2MANY;
        $many2many = AttributeType::MANY2MANY;
        /* @var $attr AbstractAttribute */
        foreach ($this->getAttributes() as $key => $attr) {
            if ($attr->isRequired() && !$attr->hasValue()) {
                $ex = new ValidationException(ValidationException::VALIDATION_FAILED);
                $ex->addError($key, ValidationException::REQUIRED);
                $validation[$key] = $ex;
                continue;
            }

            if (!count($validation) && !$this->isInstanceOf($attr, $one2many) && !$this->isInstanceOf($attr, $many2many)) {
                if ($attr->getStoreToDb()) {
                    $data[$key] = $attr->getDbValue();
                }
            }
        }

        // Throw EntityException with invalid attributes
        if (count($validation)) {
            $attributes = [];
            foreach ($validation as $attr => $error) {
                foreach ($error as $key => $value) {
                    $attributes[$key] = $value;
                }
            }
            $ex = new EntityException(EntityException::VALIDATION_FAILED, [get_class($this), count($validation)]);
            $ex->setInvalidAttributes($attributes);
            throw $ex;
        }

        /**
         * Insert or update
         */
        $mongo = $this->entity()->getDatabase();
        if (!$this->exists()) {
            $data['_id'] = $mongo->isId($data['id']) ? $mongo->id($data['id']) : $mongo->id();
            $data['id'] = (string)$data['_id'];
            $mongo->insertOne(static::$collection, $data);
            $this->id = $data['id'];
        } else {
            $where = ['_id' => $mongo->id($this->id)];
            $mongo->update(static::$collection, $where, ['$set' => $data], ['upsert' => true]);
        }

        /**
         * Now save One2Many values
         */
        foreach ($this->getAttributes() as $attr) {
            /* @var $attr One2ManyAttribute */
            if ($this->isInstanceOf($attr, AttributeType::ONE2MANY) && $attr->isLoaded()) {
                foreach ($attr->getValue() as $item) {
                    $item->getAttribute($attr->getRelatedAttribute())->setValue($this);
                    $item->save();
                }
                /**
                 * The value of one2many attribute must be set to null to trigger data reload on next access.
                 * This is necessary when we have circular references, and parent record does not get it's many2one ID saved
                 * until all child referenced objects are saved. Only then can we get proper links between referenced classes.
                 */
                $attr->setValue(null, true);
            }
        }

        /**
         * Now save Many2Many values
         */
        foreach ($this->getAttributes() as $attr) {
            /* @var $attr Many2ManyAttribute */
            if ($this->isInstanceOf($attr, AttributeType::MANY2MANY)) {
                $attr->save();
            }
        }

        // Now that this entity is saved, remove it from save log
        unset(self::$saved[$objectHash]);

        return true;
    }
1286555
public function update($event)
    {
        $formName = $event->sender->formName();
        $primaryKey = $event->sender->primaryKey;

        /** @var ActiveRecord $sender */
        $sender = $event->sender;

        /** @var MetaTags $metaTags */
        $metaTags = $sender->{$this->relationName};
        if (!$metaTags) {
            $metaTags = Yii::createObject(MetaTags::class);
            $metaTags->model = $formName;
            $metaTags->model_id = $primaryKey;
            $metaTags->language = $this->lang();
        }
        $metaTags->load(Yii::$app->request->post());

        if ($metaTags->validate()) {
            $metaTags->save();
        }
    }
1086456
public function save()
    {
        $result = false;

        if (count($this))
        {
            $result = true;

            foreach ($this as $entity)
            {
                if (!$entity->save())
                {
                    // Set current entity status message as collection status message.
                    $this->setStatusMessage($entity->getStatusMessage());
                    $result = false;
                }
            }
        }

        return $result;
    }
408245
public function save($object)
    {
        $this->assertObjectInstance($object);

        $state = $this->getState($object);
        if ($state->isReadOnly()) {
            return null;
        }

        $relationsIterator = new \ArrayIterator($this->getRelations());

        $modifiedManyManyRelations = $this->handleManyManyRelations($state, $relationsIterator);
        $this->handleHasManyRelations($state, $relationsIterator);
        $this->handleHasOneRelations($state, $relationsIterator);

        switch ($state->getObjectState()) {
            case EntityState::STATE_NEW:
                $primaryKey = $this->insert($object);
                break;

            case EntityState::STATE_NEW_WITH_PRIMARY_KEY:
                $pkField    = $this->getPrimaryKey();
                $primaryKey = $state->getOriginalFieldData($pkField);

                //Check if the record exists in the database
                if ($this->exists($primaryKey)) {
                    //We may have no way of knowing what has changed, but assume that the primary key hasn't
                    //Let's assume that the original data is actually all new
                    $data = $this->toArray($object);

                    //But only update the primary key if it really has changed
                    if ($data[ $pkField ] === $primaryKey) {
                        unset($data[ $pkField ]);
                    }

                    $primaryKey = $this->update($object, $data);
                } else {
                    $primaryKey = $this->insert($object);
                }
                break;

            default:
                $data       = $state->getChangedFields();
                $primaryKey = $this->update($object, $data);
                break;
        }

        $state->setState(EntityState::STATE_HANDLED);
        $state->refreshOriginalData();

        $this->updateManyToManyRelations($modifiedManyManyRelations, $primaryKey);

        return $primaryKey;
    }
267600
public function nonEmpty($subject) : bool
    {
        if (
            $subject instanceof \ArrayAccess
            && !($subject instanceof \Countable) && !($subject instanceof \Traversable)
        ) {
            return false;
        }
        return !$this->empty($subject);
    }
717651
protected function _post()
    {
        $subject = $this->_subject([
            'entity' => $this->_entity($this->_request()->data, $this->saveOptions()),
            'saveMethod' => $this->saveMethod(),
            'saveOptions' => $this->saveOptions()
        ]);

        $this->_trigger('beforeRegister', $subject);

        $saveCallback = [$this->_table(), $subject->saveMethod];
        if ($saveCallback($subject->entity, $subject->saveOptions)) {
            return $this->_success($subject);
        }

        return $this->_error($subject);
    }
179200
protected function _stopped(Subject $subject)
    {
        $subject->set(['success' => false]);
        $this->setFlash('error', $subject);

        return $this->_redirect($subject, ['action' => 'index']);
    }
820708
public function update(SplSubject $subject)
    {
        if ($this->hasMethod('__update') && is_callable([$this, '__update'])) {
            $this->__update($subject);
        }
    }