validate() публичный статический Метод

This is a helper method that simplifies the way of writing AJAX validation code. For example, you may use the following code in a controller action to respond to an AJAX validation request: php $model = new Post; $model->load(Yii::$app->request->post()); if (Yii::$app->request->isAjax) { Yii::$app->response->format = Response::FORMAT_JSON; return ActiveForm::validate($model); } ... respond to non-AJAX request ... To validate multiple models, simply pass each model as a parameter to this method, like the following: php ActiveForm::validate($model1, $model2, ...);
public static validate ( Model $model, mixed $attributes = null ) : array
$model yii\base\Model the model to be validated.
$attributes mixed list of attributes that should be validated. If this parameter is empty, it means any attribute listed in the applicable validation rules should be validated. When this method is used to validate multiple models, this parameter will be interpreted as a model.
Результат array the error message array indexed by the attribute IDs.
Пример #1
3
 /**
  * Performs ajax validation.
  *
  * @param \yii\base\Model $model
  *
  * @throws \yii\base\ExitException
  */
 protected function performValidationModel(Model $model)
 {
     if ($model->load(Yii::$app->request->post())) {
         return ActiveForm::validate($model);
     }
     return;
 }
Пример #2
2
 /**
  * Creates a new Usuarios model.
  * If creation is successful, the browser will be redirected to the 'view' page.
  * @return mixed
  */
 public function actionCrear()
 {
     $model = new CrearUsuarioForm();
     if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
         Yii::$app->response->format = Response::FORMAT_JSON;
         return ActiveForm::validate($model);
     }
     if ($model->load(Yii::$app->request->post())) {
         $model->setPassword($model->clave_hash);
         $model->generateAuthKey();
         $model->tipo = Usuarios::ES_VISITA;
         $model->save();
         $archivo_tmp_original = Yii::getAlias('@backend') . '/web/' . str_replace(".", '-original.', $model->imagen_nombre);
         $archivo_tmp = Yii::getAlias('@backend') . '/web/' . $model->imagen_nombre;
         $imagen_nombre = $model->idusuario . '_' . uniqid() . '.png';
         $ruta = Yii::getAlias('@common') . '/imagenes/usuarios/' . $imagen_nombre;
         $data = base64_decode($model->imagen_data);
         file_put_contents($ruta, $data);
         if (file_exists($ruta)) {
             $imgModel = Usuarios::find()->where(['idusuario' => $model->idusuario])->one();
             $imgModel->foto = $imagen_nombre;
             $imgModel->save();
             if (file_exists($archivo_tmp)) {
                 unlink($archivo_tmp);
                 unlink($archivo_tmp_original);
             }
         }
         return $this->redirect(['detalle/' . $model->idusuario]);
     } else {
         return $this->render('crear', ['model' => $model]);
     }
 }
Пример #3
2
 /**
  * VISTA PUBLICAR ARTICULO
  * @return string
  */
 public function run()
 {
     $session = Yii::$app->session;
     $idUsuario = Yii::$app->user->getId();
     $claveSession = ImagenHelper::SESSION_IMAGEN_ARTICULO . $idUsuario;
     $model = new CrearEditarDescuentoForm();
     $model->scenario = CrearEditarDescuentoForm::ESCENARIO_CREAR;
     $model->usuario = $idUsuario;
     if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
         Yii::$app->response->format = Response::FORMAT_JSON;
         return ActiveForm::validate($model);
     }
     if ($model->load(Yii::$app->request->post())) {
         if ($session->has($claveSession)) {
             $files = $session->get($claveSession);
             $model->imagenes = $files['file'];
             $model->principal = Yii::$app->request->post('dropzone_imagen_principal');
         }
         if ($model->crear()) {
             // file is uploaded successfully
             $session->remove($claveSession);
             //Toast::widget(['tipo'=>'success', 'mensaje'=>'Se ha creado la categor�a con �xito']);
             Yii::$app->session->setFlash('success', 'Se ha creado la categoria con exito');
             return $this->controller->redirect('/');
             $data = 'Se ha publicado';
             Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
             return $data;
         }
     } else {
         $session->remove($claveSession);
         return $this->controller->render('publicar-descuento', ['model' => $model]);
     }
 }
