Updates a model instance. If the instance does n't exist in the persistence it will throw an exception

@return static
431648
public function update()
    {
        $snapshot = $this->_snapshot;
        if ($snapshot === false) {
            throw new PreconditionException(['update failed: `:model` instance is snapshot disabled', 'model' => static::class]);
        }

        $primaryKeyValuePairs = $this->_getPrimaryKeyValuePairs();

        $fieldTypes = $this->getFieldTypes();
        $fields = array_keys($fieldTypes);

        $changedFields = [];
        foreach ($fields as $field) {
            if ($this->$field === null) {
                /** @noinspection NotOptimalIfConditionsInspection */
                if (isset($snapshot[$field])) {
                    $changedFields[] = $field;
                }
            } elseif (!isset($snapshot[$field])) {
                if (is_scalar($this->$field)) {
                    $this->$field = $this->normalizeValue($fieldTypes[$field], $this->$field);
                }
                $changedFields[] = $field;
            } elseif ($snapshot[$field] !== $this->$field) {
                if (is_scalar($this->$field)) {
                    $this->$field = $this->normalizeValue($fieldTypes[$field], $this->$field);
                }

                /** @noinspection NotOptimalIfConditionsInspection */
                if ($snapshot[$field] !== $this->$field) {
                    $changedFields[] = $field;
                }
            }
        }

        if (!$changedFields) {
            return $this;
        }

        $this->validate($changedFields);

        foreach ($this->getAutoFilledData(self::OP_UPDATE) as $field => $value) {
            if (in_array($field, $fields, true)) {
                $this->$field = $value;
            }
        }

        $this->eventsManager->fireEvent('model:beforeSave', $this);
        $this->eventsManager->fireEvent('model:beforeUpdate', $this);

        $fieldValues = [];
        foreach ($fields as $field) {
            if ($this->$field === null) {
                if (isset($snapshot[$field])) {
                    $fieldValues[$field] = null;
                }
            } elseif (!isset($snapshot[$field]) || $snapshot[$field] !== $this->$field) {
                $fieldValues[$field] = $this->$field;
            }
        }

        foreach ($primaryKeyValuePairs as $key => $value) {
            unset($fieldValues[$key]);
        }

        if (!$fieldValues) {
            return $this;
        }

        foreach ($this->getJsonFields() as $field) {
            if (isset($fieldValues[$field]) && is_array($fieldValues[$field])) {
                $fieldValues[$field] = json_encode($fieldValues[$field], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
            }
        }

        $query = static::query(null, $this)->where($primaryKeyValuePairs);
        $query->update($fieldValues);

        $expressionFields = [];
        foreach ($fieldValues as $field => $value) {
            if ($value instanceof ExpressionInterface) {
                $expressionFields[] = $field;
            }
        }

        if ($expressionFields) {
            $expressionFields['_id'] = false;
            if ($rs = $query->select($expressionFields)->execute()) {
                foreach ((array)$rs[0] as $field => $value) {
                    $this->$field = $value;
                }
            }
        }

        $this->_snapshot = $this->toArray();

        $this->eventsManager->fireEvent('model:afterUpdate', $this);
        $this->eventsManager->fireEvent('model:afterSave', $this);

        return $this;
    }
15091
public function update()
    {
        if (!$this->request->is('post')) {
            if ($this->request->is('ajax')) {
                throw new MethodNotAllowedException();
            } else {
                $this->Flash->error($this->invalidRequestMessage);
                $this->redirect(['action' => 'index']);
                return;
            }
        }

        if (empty($this->request->data) && !$this->request->is('ajax')) {
            $this->Flash->warning(__d('wasabi_core', 'There are no permissions to update yet.'));
            $this->redirect(['action' => 'index']);
            return;
        }

        // save the new language positions
        $permissions = $this->GroupPermissions->patchEntities(
            $this->GroupPermissions->find('all'),
            $this->request->data
        );

        /** @var Connection $connection */
        $connection = $this->GroupPermissions->connection();
        $connection->begin();
        foreach ($permissions as $permission) {
            if (!$this->GroupPermissions->save($permission)) {
                $connection->rollback();
                break;
            }
        }

        if ($connection->inTransaction()) {
            $connection->commit();
            Cache::clear(false, 'wasabi/core/group_permissions');
            if ($this->request->is('ajax')) {
                $status = 'success';
                $this->set(compact('status'));
                $this->set('_serialize', ['status']);
            } else {
                $this->Flash->success(__d('wasabi_core', 'All permissions have been saved.'));
                $this->redirect(['action' => 'index']);
                return;
            }
        } else {
            $this->Flash->error($this->dbErrorMessage);
        }
    }
781680
public function replicate()
	{
		$attributes = array_except($this->attributes, array($this->getKeyName()));

		with($instance = new static)->setRawAttributes($attributes);

		return $instance->setRelations($this->relations);
	}
427393
protected function getModel()
	{
		if (!$model = $this->owner) {
			throw new \Exception('Model is not been initialized properly.');
		}
		if (!$model instanceof ActiveRecord) {
			throw new \Exception(sprintf('Behavior must be applied to the ActiveRecord model class and it\'s iheritants, the unsupported class provided: `%s`', get_class($model)));
		}

		return $model;
	}
1005402
public function actionUpdate()
    {
        $model = $this->findModel();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            \Yii::$app->getSession()->setFlash('success', $this->getFlashMsg('success'));
            return $this->redirect(ArrayHelper::merge(['view'], $model->getPrimaryKey(true)));
        } else {
            if ($model->hasErrors()) {
                \Yii::$app->getSession()->setFlash('error', $this->getFlashMsg('error'));
            }
            return $this->render($this->viewID, [
                'model' => $model,
            ]);
        }
    }
