/** * POST save method that accepts data via JSON POST and either saves an old item (if id is valid) or creates a new one * * @param string $modelName * @param int $id * * @return JSON */ public function action_save($modelName, $id = false) { $model = ModelHelper::getModel($modelName, $id); //fill the model with our input ModelHelper::fillModel($model); $rules = isset($model::$rules) ? $model::$rules : array(); //if the model exists, this is an update if ($model->exists) { //so only include dirty fields $data = $model->get_dirty(); //and validate the fields that are being updated $rules = array_intersect_key($rules, $data); } else { //otherwise validate everything $data = $model->attributes; } //validate the model $validator = Validator::make($data, $rules); if ($validator->fails()) { return Response::json(array('success' => false, 'errors' => $validator->errors->all())); } else { $model->save(); //Save the relationships ModelHelper::saveRelationships($model); return Response::json(array('success' => true, 'data' => $model->to_array())); } }
/** * POST save method that accepts data via JSON POST and either saves an old item (if id is valid) or creates a new one * * @param ModelConfig $config * @param int $id * * @return JSON */ public function action_save($config, $id = false) { $model = ModelHelper::getModel($config, $id, false, false, true); //fill the model with our input ModelHelper::fillModel($config, $model); $rules = isset($model::$rules) ? $model::$rules : array(); //if the model exists, this is an update if ($model->exists) { //check if the user has permission to update if (!$config->actionPermissions['update']) { return Response::json(array('success' => false, 'errors' => 'There was an error updating this item. Please reload the page and try again.')); } //so only include dirty fields $data = $model->get_dirty(); //and validate the fields that are being updated $rules = array_intersect_key($rules, $data); } else { //check if the user has permission to create if (!$config->actionPermissions['create']) { return Response::json(array('success' => false, 'errors' => 'There was an error creating this item. Please reload the page and try again.')); } //otherwise validate everything $data = $model->attributes; } //validate the model $validator = Validator::make($data, $rules); if ($validator->fails()) { return Response::json(array('success' => false, 'errors' => $validator->errors->all())); } else { $model->save(); //Save the relationships ModelHelper::saveRelationships($config, $model); return Response::json(array('success' => true, 'data' => $model->to_array())); } }