Пример #4
1
 public function run()
 {
     $request = Yii::$app->request;
     $user = Yii::createObject($this->modelClass, ['scenario' => $this->scenario]);
     $profile = Yii::createObject($this->profileClass);
     $roles = [];
     if ($this->roleArray !== null) {
         $roles = call_user_func($this->roleArray, $this);
     }
     $roleArray = ArrayHelper::map($roles, 'name', 'description');
     $statusArray = [];
     if ($this->statusArray !== null) {
         $statusArray = call_user_func($this->statusArray, $this);
     }
     if ($user->load($request->post()) && $profile->load($request->post())) {
         if ($user->validate() && $profile->validate()) {
             $user->populateRelation('profile', $profile);
             if ($user->save(false)) {
                 $this->trigger('success', new Event(['data' => $user]));
                 return $this->controller->redirect(Url::to([$this->updateRoute, 'id' => $user->id]));
             } else {
                 $this->trigger('success', new Event(['data' => Module::t('admin', 'Failed create user')]));
                 return $this->controller->refresh();
             }
         } elseif ($request->isAjax) {
             Yii::$app->response->format = Response::FORMAT_JSON;
             return array_merge(ActiveForm::validate($user), ActiveForm::validate($profile));
         }
     }
     return $this->render(compact(['user', 'profile', 'roleArray', 'statusArray']));
 }
Пример #5
1
 public function actionValidateadd()
 {
     if (Yii::$app->request->get('type') == 'out') {
         $model = new OutRecord();
     } else {
         $model = new InRecord();
     }
     Yii::$app->response->format = yii\web\Response::FORMAT_JSON;
     if ($model->load(Yii::$app->request->post())) {
         $member = Member::isExist($model->membername);
         $result = yii\widgets\ActiveForm::validate($model);
         if (!$member) {
             $model->addError('membername', '用户编号不存在,请确认后输入');
         } else {
             if (Yii::$app->request->get('type') == 'out') {
                 if ($model->account_type == 1) {
                     $compareData = $member->finance_fund;
                 } else {
                     $compareData = $member->stack_fund;
                 }
                 if ($model->amount > $compareData) {
                     $model->addError('amount', '账户余额不足,理财账户余额: ' . $member->finance_fund . '. 购股账户余额: ' . $member->stack_fund);
                 }
             }
         }
         foreach ($model->getErrors() as $attribute => $errors) {
             $result[yii\helpers\Html::getInputId($model, $attribute)] = $errors;
         }
         echo json_encode($result);
     } else {
         echo json_encode(array());
     }
     Yii::$app->end();
 }
 /**
  * Performs ajax validation.
  * @param Model $model
  */
 protected function performAjaxValidation(Model $model)
 {
     if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
         Yii::$app->response->format = Response::FORMAT_JSON;
         return ActiveForm::validate($model);
     }
 }
Пример #7
1
 /**
  * Creates a new Staff model.
  * If creation is successful, the browser will be redirected to the 'view' page.
  * @return mixed
  */
 public function actionCreate()
 {
     if (Yii::$app->user->can('admin')) {
         $model = new Staff();
         if (Yii::$app->request->isAjax && $model->load($_POST)) {
             Yii::$app->response->format = 'json';
             return \yii\widgets\ActiveForm::validate($model);
         }
         if ($model->load(Yii::$app->request->post())) {
             $user = new Users();
             $user->usertype = 'Staff';
             $user->password = strtolower($model->apellido1 . substr($model->rut, 5, -2));
             $user->email = $model->correo;
             $model->save();
             $user->id_orig = $model->id;
             $user->username = $model->nombre . " " . $model->apellido1;
             $user->save();
             return $this->redirect(['view', 'id' => $model->id]);
         } else {
             return $this->render('create', ['model' => $model]);
         }
     } else {
         throw new ForbiddenHttpException();
     }
 }
Пример #8
0
 /**
  * Create Record model or update an existing Record model. Create Files and attach to Record model.
  * If update is successful, the browser will be redirected to the 'upload' page.
  * @return array|string|Response
  * @throws \yii\web\NotFoundHttpException
  */
 public function run()
 {
     $recordId = Yii::$app->request->get('id');
     if ($recordId) {
         $model = $this->controller()->findModel(Record::className(), $recordId);
     } else {
         $model = new Record();
         $model->scenario = Record::SCENARIO_UPLOAD;
     }
     $model->user_id = Yii::$app->user->id;
     if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
         Yii::$app->response->format = Response::FORMAT_JSON;
         return ActiveForm::validate($model);
     }
     $post = Yii::$app->request->post();
     if ($model->load($post) && $model->validate()) {
         if ($this->saveRecord($model, $post)) {
             Yii::$app->trigger(EventNames::UPLOAD_SUCCESS, new UploadEvent(['record' => $model, 'user_id' => Yii::$app->user->id]));
         }
         return $this->controller()->redirect(['upload', 'id' => $model->id]);
     }
     $media = self::media();
     $uploadUrl = $media->uploadRoute;
     $handleUrl = $media->handleRoute;
     $dropZone = $media->dropZone;
     $maxFileSize = $media->maxFileSize;
     $maxChunkSize = $media->maxChunkSize;
     $acceptMimeTypes = $media->acceptMimeTypes;
     $view = $recordId ? 'edit' : 'upload';
     return $this->controller()->render($view, ['model' => $model, 'handleUrl' => $handleUrl, 'uploadUrl' => $uploadUrl, 'dropZone' => $dropZone, 'maxFileSize' => $maxFileSize, 'maxChunkSize' => $maxChunkSize, 'acceptMimeTypes' => $acceptMimeTypes]);
 }