653140
protected function update()
    {
        $this->preUpdate();
        $this->data = $this->api->update($this->id, $this->data);
        $this->postUpdate();

        return $this;
    }
368908
public function update()
    {
        //get params from request
        $this->primaryKey = yii::app()->request->getParam('pk');
        $this->attribute = yii::app()->request->getParam('name');
        $this->value = yii::app()->request->getParam('value');
        $this->scenario = yii::app()->request->getParam('scenario');

        //checking params
        if (empty($this->attribute)) {
            throw new CException(Yii::t('EditableSaver.editable','Property "attribute" should be defined.'));
        }
        
        $this->model = new $this->modelClass();
        
        $isFormModel = $this->model instanceOf CFormModel;
        $isMongo = EditableField::isMongo($this->model);
        
        if (empty($this->primaryKey) && !$isFormModel) {
            throw new CException(Yii::t('EditableSaver.editable','Property "primaryKey" should be defined.'));
        }
        
        //loading model
        if($isMongo) {
        	$this->model = $this->model->findByPk(new MongoID($this->primaryKey));
		} elseif(!$isFormModel) {
			$this->model = $this->model->findByPk($this->primaryKey);
		}
        
        if (!$this->model) {
            throw new CException(Yii::t('EditableSaver.editable', 'Model {class} not found by primary key "{pk}"', array(
               '{class}'=>get_class($this->model), '{pk}' => is_array($this->primaryKey) ? CJSON::encode($this->primaryKey) : $this->primaryKey)));
        }
        
        //keep parent model for mongo
        $originalModel = $this->model;
        
        //resolve model only for mongo! we should check attribute safety
        if($isMongo) {
			$resolved = EditableField::resolveModels($this->model, $this->attribute);
			$this->model = $resolved['model']; //can be related model now
			$this->attribute = $resolved['attribute'];
			$staticModel = $resolved['staticModel'];	        	
		} else {
			$staticModel = $this->model;
		}

        //set scenario for main model
        if($this->scenario) {
            $originalModel->setScenario($this->scenario);
        }

        //is attribute safe
        if (!$this->model->isAttributeSafe($this->attribute)) {
            throw new CException(Yii::t('editable', 'Model {class} rules do not allow to update attribute "{attr}"', array(
                    '{class}'=>get_class($this->model), '{attr}'=>$this->attribute)));
        }

        //setting new value
        $this->setAttribute($this->attribute, $this->value);

        //validate attribute
        $this->model->validate(array($this->attribute));
        $this->checkErrors();

        //trigger beforeUpdate event
        $this->beforeUpdate();
        $this->checkErrors();
        
        //remove virtual attributes (which NOT in DB table)
        if(!$isMongo) {
            $this->changedAttributes = array_intersect($this->changedAttributes, $originalModel->attributeNames()); 
            if(count($this->changedAttributes) == 0) {
                //can not pass empty array in model->save() method!
                $this->changedAttributes = null;
            }
        }
        
        //saving (no validation, only changed attributes) note: for mongo save all!
        if($isMongo) {
            $result = $originalModel->save(false, null);
        } elseif(!$isFormModel) {
            $result = $originalModel->save(false, $this->changedAttributes);
        } else {
            $result = true;
        } 
        if ($result) {
            $this->afterUpdate();
        } else {
            $this->error(Yii::t('EditableSaver.editable', 'Error while saving record!'));
        }
    }
384240
public static function update()
    {
        $result = null;

        switch (static::getDriver()) {
            case self::DRIVER_MYSQL:
                $result = new \pwf\components\querybuilder\adapters\MySQL\UpdateBuilder();
                break;
            case self::DRIVER_PG:
                $result = new \pwf\components\querybuilder\adapters\PostgreSQL\UpdateBuilder();
                break;
            default:
                throw new \Exception('Wrong query builder driver');
        }

        return $result;
    }
