/** * Save and create record to DB. * @return array */ private function save() { $params = Params::getMergeParams($this->request); $id = intval(@$params['id']); $modelName = Analyzer::getModelName($this->request->get('_url')); $this->logManager->setRequestId(); if ($id) { /** * @var \Phalcon\Mvc\Model $model */ $model = $modelName::findFirst($id); if (!$model) { return array('success' => false, 'msg' => 'Record with id ' . $id . ' not found'); } $model->assign($params); $this->securityManager->check(array('model' => $model, 'action' => CrudOperations::UPDATE, 'modelName' => $modelName, 'params' => $params)); $this->logManager->setOldModel($model); if ($model->save()) { $this->logManager->updateModel($model); $errors = $this->saveRelations($model, Params::getRelations($this->request)); if ($errors !== array()) { return array('success' => false, 'msg' => implode('<br>', $errors)); } return array('success' => true, 'msg' => 'Record with id ' . $id . ' saved!'); } return array('success' => false, 'msg' => $this->jsonRecursiveGetMsg($model->getMessages())); } unset($params['id']); /** * @var \Phalcon\Mvc\Model $model */ $model = new $modelName(); $model->assign($params); $this->securityManager->check(array('model' => $model, 'action' => CrudOperations::CREATE, 'modelName' => $modelName, 'params' => $params)); if ($model->save()) { $this->logManager->createModel($model); $errors = $this->saveRelations($model, Params::getRelations($this->request)); if ($errors !== array()) { return array('success' => false, 'msg' => implode('<br>', $errors)); } return array('success' => true, 'msg' => 'New record saved!', 'id' => $model->id); } return array('success' => false, 'msg' => $this->jsonRecursiveGetMsg($model->getMessages())); }
/** * @param array $relationData * @param \Phalcon\Mvc\Model $model * @param string $relationName * @return mixed * @throws Exception */ private function update(array $relationData, $model, $relationName) { if (empty($relationData['id'])) { throw new Exception('relation "' . $relationName . '" have need id for update operation.'); } $id = intval($relationData['id']); $relation = $model->getModelsManager()->getRelationByAlias(get_class($model), $relationName); $relationClass = $relation->getReferencedModel(); $modelRelation = $relationClass::findFirstById($id); if (!$modelRelation) { throw new Exception($relationClass . '::findFirstById, with id=' . $id . ' not found'); } $modelRelation->assign($relationData); $this->securityManager->check(array('model' => $modelRelation, 'action' => CrudOperations::CREATE, 'modelName' => get_class($modelRelation), 'params' => $relationData)); $this->logManager->setOldModel($modelRelation); $result = $modelRelation->save(); if ($result) { $this->logManager->updateModel($modelRelation); } return $result; }