Пример #9
0
 /**
  * @inheritdoc
  */
 public function run()
 {
     $request = Yii::$app->getRequest();
     $modelClass = $this->modelClass === null ? $this->controller->modelClass : $this->modelClass;
     //找到当前模型的所有主键,拼接成数组条件
     $pks = $modelClass::primaryKey();
     $pkValues = [];
     $requestMethod = $request->isGet ? 'get' : 'post';
     foreach ($pks as $pk) {
         $pkValues[$pk] = $request->{$requestMethod}($pk);
     }
     $from = $request->{$requestMethod}('from');
     $model = $modelClass::findOne($pkValues);
     if ($model === null) {
         throw new NotFoundHttpException('没有找到相应的记录!');
     }
     $model->scenario = $this->scenario;
     //如果是提交数据则尝试保存
     if ($model->load($request->post())) {
         if (false !== $model->save()) {
             return $this->controller->flash(['message' => $this->successMsg, 'url' => $from]);
         } elseif ($request->isAjax) {
             //如果是ajax请求则返回错误信息而不是直接跳转到原页面
             $errors = ActiveForm::validate($model);
             return $this->controller->flash(['type' => 'error', 'message' => $this->errorMsg, 'time' => 3000, 'data' => ['errors' => $errors]]);
         }
     }
     //获取当前模型的控件属性
     $controlAttributes = method_exists($model, 'controlAttributes') ? $model->controlAttributes() : [];
     //\yii\helpers\VarDumper::dump($model, 10, true);
     return $this->controller->render($this->view, ['controlAttributes' => $controlAttributes, 'get' => $request->get(), 'model' => $model, 'pks' => $pks, 'from' => $from]);
 }
Пример #10
0
 public function actionValidatebuy()
 {
     $model = new StackTransaction();
     $stack = Stack::findOne(Yii::$app->request->get('id'));
     if ($model->load(Yii::$app->request->post())) {
         $data = Yii::$app->request->post();
         $result = ActiveForm::validate($model);
         $model->price = $stack->price;
         $model->member_id = Yii::$app->user->identity->id;
         $model->stack_id = $stack->id;
         $model->type = 0;
         $model->total_price = $model->price * $model->volume;
         if ($data['StackTransaction']['password2'] && Yii::$app->user->identity->validatePassword2($data['StackTransaction']['password2'])) {
             $model->addError('password2', '第二密码不正确, 请确认后重新输入.');
         }
         if ($model->account_type == 1 && Yii::$app->user->identity->finance_fund < $model->total_price || $model->account_type == 2 && Yii::$app->user->identity->stack_fund < $model->total_price) {
             if (Yii::$app->user->identity->finance_fund < $model->total_price) {
                 $model->addError('volume', '账户余额不足. 理财基金:.' . Yii::$app->user->identity->finance_fund . '. 购股账户:' . Yii::$app->user->identity->stack_fund);
             }
         }
         foreach ($model->getErrors() as $attribute => $errors) {
             $result[Html::getInputId($model, $attribute)] = $errors;
         }
         Yii::$app->response->format = Response::FORMAT_JSON;
         echo json_encode(ActiveForm::validate($model));
     } else {
         echo json_encode(array());
     }
     Yii::$app->end();
 }
Пример #11
0
 /**
  * Delete user page.
  *
  * @param integer $id User ID
  *
  * @return mixed View
  */
 public function run($id)
 {
     $request = Yii::$app->request;
     $user = $this->findModel($id);
     $user->scenario = $this->scenario;
     $profile = $user->{$this->profileRelation};
     $roles = [];
     if ($this->roleArray !== null) {
         $roles = call_user_func($this->roleArray, $this);
     }
     $roleArray = ArrayHelper::map($roles, 'name', 'description');
     $statusArray = [];
     if ($this->statusArray !== null) {
         $statusArray = call_user_func($this->statusArray, $this);
     }
     if ($user->load($request->post()) && $profile->load($request->post())) {
         if ($user->validate() && $profile->validate()) {
             $user->populateRelation($this->profileRelation, $profile);
             if (!$user->save(false)) {
                 $this->trigger('danger', new Event(['data' => $user]));
                 //Yii::$app->session->setFlash('danger', Module::t('admin', 'Failed update user'));
             }
             return $this->controller->refresh();
         } elseif ($request->isAjax) {
             Yii::$app->response->format = Response::FORMAT_JSON;
             return array_merge(ActiveForm::validate($user), ActiveForm::validate($profile));
         }
     }
     return $this->render(compact(['user', 'profile', 'roleArray', 'statusArray']));
 }