1025676
public function postUpdate() {
        $Model = $this->Model;

        //determine which field from ExtJs to use as the primary key
        //may replace with $id = Input::get('id');
        $id = $this->getKeyFromInput();

        //get record
        $record = $Model::findOrFail($id);
        $record->update(Input::all());

        return ( $record->errors )
            ? $this->failure($record, $record->getErrors())
            : $this->success($record);

    }
1140181
public function actionUpdateSelf()
    {
        $model = User::findOne(['id' => yii::$app->getUser()->getIdentity()->getId()]);
        $model->setScenario('self-update');
        if (yii::$app->getRequest()->getIsPost()) {
            if ($model->load(yii::$app->getRequest()->post()) && $model->selfUpdate()) {
                Yii::$app->getSession()->setFlash('success', yii::t('cms', 'Success'));
            } else {
                $errors = $model->getErrors();
                $err = '';
                foreach ($errors as $v) {
                    $err .= $v[0] . '<br>';
                }
                Yii::$app->getSession()->setFlash('error', $err);
            }
            $model = User::findOne(['id' => yii::$app->getUser()->getIdentity()->getId()]);
        }

        return $this->render('update', [
            'model' => $model,
        ]);
    }
1223774
public function update()
	{
		//get params from request
		$this->primaryKey = yii::app()->request->getParam('pk');
		$this->attribute = yii::app()->request->getParam('name');
		$this->value = yii::app()->request->getParam('value');

		//checking params
		if (empty($this->attribute)) {
			throw new CException(Yii::t('TbEditableSaver.editable', 'Property "attribute" should be defined.'));
		}
		if (empty($this->primaryKey)) {
			throw new CException(Yii::t('TbEditableSaver.editable', 'Property "primaryKey" should be defined.'));
		}

		//loading model
		$this->model = CActiveRecord::model($this->modelClass)->findByPk($this->primaryKey);
		if (!$this->model) {
			throw new CException(Yii::t(
				'TbEditableSaver.editable',
				'Model {class} not found by primary key "{pk}"',
				array(
					'{class}' => get_class($this->model),
					'{pk}' => is_array($this->primaryKey) ? CJSON::encode($this->primaryKey) : $this->primaryKey
				)
			));
		}

		//set scenario
		$this->model->setScenario($this->scenario);

		//commented to be able to work with virtual attributes
		//see https://github.com/vitalets/yii-bootstrap-editable/issues/15
		/*
		//is attribute exists
		if (!$this->model->hasAttribute($this->attribute)) {
			throw new CException(Yii::t('EditableSaver.editable', 'Model {class} does not have attribute "{attr}"', array(
			  '{class}'=>get_class($this->model), '{attr}'=>$this->attribute)));
		}
		*/

		//is attribute safe
		if (!$this->model->isAttributeSafe($this->attribute)) {
			throw new CException(Yii::t(
				'editable',
				'Model {class} rules do not allow to update attribute "{attr}"',
				array(
					'{class}' => get_class($this->model),
					'{attr}' => $this->attribute
				)
			));
		}

		//setting new value
		$this->setAttribute($this->attribute, $this->value);

		//validate attribute
		$this->model->validate(array($this->attribute));
		$this->checkErrors();

		//trigger beforeUpdate event
		$this->beforeUpdate();
		$this->checkErrors();

		//saving (no validation, only changed attributes)
		if ($this->model->save(false, $this->changedAttributes)) {
			//trigger afterUpdate event
			$this->afterUpdate();
		} else {
			$this->error(Yii::t('TbEditableSaver.editable', 'Error while saving record!'));
		}
	}
391896
public function updateModels(Models $models)
    {
        foreach ($models as $model) {
            if ($model->isSoftDeleted()) {
                $this->dispatchBeforeEvent($model, Event::DELETE);
            } else {
                $this->dispatchBeforeEvent($model, Event::UPDATE);
                $this->dispatchBeforeEvent($model, Event::SAVE);
            }
        }

        $this->updateAll()->executeModels($models);

        foreach ($models as $model) {

            $model->resetOriginals();

            if ($model->isSoftDeleted()) {
                $this->dispatchAfterEvent($model, Event::DELETE);
            } else {
                $this->dispatchAfterEvent($model, Event::UPDATE);
                $this->dispatchAfterEvent($model, Event::SAVE);
            }
        }

        return $this;
    }
994623
public function updateAllAction() {
        QC::executeSQL('SET FOREIGN_KEY_CHECKS = 0');
        ModelOperator::getInstance(DC::getEnvironment()->getUserClassesRoot().'db/')->updateDBForAllModels();
        ModelOperator::getInstance()->generateAllModelClasses();
        $this->writeln('DB updated');
    }