Пример #12
0
 public function actionRegister()
 {
     //     	if (!\Yii::$app->user->isGuest) {
     //     		return $this->goHome();
     //     	}
     $model = new RegisterForm();
     if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
         Yii::$app->response->format = Response::FORMAT_JSON;
         return ActiveForm::validate($model, 'username');
     }
     if ($model->load(Yii::$app->request->post())) {
         if ($model->validate()) {
             $user = new User();
             $user->username = $model->username;
             $user->setPassword($model->password);
             $user->email = $model->email;
             $user->name = $model->name;
             $user->surname = $model->surname;
             Yii::trace($user);
             if ($user->save(false)) {
                 return $this->redirect('/user/login');
             }
         }
     }
     return $this->render('register', ['model' => $model]);
 }
Пример #13
0
 /**
  * @param string $back
  * @return string
  */
 public function run($back = null)
 {
     if (!Yii::$app->user->isGuest) {
         if ($back) {
             return Yii::$app->response->redirect($back);
         }
         return $this->controller->goHome();
     }
     /** @var AuthLoginFormInterface|Model $model */
     $model = Yii::createObject($this->modelClass);
     $postData = Yii::$app->request->post();
     if ($model->load($postData)) {
         $request = Yii::$app->request;
         if ($request->isAjax && !$request->isPjax) {
             Yii::$app->response->format = Response::FORMAT_JSON;
             return ActiveForm::validate($model);
         }
         if ($model->login()) {
             if ($back) {
                 return Yii::$app->response->redirect($back);
             }
             return $this->controller->goBack();
         }
     }
     return $this->controller->render($this->viewName, ['model' => $model]);
 }
 /**
  * @return string
  */
 public function run()
 {
     /** @var ActiveRecord $model */
     $model = Yii::createObject($this->modelClass);
     $model->scenario = $this->scenario;
     $params = Yii::$app->getRequest()->getBodyParams();
     if ($model->load($params)) {
         if ($this->enableAjaxValidation && Yii::$app->request->isAjax && !empty($params['ajax'])) {
             Yii::$app->response->format = Response::FORMAT_JSON;
             return ActiveForm::validate($model);
         }
         if ($model->save()) {
             if (is_callable($this->successCallback)) {
                 call_user_func($this->successCallback, $model, $this);
             } elseif ($this->successCallback !== false) {
                 Yii::$app->session->setFlash('create:success');
             }
             if ($this->redirectUrl) {
                 return $this->redirect($model);
             }
         } else {
             if (is_callable($this->errorCallback)) {
                 call_user_func($this->errorCallback, $model, $this);
             } elseif ($this->errorCallback !== false) {
                 Yii::$app->session->setFlash('create:error');
             }
         }
     }
     if (!$this->viewFile) {
         return null;
     }
     /** @var Controller $controller */
     $controller = $this->controller;
     return $controller->render($this->viewFile, ['model' => $model]);
 }
Пример #15
0
 /**
  * Sign Up page.
  * If record will be successful created, user will be redirected to home page.
  */
 public function run()
 {
     $user = Yii::createObject($this->modelClass, ['scenario' => 'signup']);
     $profile = Yii::createObject($this->profileClass);
     $post = Yii::$app->request->post();
     if ($user->load($post) && $profile->load($post)) {
         if ($user->validate() && $profile->validate()) {
             $user->populateRelation('profile', $profile);
             if ($user->save(false)) {
                 if (Module::param('requireEmailConfirmation', false)) {
                     $this->trigger('success', new Event(['data' => Module::t('model', 'Your account has been created successfully. An email has been sent to you with detailed instructions.', ['url' => Url::to($this->resendRoute)])]));
                 } else {
                     Yii::$app->user->login($user);
                     $this->trigger('success', new Event(['data' => Module::t('model', 'Your account has been created successfully.')]));
                 }
                 return $this->controller->goHome();
             } else {
                 $this->trigger('danger', new Event(['data' => Module::t('model', 'Create account failed. Please try again later.')]));
                 return $this->controller->refresh();
             }
         } elseif (Yii::$app->request->isAjax) {
             Yii::$app->response->format = Response::FORMAT_JSON;
             return array_merge(ActiveForm::validate($user), ActiveForm::validate($profile));
         }
     }
     return $this->render(compact('user', 'profile'));
 }