752530
public function update()
    {
        // Do the initial check
        $fromTables = $this->getInstalledTables();
        $toTables = $this->getSchemaTables();
        $protectedTableNames = $this->app['schema.content_tables']->keys();

        $this->getSchemaComparator()->compare($fromTables, $toTables, $protectedTableNames, true);
        $response = $this->getSchemaComparator()->getResponse();
        $creates = $this->getSchemaComparator()->getCreates();
        $alters = $this->getSchemaComparator()->getAlters();

        $modifier = new TableModifier($this->connection, $this->app['logger.system'], $this->app['logger.flash']);
        $modifier->createTables($creates, $response);
        $modifier->alterTables($alters, $response);

        $event = new SchemaEvent($creates, $alters);
        $this->app['dispatcher']->dispatch(SchemaEvents::UPDATE, $event);

        // Recheck now that we've processed
        $fromTables = $this->getInstalledTables();
        $toTables = $this->getSchemaTables();
        $this->getSchemaComparator()->compare($fromTables, $toTables, $protectedTableNames);
        if (!$this->getSchemaComparator()->hasPending($fromTables, $toTables, $protectedTableNames)) {
            $this->getSchemaTimer()->setCheckExpiry();
        }

        return $response;
    }
340345
def update(self):
        
        if self.instance is None:
            raise CQLEngineException("DML Query intance attribute is None")
        assert type(self.instance) == self.model
        null_clustering_key = False if len(self.instance._clustering_keys) == 0 else True
        static_changed_only = True
        statement = UpdateStatement(self.column_family_name, ttl=self._ttl,
                                    timestamp=self._timestamp, transactions=self._transaction)
        for name, col in self.instance._clustering_keys.items():
            null_clustering_key = null_clustering_key and col._val_is_null(getattr(self.instance, name, None))
        #get defined fields and their column names
        for name, col in self.model._columns.items():
            # if clustering key is null, don't include non static columns
            if null_clustering_key and not col.static and not col.partition_key:
                continue 
            if not col.is_primary_key:
                val = getattr(self.instance, name, None)
                val_mgr = self.instance._values[name]

                # don't update something that is null
                if val is None:
                    continue

                # don't update something if it hasn't changed
                if not val_mgr.changed and not isinstance(col, Counter):
                    continue
                
                static_changed_only = static_changed_only and col.static
                if isinstance(col, (BaseContainerColumn, Counter)):
                    # get appropriate clause
                    if isinstance(col, List): klass = ListUpdateClause
                    elif isinstance(col, Map): klass = MapUpdateClause
                    elif isinstance(col, Set): klass = SetUpdateClause
                    elif isinstance(col, Counter): klass = CounterUpdateClause
                    else: raise RuntimeError

                    # do the stuff
                    clause = klass(col.db_field_name, val,
                            previous=val_mgr.previous_value, column=col)
                    if clause.get_context_size() > 0:
                        statement.add_assignment_clause(clause)
                else:
                    statement.add_assignment_clause(AssignmentClause(
                        col.db_field_name,
                        col.to_database(val)
                    ))

        if statement.get_context_size() > 0 or self.instance._has_counter:
            for name, col in self.model._primary_keys.items():
                # only include clustering key if clustering key is not null, and non static columns are changed to avoid cql error
                if (null_clustering_key or static_changed_only) and (not col.partition_key):
                    continue
                statement.add_where_clause(WhereClause(
                    col.db_field_name,
                    EqualsOperator(),
                    col.to_database(getattr(self.instance, name))
                ))
            self._execute(statement)

        if not null_clustering_key:
            self._delete_null_columns()
920251
public function update()
    {
        $args = func_get_args();
        $user = null;

        if (count($args) == 1 && $args[0] instanceof User) {
            $user = $args[0];
        } elseif (count($args) == 2 && !empty($args[0]) && is_array($args[1])) {
            $user = $this->find($args[0]);
            $user->fill($args[1]);
        }

        if ($user instanceof User) {
            if ($this->fireEvent('updating', array($user)) === false) {
                return false;
            }

            $user->setCaller($this);
            $user->save();

            $this->fireEvent('updated', array($user));

            return $user;
        }

        throw new Exception(sprintf(Exception::CANT_UPDATE_MODEL,
            'Subbly\\Model\\User',
            $this->name()
        ));
    }
573433
public function actionUpdate()
    {
        /** @var Authentication $model */
        if (($model = Authentication::findOne(['user_id' => Yii::$app->user->id])) == null) {
            return $this->redirect(['create']);
        }
        $model->scenario = Authentication::SCENARIO_UPDATE;
        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['index']);
        }
        return $this->render('update', [
            'model' => $model,
        ]);
    }