Пример #16
0
 /** Create user */
 public function actionCreate()
 {
     $user = new User(['scenario' => 'admin-create']);
     $statusArray = User::getStatusArray();
     $roles = ArrayHelper::map(Yii::$app->authManager->getRoles(), 'name', 'description');
     if ($user->load(Yii::$app->request->post())) {
         if ($user->validate()) {
             if ($user->save(false)) {
                 foreach (Yii::$app->request->post('roles') as $role) {
                     $new_role = Yii::$app->authManager->getRole($role);
                     Yii::$app->authManager->assign($new_role, $user->getId());
                 }
                 Yii::$app->session->setFlash('success', Yii::t('userscube', 'USER_CREATE_SUCCESS'));
                 return $this->redirect(['update', 'id' => $user->id]);
             } else {
                 Yii::$app->session->setFlash('danger', Yii::t('userscube', 'USER_CREATE_FAIL'));
                 return $this->refresh();
             }
         } elseif (Yii::$app->request->isAjax) {
             Yii::$app->response->format = Response::FORMAT_JSON;
             return ActiveForm::validate($user);
         }
     }
     return $this->render('create', ['user' => $user, 'roles' => $roles, 'statusArray' => $statusArray]);
 }
Пример #17
0
 /**
  * Edit menu
  * @param $id
  * @return array|string|Response
  */
 public function actionEdit($id)
 {
     $model = Menu::findOne($id);
     $this->layout = 'menu';
     if ($model === null) {
         $this->flash('error', Yii::t('easyii', 'Not found'));
         return $this->redirect(['/admin/' . $this->module->id]);
     }
     if (isset($_POST['Menu'])) {
         if ($model->load(Yii::$app->request->post())) {
             if (Yii::$app->request->isAjax) {
                 Yii::$app->response->format = Response::FORMAT_JSON;
                 return ActiveForm::validate($model);
             } else {
                 if ($model->save()) {
                     $this->flash('success', Yii::t('site', 'Menu updated'));
                 } else {
                     $this->flash('error', Yii::t('site', 'Update error. {0}', $model->formatErrors()));
                 }
                 return $this->refresh();
             }
         }
     } else {
         return $this->render('edit', ['model' => $model]);
     }
 }
Пример #18
0
 public function run()
 {
     /** @var User $user */
     $user = Yii::$app->user->identity;
     if ($user === null) {
         throw new ServerErrorHttpException("No user identity found");
     }
     $user->setScenario(User::SCENARIO_PROFILE_UPDATE);
     if ($user->load(Yii::$app->request->post())) {
         if (Yii::$app->request->isAjax) {
             Yii::$app->response->format = Response::FORMAT_JSON;
             // perform AJAX validation
             echo ActiveForm::validate($user);
             Yii::$app->end();
             return '';
         }
         if ($user->username_is_temporary && count($user->getDirtyAttributes(['username'])) === 1) {
             $user->username_is_temporary = false;
         }
         if ($user->save()) {
             $returnUrl = RedirectHelper::getPostedReturnUrl();
             if ($returnUrl !== null) {
                 return $this->controller->redirect($returnUrl);
             } else {
                 Yii::$app->session->setFlash('success', Yii::t('users', 'Your profile sucessfully updated.'));
             }
         }
     }
     return $this->controller->render($this->viewFile, ['profileWidgetOptions' => $this->profileWidgetOptions, 'user' => $user]);
 }
Пример #19
0
 /**
  * Performs AJAX validation of the model via [[ActiveForm::validate()]].
  * @param Model $model main model.
  * @return array the error message array indexed by the attribute IDs.
  */
 protected function performAjaxValidation($model)
 {
     /* @var $this Action */
     $event = new ActionEvent($this, ['model' => $model, 'result' => ActiveForm::validate($model)]);
     $this->trigger('afterAjaxValidate', $event);
     return $event->result;
 }
Пример #20
0
 public function actionModificar($id = null)
 {
     $model = new ValidarDeporte();
     if ($model->load(Yii::$app->request->post()) && Yii::$app->request->isAjax) {
         Yii::$app->response->format = Response::FORMAT_JSON;
         return ActiveForm::validate($model);
     }
     if ($model->load(Yii::$app->request->post())) {
         if ($model->validate()) {
             $table = Deporte::findOne($model->deporte);
             $table->id_deporte = $model->deporte;
             $table->nombre_deporte = strtolower($model->nombre_deporte);
             if ($table->update()) {
                 $model->nombre_deporte = null;
                 $model->deporte = null;
             }
         } else {
             $model->getErrors();
         }
         $this->redirect(["deporte/buscar"]);
     }
     if (Yii::$app->request->get()) {
         if (preg_match("/^[0-9]+\$/", $id)) {
             $table = Deporte::findOne($id);
             $model->deporte = $table->id_deporte;
             $model->nombre_deporte = $table->nombre_deporte;
             return $this->render("modificar_deporte", ['model' => $model]);
         }
     }
     $this->redirect(["deporte/buscar"]);
 }
Пример #21
0
 public function actionLogo()
 {
     $model = Setting::find()->where(['name' => 'logo'])->one();
     if ($model === null || $model->visibility < (IS_ROOT ? Setting::VISIBLE_ROOT : Setting::VISIBLE_ALL)) {
         $this->flash('error', Yii::t('easyii', 'Not found'));
         return $this->redirect(['/admin/settings']);
     }
     if ($model->load(Yii::$app->request->post())) {
         if (Yii::$app->request->isAjax) {
             Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
             return ActiveForm::validate($model);
         } else {
             if (isset($_POST['Setting']['value'])) {
                 $model->value = UploadedFile::getInstance($model, 'value');
                 if ($model->value) {
                     $model->value = Image::uploadLogo($model->value, 'logo', false);
                 } else {
                     $model->value = '';
                 }
             }
             if ($model->save()) {
                 $this->flash('success', Yii::t('easyii', 'Setting updated'));
             } else {
                 $this->flash('error', Yii::t('easyii', 'Update error. {0}', $model->formatErrors()));
             }
             return $this->refresh();
         }
     } else {
         return $this->render('logo', ['model' => $model]);
     }
 }
Пример #22
0
 public function run($id)
 {
     /** @var PostBase $model */
     $model = $this->findModel((int) $id);
     if ($this->checkAccess) {
         call_user_func($this->checkAccess, $this->id, $model);
     }
     $model->scenario = $this->scenario;
     /* @var $modelClass PostBase */
     $modelClass = $this->modelClass;
     $statusArray = $modelClass::statusLabels();
     if ($model->load(Yii::$app->request->post())) {
         if ($model->validate()) {
             if ($model->save(false)) {
                 return $this->controller->refresh();
             } else {
                 Yii::$app->session->setFlash('danger', Module::t('admin', 'BACKEND_FLASH_FAIL_ADMIN_UPDATE'));
                 return $this->controller->refresh();
             }
         } elseif (Yii::$app->request->isAjax) {
             Yii::$app->response->format = Response::FORMAT_JSON;
             return ActiveForm::validate($model);
         }
     }
     return $this->controller->render('update', ['model' => $model, 'statusArray' => $statusArray]);
 }
 /**
  * Updates the downloads attribute of  an existing RealEstate model.
  * If update is successful, the browser will be redirected to the 'view' page.
  * @param string $id
  * @return mixed
  */
 public function actionDownloads($id)
 {
     $model = $this->findModel($id);
     if (Yii::$app->request->getIsPost()) {
         $post = Yii::$app->request->post();
         // Ajax request, validate the models
         if (Yii::$app->request->isAjax) {
             // Populate the model with the POST data
             $model->load($post);
             // Validate the model
             $response = ActiveForm::validate($model);
             // Return validation in JSON format
             Yii::$app->response->format = Response::FORMAT_JSON;
             return $response;
             // Normal request, save models
         } else {
             // Save the main model
             if (!$model->load($post) || !$model->save()) {
                 return $this->render('downloads', ['model' => $model]);
             }
             // Set flash message
             Yii::$app->getSession()->setFlash('agenda', Yii::t('app', '"{item}" has been updated', ['item' => $model->fullAddress]));
             // Take appropriate action based on the pushed button
             if (isset($post['close'])) {
                 return $this->redirect(['index']);
             } else {
                 return $this->redirect(['downloads', 'id' => $model->id]);
             }
         }
     }
     return $this->render('downloads', ['model' => $model]);
 }
Пример #24
0
 public function actionEdit($id)
 {
     if (!($model = Item::findOne($id))) {
         return $this->redirect(['/admin/' . $this->module->id]);
     }
     if ($model->load(Yii::$app->request->post())) {
         if (Yii::$app->request->isAjax) {
             Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
             return ActiveForm::validate($model);
         } else {
             if (isset($_FILES) && $this->module->settings['articleThumb']) {
                 $model->image = UploadedFile::getInstance($model, 'image');
                 if ($model->image && $model->validate(['image'])) {
                     $model->image = Image::upload($model->image, 'sections');
                 } else {
                     $model->image = $model->oldAttributes['image'];
                 }
             }
             if ($model->save()) {
                 $this->flash('success', Yii::t('easyii/sections', 'Article updated'));
                 return $this->redirect(['/admin/' . $this->module->id . '/items/edit', 'id' => $model->primaryKey]);
             } else {
                 $this->flash('error', Yii::t('easyii', 'Update error. {0}', $model->formatErrors()));
                 return $this->refresh();
             }
         }
     } else {
         return $this->render('edit', ['model' => $model]);
     }
 }
Пример #25
0
 public function actionDatasave()
 {
     if (Yii::$app->request->isAjax) {
         $step = Yii::$app->session->get('step');
         $FormObj = $step == 1 ? new FormUser() : new FormAncet();
         $FormObj->load(Yii::$app->request->post());
         $e = ActiveForm::validate($FormObj);
         if (empty($e)) {
             $dbObj = $step == 1 ? new user() : new user_questionnaire();
             if ($dbObj->SaveData($FormObj) === true) {
                 if ($step == 1) {
                     Yii::$app->session->set('user', Yii::$app->db->getLastInsertID());
                 }
                 Yii::$app->session->set('step', $step + 1);
                 return $this->renderAjax('widgetForm', ['widget' => $step + 1 !== 3 ? 'app\\widgets\\UserForm\\UserFormWidget' : 'app\\widgets\\UserBonus\\UserBonusWidget']);
             } else {
                 Yii::$app->response->format = Response::FORMAT_JSON;
                 die(print json_encode(['text' => 'error cant add' . ($step == 1 ? ' user' : ' data')]));
             }
         } else {
             Yii::$app->response->format = Response::FORMAT_JSON;
             die(print json_encode($e));
         }
     } else {
         return $this->goHome();
     }
 }
Пример #26
0
 public function actionEdit($id)
 {
     if (!($model = Category::findOne($id))) {
         return $this->redirect(['/admin/catalog']);
     }
     if ($model->load(Yii::$app->request->post())) {
         if (Yii::$app->request->isAjax) {
             Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
             return ActiveForm::validate($model);
         } else {
             if (isset($_FILES) && $this->module->settings['categoryThumb']) {
                 $model->thumb = UploadedFile::getInstance($model, 'thumb');
                 if ($model->thumb && $model->validate(['thumb'])) {
                     $model->thumb = Image::upload($model->thumb, 'catalog', $this->module->settings['categoryThumbWidth'], $this->module->settings['categoryThumbHeight'], $this->module->settings['categoryThumbCrop']);
                 } else {
                     $model->thumb = $model->oldAttributes['thumb'];
                 }
             }
             if ($model->save()) {
                 $this->flash('success', Yii::t('easyii/catalog', 'Category updated'));
             } else {
                 $this->flash('error', Yii::t('easyii', 'Update error. {0}', $model->formatErrors()));
             }
             return $this->refresh();
         }
     } else {
         return $this->render('edit', ['model' => $model]);
     }
 }
Пример #27
0
 public function actionCreate($type = 0)
 {
     $model = new FormOutcome();
     if ($type == 1) {
         $model->account_id = \app\helpers\Linet3Helper::getSetting("company.acc.payvat");
         $model->sum = Accounts::findOne($model->account_id)->getBalance();
     }
     if ($type == 2) {
         $model->account_id = \app\helpers\Linet3Helper::getSetting("company.acc.natinspay");
         $model->sum = Accounts::findOne($model->account_id)->getBalance();
     }
     if ($type == 3) {
         $model->account_id = \app\helpers\Linet3Helper::getSetting("company.acc.pretax");
         $model->sum = Accounts::findOne($model->account_id)->getBalance();
     }
     // Uncomment the following line if AJAX validation is needed
     if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
         Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
         return \yii\widgets\ActiveForm::validate($model);
     }
     if ($model->load(Yii::$app->request->post())) {
         if ($model->transaction()) {
             \Yii::$app->getSession()->setFlash('success', Yii::t('app', 'transaction Success'));
         }
     }
     return $this->render('create', array('model' => $model));
 }
Пример #28
0
 public function actionEdit($id)
 {
     $model = Carousel::findOne($id);
     if ($model === null) {
         $this->flash('error', Yii::t('easyii', 'Not found'));
         return $this->redirect(['/admin/' . $this->module->id]);
     }
     if ($model->load(Yii::$app->request->post())) {
         if (Yii::$app->request->isAjax) {
             Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
             return ActiveForm::validate($model);
         } else {
             if ($fileInstanse = UploadedFile::getInstance($model, 'image')) {
                 $model->image = $fileInstanse;
                 if ($model->validate(['image'])) {
                     $model->image = Image::upload($model->image, 'carousel');
                 } else {
                     $this->flash('error', Yii::t('easyii', 'Update error. {0}', $model->formatErrors()));
                     return $this->refresh();
                 }
             } else {
                 $model->image = $model->oldAttributes['image'];
             }
             if ($model->save()) {
                 $this->flash('success', Yii::t('easyii/carousel', 'Carousel updated'));
             } else {
                 $this->flash('error', Yii::t('easyii/carousel', 'Update error. {0}', $model->formatErrors()));
             }
             return $this->refresh();
         }
     } else {
         return $this->render('edit', ['model' => $model]);
     }
 }
Пример #29
0
 /**
  * VISTA MIS DATOS
  * @return array|string|Response
  * @throws NotFoundHttpException
  * @throws \Exception
  */
 public function run()
 {
     $user = Yii::$app->getUser();
     $model = $this->findModelUsuario($user->id);
     $model->scenario = Usuarios::ESCENARIO_DATOS_PERFIL;
     if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
         Yii::$app->response->format = Response::FORMAT_JSON;
         return ActiveForm::validate($model);
     }
     if ($model->load(Yii::$app->request->post())) {
         $post = Yii::$app->request->post('Usuarios');
         $model->attributes = $post;
         if ($model->validate()) {
             if (!empty($post['clave_nueva'])) {
                 $model->clave_nueva = $post['clave_nueva'];
                 $model->clave = $model->clave_nueva;
                 $model->setPassword($model->clave_nueva);
                 $model->generateAuthKey();
             }
             $model->save(false);
             //
             //                $usuario = Usuarios::find()->where(['idusuario' => $model->idusuario])->one();
             //                $usuario->scenario = Usuarios::ESCENARIO_DATOS_PERFIL;
             //                echo '<pre>';print_r($usuario->attributes);die();
             //                $usuario->attributes = $model->attributes;
             //                $usuario->update(false);
         }
         if (!empty($model->imagen_nombre)) {
             $ruta = ImagenHelper::rutaImagenPerfil();
             $imagen_actual = $ruta . $model->foto;
             $imagen_nueva = $model->idusuario . '_' . uniqid() . '.png';
             $imagen_tmp_original = $ruta . str_replace(".", '-original.', $model->imagen_nombre);
             $imagen_tmp = $ruta . $model->imagen_nombre;
             $data = base64_decode($model->imagen_data);
             file_put_contents($ruta . $imagen_nueva, $data);
             if (file_exists($ruta)) {
                 //actualizo foto nueva
                 //                    $imgModel = Usuarios::find()->where(['idusuario' => $model->idusuario])->one();
                 //                    $imgModel->foto = $imagen_nueva;
                 //                    $imgModel = Usuarios::find()->where(['idusuario' => $model->idusuario])->one();
                 $model->foto = $imagen_nueva;
                 //elimino imagenes fisicas
                 if ($model->update()) {
                     if (file_exists($imagen_actual)) {
                         unlink($imagen_actual);
                     }
                     if (file_exists($imagen_tmp)) {
                         unlink($imagen_tmp);
                     }
                     if (file_exists($imagen_tmp_original)) {
                         unlink($imagen_tmp_original);
                     }
                 }
             }
         }
         return $this->controller->redirect('mis-datos');
     }
     return $this->controller->render('mis-datos', ['model' => $model]);
 }
Пример #30
-1
 /**
  * @inheritdoc
  */
 public function run($id = null, $tab = 'account')
 {
     if (Yii::$app->user->isGuest) {
         return $this->controller->redirect(['user/login']);
     }
     if ($id === null) {
         $user = Yii::$app->user->getIdentity();
     } elseif (Yii::$app->user->can('updateAnyUser')) {
         $user = $this->controller->findModel(User::className(), $id);
     } else {
         throw new \yii\web\ForbiddenHttpException();
     }
     $model = new $this->modelClass($user);
     if (Yii::$app->request->isPost) {
         if (Yii::$app->user->can('updateAnyUser')) {
             $model->setScenario('admin');
         }
         if ($model->load(Yii::$app->request->post()) && $model->save()) {
             $this->controller->addFlash(Controller::FLASH_INFO, Yii::t('app', 'Changes has saved.'));
             $model->reset();
         }
     }
     if (!Yii::$app->request->isPjax && Yii::$app->request->isAjax) {
         Yii::$app->response->format = Response::FORMAT_JSON;
         return ActiveForm::validate($model);
     }
     return $this->render(['model' => $model, 'tab' => $tab]);
 }