This is a helper method that simplifies the way of writing AJAX validation code for tabular input.
For example, you may use the following code in a controller action to respond
to an AJAX validation request:
php
... load $models ...
if (Yii::$app->request->isAjax) {
Yii::$app->response->format = Response::FORMAT_JSON;
return ActiveForm::validateMultiple($models);
}
... respond to non-AJAX request ...
public static validateMultiple ( array $models, mixed $attributes = null ) : array | ||
$models | array | an array of models 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. |
리턴 | array | the error message array indexed by the attribute IDs. |
public function update(AdminAction $adminAction) { /** * @var $model CmsTree */ $model = $this->model; $relatedModel = $model->relatedPropertiesModel; $rr = new RequestResponse(); if (\Yii::$app->request->isAjax && !\Yii::$app->request->isPjax) { $model->load(\Yii::$app->request->post()); $relatedModel->load(\Yii::$app->request->post()); return \yii\widgets\ActiveForm::validateMultiple([$model, $relatedModel]); } if ($rr->isRequestPjaxPost()) { $model->load(\Yii::$app->request->post()); $relatedModel->load(\Yii::$app->request->post()); if ($model->save() && $relatedModel->save()) { \Yii::$app->getSession()->setFlash('success', \Yii::t('skeeks/cms', 'Saved')); if (\Yii::$app->request->post('submit-btn') == 'apply') { } else { return $this->redirect($this->indexUrl); } $model->refresh(); } else { $errors = []; if ($model->getErrors()) { foreach ($model->getErrors() as $error) { $errors[] = implode(', ', $error); } } \Yii::$app->getSession()->setFlash('error', \Yii::t('skeeks/cms', 'Could not save') . $errors); } } return $this->render('_form', ['model' => $model, 'relatedModel' => $relatedModel]); }
public function actionUpdate($id) { $modelClassified = Classified::findOne($id); $modelImage = ClassifiedImage::find()->where(['classified_id' => $id])->all(); //$modelImage = $modelClassified->id; if ($modelClassified->load(Yii::$app->request->post())) { $oldIDs = \yii\helpers\ArrayHelper::map($modelImage, 'id', 'classified_id'); print_r($oldIDs); $modelImage = \common\models\Model::createMultiple(ClassifiedImage::classname(), $modelImage); \common\models\Model::loadMultiple($modelImage, Yii::$app->request->post()); $deletedIDs = array_diff($oldIDs, array_filter(\yii\helpers\ArrayHelper::map($modelImage, 'id', 'classified_id'))); // ajax validation if (Yii::$app->request->isAjax) { Yii::$app->response->format = \yii\web\Response::FORMAT_JSON; return \yii\helpers\ArrayHelper::merge(\yii\widgets\ActiveForm::validateMultiple($modelImage), \yii\widgets\ActiveForm::validate($modelClassified)); } // validate all models $valid = $modelClassified->validate(); $valid = \common\models\Model::validateMultiple($modelImage) && $valid; if ($valid) { $transaction = \Yii::$app->db->beginTransaction(); try { if ($flag = $modelClassified->save(false)) { if (!empty($deletedIDs)) { ClassifiedImage::deleteAll(['id' => $deletedIDs]); } foreach ($modelImage as $i => $modelImage) { $modelImage->classified_id = $modelClassified->id; if (empty($modelImage->imageFile)) { $name = Yii::$app->security->generateRandomString(); $modelImage->imageFile = \yii\web\UploadedFile::getInstance($modelImage, "[{$i}]imageFile"); if ($modelImage->imageFile) { $modelImage->imageFile->saveAs('uploads/' . $name . '.' . $modelImage->imageFile->extension); //Upload files to server ////save path in db column $modelImage->image = 'uploads/' . $name . '.' . $modelImage->imageFile->extension; //$model->fileProfile->saveAs($model->image_profile); } } if (!($flag = $modelImage->save(false))) { $transaction->rollBack(); break; } } } if ($flag) { $transaction->commit(); return $this->refresh(); } } catch (Exception $e) { $transaction->rollBack(); } } } return $this->render('update', ['modelClassified' => $modelClassified, 'modelImage' => empty($modelImage) ? [new ClassifiedImage()] : $modelImage]); }
protected function performAjaxValidationMultiple(array $models) { if (Yii::$app->request->isAjax && Model::loadMultiple($models, Yii::$app->request->post())) { Yii::$app->response->format = Response::FORMAT_JSON; return ActiveForm::validateMultiple($models); } }
/** * Performs ajax validation * * @param $model * @return \yii\console\Response|\yii\web\Response */ protected function performAjaxValidation($model) { $result = $model instanceof Model ? ActiveForm::validate($model) : ActiveForm::validateMultiple($model); $response = Yii::$app->getResponse(); if (!empty($result) && ($ajaxRedirect = Yii::$app->getSession()->get('site_ajax_redirect'))) { $response = $response->redirect($ajaxRedirect); Yii::$app->getSession()->remove('site_ajax_redirect'); } else { $response->format = Response::FORMAT_JSON; $response->data = $result; } return $response; }
public function update(AdminAction $adminAction) { /** * @var $model CmsUser */ $model = $this->model; $relatedModel = $model->relatedPropertiesModel; $passwordChange = new PasswordChangeForm(['user' => $model]); $passwordChange->scenario = PasswordChangeForm::SCENARION_NOT_REQUIRED; $rr = new RequestResponse(); if (\Yii::$app->request->isAjax && !\Yii::$app->request->isPjax) { $model->load(\Yii::$app->request->post()); $relatedModel->load(\Yii::$app->request->post()); $passwordChange->load(\Yii::$app->request->post()); return \yii\widgets\ActiveForm::validateMultiple([$model, $relatedModel, $passwordChange]); } if ($rr->isRequestPjaxPost()) { $model->load(\Yii::$app->request->post()); $relatedModel->load(\Yii::$app->request->post()); $passwordChange->load(\Yii::$app->request->post()); if ($model->save() && $relatedModel->save()) { \Yii::$app->getSession()->setFlash('success', \Yii::t('skeeks/cms', 'Saved')); if ($passwordChange->new_password) { if (!$passwordChange->changePassword()) { \Yii::$app->getSession()->setFlash('error', "Пароль не изменен"); } } if (\Yii::$app->request->post('submit-btn') == 'apply') { } else { return $this->redirect($this->indexUrl); } $model->refresh(); } else { $errors = []; if ($model->getErrors()) { foreach ($model->getErrors() as $error) { $errors[] = implode(', ', $error); } } \Yii::$app->getSession()->setFlash('error', \Yii::t('skeeks/cms', 'Could not save') . ". " . implode($errors)); } } return $this->render('_form', ['model' => $model, 'relatedModel' => $relatedModel, 'passwordChange' => $passwordChange]); }
public function actionStuinforeport() { $selected_list = $query = NULL; $student_data = array(); $model = new StuMaster(); $info = new StuInfo(); $course = $batch = $section = null; if (!empty($_POST['s_info']) && !empty($_POST['StuMaster']['stu_master_course_id']) || (!empty($_POST['StuMaster']['report_batch_id']) || !empty($_POST['StuMaster']['report_section_id']) || !empty($_POST['StuMaster']['report_city']) || !empty($_POST['StuInfo']['stu_gender']))) { if (Yii::$app->request->isAjax) { \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON; return ActiveForm::validateMultiple([$model, $info]); } if (!empty($_POST['StuMaster']['stu_master_course_id'])) { $query .= "stu.stu_master_course_id=" . $_POST['StuMaster']['stu_master_course_id'] . " AND "; } if (!empty($_POST['StuMaster']['report_batch_id'])) { $query .= "stu.stu_master_batch_id=" . $_POST['StuMaster']['report_batch_id'] . " AND "; } if (!empty($_POST['StuMaster']['report_section_id'])) { $query .= "stu.stu_master_section_id=" . $_POST['StuMaster']['report_section_id'] . " AND "; } if (!empty($_POST['StuMaster']['report_city'])) { $query .= "add.stu_cadd_city=" . $_POST['StuMaster']['report_city'] . " AND "; } if (!empty($_POST['StuInfo']['stu_gender'])) { $query .= "s_info.stu_gender='" . $_POST['StuInfo']['stu_gender'] . "' AND "; } if (!empty($_POST['s_info'])) { $selected_list = $_POST['s_info']; } echo $model->validate(); $query1 = new \yii\db\Query(); $query1->select('*')->from('stu_master stu')->join('join', 'stu_info s_info', 's_info.stu_info_id = stu.stu_master_stu_info_id')->join('join', 'stu_address add', 'add.stu_address_id = stu.stu_master_stu_address_id')->where($query . 'stu.is_status = 0'); $command = $query1->createCommand(); $student_data = $command->queryAll(); if (empty($student_data)) { \Yii::$app->getSession()->setFlash('studerror', "<i class='fa fa-exclamation-triangle'></i> <b> No Record For This Criteria.</b>"); return $this->redirect(['stuinforeport']); } return $this->render('stu_info_report', ['student_data' => $student_data, 'selected_list' => $selected_list, 'query' => $query]); break; } return $this->render('stu_report_view', ['model' => $model, 'info' => $info, 'query' => $query, 'selected_list' => $selected_list]); }
/** * Display all config paramters for $byModule. * @return mixed */ public function actionIndex() { $models = Config::find()->where(['module' => $this->byModule])->orderBy(['id' => SORT_ASC])->indexBy('id')->all(); if (Model::loadMultiple($models, Yii::$app->request->post())) { if (Yii::$app->request->isAjax) { Yii::$app->response->format = Response::FORMAT_JSON; return ActiveForm::validateMultiple($models, 'value'); } $result = true; foreach ($models as $model) { $result = $result && $model->save(true, ['value']); } if ($result && Module::getInstance()->configManager->clearCache()) { Yii::$app->session->setFlash('success', Module::t('SAVE_SUCCESS')); return $this->redirect(['index']); } } return $this->render('index', ['models' => $models]); }
/** * @return array|string|Response */ public function run() { $models = ConfigModel::find()->orderBy(['sort' => SORT_ASC])->indexBy('name')->all(); if (Model::loadMultiple($models, Yii::$app->request->post())) { if (Yii::$app->request->isAjax) { Yii::$app->response->format = Response::FORMAT_JSON; return ActiveForm::validateMultiple($models, 'value'); } $result = true; /** @var ConfigModel $model */ foreach ($models as $model) { $result = $result && $model->save(true, ['value']); Config::clearCache($model->name); } if ($result) { Yii::$app->session->setFlash('success', $this->successMessage); return $this->controller->redirect([$this->id]); } } return $this->controller->render($this->viewPath, ['models' => $models]); }
public function actionStuinforeport() { $student_data = $selected_list = []; $model = new StuMaster(); $info = new StuInfo(); if ($model->load(Yii::$app->request->post()) && $info->load(Yii::$app->request->post())) { if (Yii::$app->request->isAjax) { \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON; return ActiveForm::validateMultiple([$model, $info]); } $selected_list = $_POST['s_info']; $query1 = new \yii\db\Query(); $query1->select('*')->from('stu_master stu')->join('join', 'stu_info s_info', 's_info.stu_info_id = stu.stu_master_stu_info_id')->join('join', 'stu_address add', 'add.stu_address_id = stu.stu_master_stu_address_id')->where(['stu.is_status' => 0])->andFilterWhere(['stu.stu_master_course_id' => $model->stu_master_course_id])->andFilterWhere(['stu.stu_master_batch_id' => $model->report_batch_id])->andFilterWhere(['stu.stu_master_section_id' => $model->report_section_id])->andFilterWhere(['add.stu_cadd_city' => $model->report_city])->andFilterWhere(['s_info.stu_gender' => $info->stu_gender]); $command = $query1->createCommand(); $student_data = $command->queryAll(); Yii::$app->session->set('data["stuData"]', $student_data); Yii::$app->session->set('data["selection"]', $selected_list); if (empty($student_data)) { \Yii::$app->getSession()->setFlash('studerror', "<i class='fa fa-exclamation-triangle'></i> <b> " . Yii::t('report', 'No Record Found For This Criteria.') . "</b>"); return $this->redirect(['stuinforeport']); } return $this->render('stu_info_report', ['student_data' => $student_data, 'selected_list' => $selected_list]); } else { if (Yii::$app->request->get('exportExcel')) { $file = $this->renderPartial('stu_info_report_excel', array('student_data' => Yii::$app->session->get('data["stuData"]'), 'selected_list' => Yii::$app->session->get('data["selection"]'))); $fileName = "Employee_info_report" . date('YmdHis') . '.xls'; $options = ['mimeType' => 'application/vnd.ms-excel']; return Yii::$app->excel->exportExcel($file, $fileName, $options); } else { if (Yii::$app->request->get('exportPDF')) { $html = $this->renderPartial('stu_info_report_pdf', array('student_data' => Yii::$app->session->get('data["stuData"]'), 'selected_list' => Yii::$app->session->get('data["selection"]'))); ob_clean(); return Yii::$app->pdf->exportData('Employee Info Report', 'Employee_info_report', $html); } } } return $this->render('stu_report_view', ['model' => $model, 'info' => $info, 'selected_list' => $selected_list]); }
/** * Updates an existing Po model. * If update is successful, the browser will be redirected to the 'view' page. * @param integer $id * @return mixed */ public function actionUpdate($id) { // $model = $this->findModel($id); // // if ($model->load(Yii::$app->request->post()) && $model->save()) { // return $this->redirect(['view', 'id' => $model->id]); // } else { // return $this->render('update', [ // 'model' => $model, // ]); // } $model = $this->findModel($id); $modelsPoItems = $model->poItems; if ($model->load(Yii::$app->request->post())) { $oldIDs = ArrayHelper::map($modelsPoItems, 'id', 'id'); $modelsPoItems = Model::createMultiple(Poitem::classname(), $modelsPoItems); Model::loadMultiple($modelsPoItems, Yii::$app->request->post()); $deletedIDs = array_diff($oldIDs, array_filter(ArrayHelper::map($modelsPoItems, 'id', 'id'))); // ajax validation if (Yii::$app->request->isAjax) { Yii::$app->response->format = Response::FORMAT_JSON; return ArrayHelper::merge(ActiveForm::validateMultiple($modelsPoItems), ActiveForm::validate($model)); } // validate all models $valid = $model->validate(); $valid = Model::validateMultiple($modelsPoItems) && $valid; if ($valid) { $transaction = \Yii::$app->db->beginTransaction(); try { if ($flag = $model->save(false)) { if (!empty($deletedIDs)) { Poitem::deleteAll(['id' => $deletedIDs]); } foreach ($modelsPoItems as $modelPoItem) { $modelPoItem->po_id = $model->id; if (!($flag = $modelPoItem->save(false))) { $transaction->rollBack(); break; } } } if ($flag) { $transaction->commit(); return $this->redirect(['view', 'id' => $model->id]); } } catch (Exception $e) { $transaction->rollBack(); } } } return $this->render('update', ['model' => $model, 'modelsPoItems' => empty($modelsPoItems) ? [new Poitem()] : $modelsPoItems]); }
public function actionSignup() { $model = new SignupForm(); $model_pets = []; for ($i = 1; $i < Yii::$app->params['countPetsInSignup']; $i++) { $model_pets["pet_{$i}"] = new PetForm(); } if ($model->load(Yii::$app->request->post()) && Model::loadMultiple($model_pets, Yii::$app->request->post())) { $model_pet_valid = []; for ($i = 1; $i <= $model->count_pets; $i++) { $model_pet_valid["pet_{$i}"] = clone $model_pets["pet_{$i}"]; } if (Yii::$app->request->isAjax) { Yii::$app->response->format = Response::FORMAT_JSON; $erros = ActiveForm::validate($model); $erros_pets = ActiveForm::validateMultiple($model_pet_valid); return array_merge($erros, $erros_pets); } if (Model::validateMultiple($model_pet_valid) && $model->signup()) { foreach ($model_pet_valid as $pet) { try { /**@var $pet PetForm */ if (!PurinaAuth::init()->createUserPet($pet->name, $pet->gender, $pet->year, $pet->month, $pet->breed)) { $data = PurinaAuth::getData(); if ($data->message) { Yii::$app->session->setFlash("error", $data->message); } } } catch (\Exception $e) { break; } } return $this->goHome(); } else { $validation = true; for ($i = 1; $i <= $model->count_pets; $i++) { /** * @var $model_valid PetForm */ $model_valid = $model_pet_valid["pet_{$i}"]; if ($model_valid->hasErrors()) { $validation = false; $model_pets["pet_{$i}"] = clone $model_valid; } } if (!$validation) { $model->validate(); } } } return $this->render('signup', ['model' => $model, 'model_pets' => $model_pets]); }
$users = User::find()->all(); $scholars = Scholar::find()->all(); $model = new Subject(); $modelCustomer = new Grade(); $modelsAddress = [new Grade()]; foreach ($users as $user) { foreach ($scholars as $scholar) { if ($user->username == $username && $user->id == $scholar->scholar_user_id) { $modelCustomer->subject_scholar_scholar_id = $scholar->scholar_id; if ($modelCustomer->load(Yii::$app->request->post())) { $modelsAddress = GroupGrade::createMultiple(Grade::classname()); GroupGrade::loadMultiple($modelsAddress, Yii::$app->request->post()); // ajax validation if (Yii::$app->request->isAjax) { Yii::$app->response->format = Response::FORMAT_JSON; return ArrayHelper::merge(ActiveForm::validateMultiple($modelsAddress), ActiveForm::validate($modelCustomer)); } // validate all models $valid = $modelCustomer->validate(); $valid = GroupGrade::validateMultiple($modelsAddress) && $valid; if ($valid) { $transaction = \Yii::$app->db->beginTransaction(); try { // if($flag = $modelCustomer->save(false)){ foreach ($modelsAddress as $modelAddress) { $modelAddress->subject_scholar_scholar_id = $modelCustomer->subject_scholar_scholar_id; $modelAddress->grade_school_year_start = $modelCustomer->grade_school_year_start; $modelAddress->grade_school_year_end = $modelCustomer->grade_school_year_end; $selectSchool = ArrayHelper::map(Scholar::find()->where(['scholar_id' => $modelAddress->subject_scholar_scholar_id])->all(), 'school_school_id', 'school_school_id'); $schoolID = array_values($selectSchool)[0]; $modelAddress->subject_scholar_school_school_id = $schoolID;
/** * Performs validation on the provided model and $_POST data * * @param \infoweb\pages\models\Page $model The page model * @param array $post The $_POST data * @return array */ protected function validateModel($model, $post) { $languages = Yii::$app->params['languages']; // Populate the model with the POST data $model->load($post); // Parent is root if (empty($post[StringHelper::basename(MenuItem::className())]['parent_id'])) { $model->parent_id = 0; $model->level = 0; } else { $parent = MenuItem::findOne($post[StringHelper::basename(MenuItem::className())]['parent_id']); $model->parent_id = $parent->id; $model->level = $parent->level + 1; } // Create an array of translation models and populate them $translationModels = []; // Insert if ($model->isNewRecord) { foreach ($languages as $languageId => $languageName) { $translationModels[$languageId] = new MenuItemLang(['language' => $languageId]); } // Update } else { $translationModels = ArrayHelper::index($model->getTranslations()->all(), 'language'); } Model::loadMultiple($translationModels, $post); // Validate the model and translation $response = array_merge(ActiveForm::validate($model), ActiveForm::validateMultiple($translationModels)); // Return validation in JSON format Yii::$app->response->format = Response::FORMAT_JSON; return $response; }
public function update(AdminAction $adminAction) { /** * @var $model CmsContentElement */ $model = $this->model; $relatedModel = $model->relatedPropertiesModel; $shopProduct = ShopProduct::find()->where(['id' => $model->id])->one(); $productPrices = []; if (!$shopProduct) { $shopProduct = new ShopProduct(['id' => $model->id]); $shopProduct->save(); } else { if ($typePrices = ShopTypePrice::find()->where(['!=', 'def', Cms::BOOL_Y])->all()) { foreach ($typePrices as $typePrice) { $productPrice = ShopProductPrice::find()->where(['product_id' => $shopProduct->id, 'type_price_id' => $typePrice->id])->one(); if (!$productPrice) { $productPrice = new ShopProductPrice(['product_id' => $shopProduct->id, 'type_price_id' => $typePrice->id]); } if ($post = \Yii::$app->request->post()) { $data = ArrayHelper::getValue($post, 'prices.' . $typePrice->id); $productPrice->load($data, ""); } $productPrices[] = $productPrice; } } } $rr = new RequestResponse(); if (\Yii::$app->request->isAjax && !\Yii::$app->request->isPjax) { $model->load(\Yii::$app->request->post()); $relatedModel->load(\Yii::$app->request->post()); $shopProduct->load(\Yii::$app->request->post()); return \yii\widgets\ActiveForm::validateMultiple([$model, $relatedModel, $shopProduct]); } if ($rr->isRequestPjaxPost()) { $model->load(\Yii::$app->request->post()); $relatedModel->load(\Yii::$app->request->post()); $shopProduct->load(\Yii::$app->request->post()); /** * @var $productPrice ShopProductPrice */ foreach ($productPrices as $productPrice) { if ($productPrice->save()) { } else { \Yii::$app->getSession()->setFlash('error', \Yii::t('skeeks/shop/app', 'Check the correctness of the prices')); } } if ($model->save() && $relatedModel->save() && $shopProduct->save()) { \Yii::$app->getSession()->setFlash('success', \Yii::t('skeeks/shop/app', 'Saved')); if (\Yii::$app->request->post('submit-btn') == 'apply') { } else { return $this->redirect($this->indexUrl); } $model->refresh(); } else { $errors = []; if ($model->getErrors()) { foreach ($model->getErrors() as $error) { $errors[] = implode(', ', $error); } } \Yii::$app->getSession()->setFlash('error', \Yii::t('skeeks/shop/app', 'Could not save') . $errors); } } if (!$shopProduct->baseProductPrice) { $baseProductPrice = new ShopProductPrice(['type_price_id' => \Yii::$app->shop->baseTypePrice->id, 'currency_code' => \Yii::$app->money->currencyCode, 'product_id' => $model->id]); $baseProductPrice->save(); } return $this->render('_form', ['model' => $model, 'relatedModel' => $relatedModel, 'shopProduct' => $shopProduct, 'productPrices' => $productPrices, 'baseProductPrice' => $shopProduct->getBaseProductPrice()->one()]); }
/** * Allows users to view or update their profile. * @param boolean $update * @return string */ public function actionProfile($update = false) { /** @var ProfileForm */ $model = $this->module->createFormModel('ProfileForm'); $model->setAttributes($model->getIdentity()->getIdentityAttributes()); $loadedModel = $model->load($_POST); /** @var PasswordForm */ $passwordForm = $this->module->createFormModel('PasswordForm'); $loadedPassword = isset($_POST[$passwordForm->formName()]) && trim($_POST[$passwordForm->formName()]['newPassword']) !== '' && $passwordForm->load($_POST); if ($loadedModel) { if ($model->getIdentity() instanceof PictureIdentityInterface && !empty($model->pictureUploadRules)) { $model->picture = \yii\web\UploadedFile::getInstance($model, 'picture'); } $passwordForm->password = $model->password; } if (Yii::$app->request->isAjax) { Yii::$app->response->format = \yii\web\Response::FORMAT_JSON; $models = []; if ($loadedModel) { $models[] = $model; } if ($loadedPassword) { $models[] = $passwordForm; } return \yii\widgets\ActiveForm::validateMultiple($models); } $flashes = ['success' => [], 'error' => []]; /** * Only try to set new password if it has been specified in the form. * The current password could have been used to authorize other changes. */ if ($loadedPassword) { if ($passwordForm->validate() && $passwordForm->resetPassword($model->getIdentity())) { $flashes['success'][] = Yii::t('usr', 'Changes have been saved successfully.'); } else { $flashes['error'][] = Yii::t('usr', 'Failed to change password.'); } } if ($loadedModel && empty($flashes['error'])) { if ($model->validate()) { $oldEmail = $model->getIdentity()->getEmail(); if ($model->save($this->module->requireVerifiedEmail)) { if ($this->module->requireVerifiedEmail && $oldEmail != $model->email) { if ($this->sendEmail($model, 'verify')) { $flashes['success'][] = Yii::t('usr', 'An email containing further instructions has been sent to provided email address.'); } else { $flashes['error'][] = Yii::t('usr', 'Failed to send an email.') . ' ' . Yii::t('usr', 'Try again or contact the site administrator.'); } } $flashes['success'][] = Yii::t('usr', 'Changes have been saved successfully.'); if (!empty($flashes['success'])) { Yii::$app->session->setFlash('success', implode('<br/>', $flashes['success'])); } if (!empty($flashes['error'])) { Yii::$app->session->setFlash('error', implode('<br/>', $flashes['error'])); } return $this->redirect(['profile']); } else { $flashes['error'][] = Yii::t('usr', 'Failed to update profile.') . ' ' . Yii::t('usr', 'Try again or contact the site administrator.'); } } } if (!empty($flashes['success'])) { Yii::$app->session->setFlash('success', implode('<br/>', $flashes['success'])); } if (!empty($flashes['error'])) { Yii::$app->session->setFlash('error', implode('<br/>', $flashes['error'])); } if ($update) { return $this->render('updateProfile', ['model' => $model, 'passwordForm' => $passwordForm]); } else { return $this->render('viewProfile', ['model' => $model]); } }
/** * Updates an existing Usuario model. * If update is successful, the browser will be redirected to the 'view' page. * @param integer $id * @return mixed */ public function actionUpdate($id) { $user = new Usuario(); $user = $this->findModel($id); $modelsConocimientos = $user->conocimientos; $modelsConocimientos = Conocimiento::find()->where(['id_conocimiento' => $user->id_usuario])->all(); $institucion = ArrayHelper::map(Institucion::find()->all(), 'id_institucion', 'nombre'); $cont = Contacto::find()->where(['id_contacto' => $user->id_usuario])->one(); $dir = Direccion::find()->where(['id_direccion' => $user->id_usuario])->one(); $repr = Representante::find()->where(['id_representante' => $user->id_usuario])->one(); if ($user->load(Yii::$app->request->post()) && $cont->load(Yii::$app->request->post()) && $dir->load(Yii::$app->request->post()) && $repr->load(Yii::$app->request->post())) { $oldIDs = ArrayHelper::map($modelsConocimientos, 'id', 'id'); $modelsConocimientos = Model::createMultiple(Conocimiento::classname(), $modelsConocimientos); Model::loadMultiple($modelsConocimientos, Yii::$app->request->post()); $deletedIDs = array_diff($oldIDs, array_filter(ArrayHelper::map($modelsConocimientos, 'id_conocimiento', 'id_conocimiento'))); if (Yii::$app->request->isAjax) { Yii::$app->response->format = Response::FORMAT_JSON; return ArrayHelper::merge(ActiveForm::validateMultiple($modelsConocimientos), ActiveForm::validate($user)); } // validate all models $valid = $user->validate(); $valid = Model::validateMultiple($modelsConocimientos) && $valid; if ($valid) { $transaction = \Yii::$app->db->beginTransaction(); try { if ($flag = $user->save(false)) { if (!empty($deletedIDs)) { Conocimiento::deleteAll(['id' => $deletedIDs]); } foreach ($modelsConocimientos as $modelConocimientos) { $modelConocimientos->Usuarioid_usuario = $user->id_usuario; if (!($flag = $modelConocimientos->save(false))) { $transaction->rollBack(); break; } } } if ($flag) { $transaction->commit(); return $this->redirect(['view', 'id' => $user->id_usuario]); } } catch (Exception $e) { $transaction->rollBack(); } } if ($repr->save() && $cont->save() && $dir->save()) { return $this->redirect(['view', 'id' => $user->id_usuario]); } else { return $this->redirect(['index', 'id' => $user->id_usuario]); } } else { return $this->render('update', ['user' => $user, 'cont' => $cont, 'dir' => $dir, 'repr' => $repr, 'institucion' => $institucion, 'modelsConocimientos' => empty($modelsConocimientos) ? [new Conocimiento()] : $modelsConocimientos]); } }
/** * Updates an existing Image model. * If update is successful, the browser will be redirected to the 'view' page. * @param string $id * @return mixed */ public function actionUpdate($id) { $model = $this->findModel($id); $gallery = Gallery::findOne(Yii::$app->session->get('gallery.gallery-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); // Create an array of translation models and populate them $translationModels = ArrayHelper::index($model->getTranslations()->all(), 'language'); Model::loadMultiple($translationModels, $post); // Validate the model and translation $response = array_merge(ActiveForm::validate($model), ActiveForm::validateMultiple($translationModels)); // Return validation in JSON format Yii::$app->response->format = Response::FORMAT_JSON; return $response; // Normal request, save models } else { // Wrap everything in a database transaction $transaction = Yii::$app->db->beginTransaction(); // Validate the main model if (!$model->load($post)) { return $this->render('update', ['model' => $model]); } // Add the translations foreach (Yii::$app->request->post(StringHelper::basename(ImageLang::className()), []) as $language => $data) { foreach ($data as $attribute => $translation) { $model->translate($language)->{$attribute} = $translation; } } if (!$model->save()) { return $this->render('update', ['model' => $model]); } $transaction->commit(); // Set flash message Yii::$app->getSession()->setFlash('image-success', Yii::t('app', '{item} has been updated', ['item' => $model->name])); return $this->redirect('index'); } } return $this->render('update', ['model' => $model, 'gallery' => $gallery]); }
/** * Updates an existing Alias model. * If update is successful, the browser will be redirected to the 'view' page. * @param string $id * @return mixed */ public function actionUpdate($id) { $languages = Yii::$app->params['languages']; $model = $this->findModel($id); // Load all the translations $model->loadTranslations(array_keys($languages)); // Load the entities $entities = []; $entities['pages'] = (new Query())->select('page.id, page_lang.name')->from(['page' => 'pages'])->innerJoin(['page_lang' => 'pages_lang'], "page.id = page_lang.page_id AND page_lang.language = '" . Yii::$app->language . "'")->orderBy(['page_lang.name' => SORT_ASC])->all(); 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); // Create an array of translation models $translationModels = []; foreach ($languages as $languageId => $languageName) { $translationModels[$languageId] = new AliasLang(['language' => $languageId]); } // Populate the translation models Model::loadMultiple($translationModels, $post); // Validate the model and translation models $response = array_merge(ActiveForm::validate($model), ActiveForm::validateMultiple($translationModels)); // Return validation in JSON format Yii::$app->response->format = Response::FORMAT_JSON; return $response; // Normal request, save models } else { // Wrap the everything in a database transaction $transaction = Yii::$app->db->beginTransaction(); // Save the main model if (!$model->load($post) || !$model->save()) { return $this->render('update', ['model' => $model, 'entities' => $entities]); } // Save the translations foreach ($languages as $languageId => $languageName) { $data = $post['AliasLang'][$languageId]; // Set the translation language and attributes $model->language = $languageId; $model->url = $data['url']; if (!$model->saveTranslation()) { return $this->render('update', ['model' => $model, 'entities' => $entities]); } } $transaction->commit(); // Switch back to the main language $model->language = Yii::$app->language; // Set flash message Yii::$app->getSession()->setFlash('alias', Yii::t('app', '"{item}" has been updated', ['item' => $model->url])); // Take appropriate action based on the pushed button if (isset($post['close'])) { return $this->redirect(['index']); } elseif (isset($post['new'])) { return $this->redirect(['create']); } else { return $this->redirect(['update', 'id' => $model->id]); } } } return $this->render('update', ['model' => $model, 'entities' => $entities]); }
/** * Updates an existing Term model. * If update is successful, the browser will be redirected to the 'view' page. * @param integer $id * @return mixed */ public function actionUpdate($id) { $languages = Yii::$app->params['languages']; $model = Term::findOne($id); $root = Yii::$app->session->get('taxonomy.taxonomy-id'); try { 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); // Create an array of translation models $translationModels = []; foreach ($languages as $languageId => $languageName) { $translationModels[$languageId] = $model->getTranslation($languageId); } // Populate the translation models Model::loadMultiple($translationModels, $post); // Validate the model and translation models $response = array_merge(ActiveForm::validate($model), ActiveForm::validateMultiple($translationModels)); // Return validation in JSON format Yii::$app->response->format = Response::FORMAT_JSON; return $response; // Normal request, save models } else { // Wrap the everything in a database transaction $transaction = Yii::$app->db->beginTransaction(); $parent = Term::findOne($post['Term']['parent_id']); $previous = $model->prev()->one(); // Save the main model if (!$model->load($post)) { throw new Exception(Yii::t('app', 'Failed to load the node')); } /* // If there is a new parent, move as last if ($parent->id <> $model->parents(1)->one()->id) { if (!$model->moveAsLast($parent)) { throw new Exception(Yii::t('app', 'Failed to update the node')); } // If there is a ancestor sibling, move after the sibling } elseif (isset($previous)) { if (!$model->moveAfter($previous)) { throw new Exception(Yii::t('app', 'Failed to update the node')); } // Or else, move as first } else { if (!$model->moveAsFirst($parent)) { throw new Exception(Yii::t('app', 'Failed to update the node')); } } */ // Save the translations foreach ($languages as $languageId => $languageName) { $data = $post['Lang'][$languageId]; // Set the translation language and attributes $model->language = $languageId; $model->name = $data['name']; $model->content = $data['content']; if (!$model->saveTranslation()) { throw new Exception(Yii::t('app', 'Failed to save the translation')); } } $transaction->commit(); // Switch back to the main language $model->language = Yii::$app->language; // Set flash message Yii::$app->getSession()->setFlash('term', Yii::t('app', '"{item}" has been updated', ['item' => $model->name])); // Take appropriate action based on the pushed button if (isset($post['close'])) { return $this->redirect(['index']); } elseif (isset($post['new'])) { return $this->redirect(['create']); } else { return $this->redirect(['update', 'id' => $model->id]); } } } } catch (Exception $e) { if (isset($transaction)) { $transaction->rollBack(); } // Set flash message Yii::$app->getSession()->setFlash('term-error', $e->getMessage()); } return $this->render('update', ['model' => $model, 'terms' => $model::find()->getDropDownListItems($root), 'parent_id' => $model->parents(1)->one()->id]); }
/** * Updates an existing Poll model. * If update is successful, the browser will be redirected to the 'view' page. * @param integer $id * @return mixed */ public function actionUpdate($id) { $model = $this->findModel($id); if ($model->isLocked()) { throw new HttpException(403, Yii::t('app', 'This poll cannot be edited because it has already been accessed by a voter')); } $modelOptions = $model->options; if ($model->load(Yii::$app->request->post())) { $oldIDs = ArrayHelper::map($modelOptions, 'id', 'id'); $modelOptions = Model::createMultiple(Option::classname(), $modelOptions); Model::loadMultiple($modelOptions, Yii::$app->request->post()); $deletedIDs = array_diff($oldIDs, array_filter(ArrayHelper::map($modelOptions, 'id', 'id'))); // ajax validation if (Yii::$app->request->isAjax) { Yii::$app->response->format = Response::FORMAT_JSON; return ArrayHelper::merge(ActiveForm::validateMultiple($modelOptions), ActiveForm::validate($model)); } // validate all models $valid = $model->validate(); $valid = Model::validateMultiple($modelOptions) && $valid; if ($valid) { $transaction = \Yii::$app->db->beginTransaction(); try { if ($flag = $model->save(false)) { if (!empty($deletedIDs)) { Option::deleteAll(['id' => $deletedIDs]); } foreach ($modelOptions as $modelOption) { $modelOption->poll_id = $model->id; if (!($flag = $modelOption->save(false))) { $transaction->rollBack(); break; } } } if ($flag) { $transaction->commit(); return $this->redirect(['view', 'id' => $model->id]); } } catch (Exception $e) { $transaction->rollBack(); } } } return $this->render('update', ['model' => $model, 'modelOptions' => empty($modelOptions) ? [new Option(), new Option()] : $modelOptions]); }
/** * Updates an existing Monitoring1 model. * If update is successful, the browser will be redirected to the 'view' page. * @param integer $id * @return mixed */ public function actionUpdate($id) { $model = $this->findModel($id); $modelsStr = $model->mon1str; if (!Yii::$app->user->can('admin')) { if ($model->user_id != Yii::$app->user->id) { $this->redirect(['index']); } } if (!Yii::$app->user->can('admin')) { if ($model->status == 1) { $this->redirect(['index']); } } $months = Month::find()->all(); $years = Year::find()->all(); // $model->user_id = Yii::$app->user->id; if ($model->load(Yii::$app->request->post())) { $model->date = date('Y-m-d', strtotime($model->date)); if (!Monitoring1::find()->where(['date' => $model->date, 'user_id' => Yii::$app->user->id])->one()) { if ($model->save()) { $oldIDs = ArrayHelper::map($modelsStr, 'id', 'id'); $modelsStr = Model::createMultiple(Mon1str::classname(), $modelsStr); Model::loadMultiple($modelsStr, Yii::$app->request->post()); $deletedIDs = array_diff($oldIDs, array_filter(ArrayHelper::map($modelsStr, 'id', 'id'))); // ajax validation if (Yii::$app->request->isAjax) { Yii::$app->response->format = Response::FORMAT_JSON; return ArrayHelper::merge(ActiveForm::validateMultiple($modelsStr), ActiveForm::validate($model)); } // validate all models $valid = $model->validate(); $valid = Model::validateMultiple($modelsStr) && $valid; if ($valid) { $transaction = \Yii::$app->db->beginTransaction(); try { if ($flag = $model->save(false)) { if (!empty($deletedIDs)) { Mon1str::deleteAll(['id' => $deletedIDs]); } foreach ($modelsStr as $modelStr) { $modelStr->monitoring1_id = $model->id; if (!($flag = $modelStr->save(false))) { $transaction->rollBack(); break; } } } if ($flag) { $transaction->commit(); return $this->redirect(['view', 'id' => $model->id]); } } catch (Exception $e) { $transaction->rollBack(); } } } } } return $this->render('update', ['model' => $model, 'months' => $months, 'years' => $years, 'modelsStr' => empty($modelsStr) ? [new Mon1str()] : $modelsStr]); }
/** * Редактировать пользователя * @param $id * @return array|string|Response * @throws ForbiddenHttpException * @throws NotFoundHttpException */ public function actionUpdate($id) { if (!Yii::$app->user->can('user-view')) { throw new ForbiddenHttpException(Yii::t('users.rbac', 'ACCESS_DENIED')); } $user = $this->findModel($id); $user->scenario = 'update'; $profile = new models\backend\Profile(['scenario' => 'create']); $person = new models\backend\LegalPerson(['scenario' => 'create']); $user->password = ''; // Сброс пароля if ($user->profile) { $profile = $user->profile; $profile->scenario = 'update'; } if ($user->person) { $person = $user->person; $person->scenario = 'update'; } // Разблокировать пользователя if (isset(Yii::$app->request->get()['rebanned'])) { if (Yii::$app->user->reBannedByUser($user->id)) { Yii::$app->session->setFlash('success', Yii::t('users', 'SUCCESS_UPDATE')); } else { Yii::$app->session->setFlash('danger', Yii::t('users', 'FAIL_UPDATE')); } return $this->redirect(['update', 'id' => $user->id]); } if (Yii::$app->request->isPost) { if (!Yii::$app->user->can('user-update')) { throw new ForbiddenHttpException(Yii::t('users.rbac', 'ACCESS_DENIED')); } $user->load(Yii::$app->request->post()); $profile->load(Yii::$app->request->post()); $person->load(Yii::$app->request->post()); if (!ActiveForm::validateMultiple([$user, $profile, $person])) { $user->populateRelation('profile', $profile); $user->populateRelation('person', $person); if ($user->save(false)) { Yii::$app->session->setFlash('success', Yii::t('users', 'SUCCESS_UPDATE')); } else { Yii::$app->session->setFlash('danger', Yii::t('users', 'FAIL_UPDATE')); } return $this->refresh(); } else { if (Yii::$app->request->isAjax) { Yii::$app->response->format = Response::FORMAT_JSON; return ActiveForm::validateMultiple([$user, $profile, $person]); } } } return $this->render('update', ['user' => $user, 'profile' => $profile, 'person' => $person]); }
/** * Performs validation on the provided model and $_POST data * * @param \infoweb\pages\models\Page $model The page model * @param array $post The $_POST data * @return array */ protected function validateModel($model, $post) { $languages = Yii::$app->params['languages']; // Populate the model with the POST data $model->load($post); // Create an array of translation models and populate them $translationModels = []; // Insert if ($model->isNewRecord) { foreach ($languages as $languageId => $languageName) { $translationModels[$languageId] = new Lang(['language' => $languageId]); } // Update } else { $translationModels = ArrayHelper::index($model->getTranslations()->all(), 'language'); } Model::loadMultiple($translationModels, $post); // Validate the model and translation $response = array_merge(ActiveForm::validate($model), ActiveForm::validateMultiple($translationModels)); // Return validation in JSON format Yii::$app->response->format = Response::FORMAT_JSON; return $response; }
public function actionUpdate($id) { $modelorder = $this->findModel($id); $modelsorders = $modelorder->table1s; if ($modelorder->load(Yii::$app->request->post())) { $oldIDs = ArrayHelper::map($modelsorders, 'id', 'id'); $modelsorders = Model::createMultiple(Table1::classname(), $modelsorders); Model::loadMultiple($modelsorders, Yii::$app->request->post()); $deletedIDs = array_diff($oldIDs, array_filter(ArrayHelper::map($modelsorders, 'id', 'id'))); // ajax validation if (Yii::$app->request->isAjax) { Yii::$app->response->format = Response::FORMAT_JSON; return ArrayHelper::merge(ActiveForm::validateMultiple($modelsorders), ActiveForm::validate($modelorder)); } // validate all models $valid = $modelorder->validate(); $valid = Model::validateMultiple($modelsorders) && $valid; if ($valid) { $transaction = \Yii::$app->db->beginTransaction(); try { if ($flag = $modelorder->save(false)) { if (!empty($deletedIDs)) { Table1::deleteAll(['id' => $deletedIDs]); } foreach ($modelsorders as $modelTable1) { $modelTable1->order_id = $modelorder->id; if (!($flag = $modelTable1->save(false))) { $transaction->rollBack(); break; } } } if ($flag) { $transaction->commit(); return $this->redirect(['update', 'id' => $modelorder->id]); } } catch (Exception $e) { $transaction->rollBack(); } } } return $this->render('update', ['modelorder' => $modelorder, 'modelsorders' => empty($modelsorders) ? [new Table1()] : $modelsorders]); }
/** * Updates a particular model. * If update is successful, the browser will be redirected to the 'index' page. * @param integer $id the ID of the model to be updated * @return string|\yii\web\Response * @throws \yii\db\Exception * @throws \yii\web\ForbiddenHttpException * @throws \yii\web\NotFoundHttpException */ public function actionUpdate($id = null) { if (!Yii::$app->user->can($id === null ? 'usr.create' : 'usr.update')) { throw new \yii\web\ForbiddenHttpException(Yii::t('yii', 'You are not authorized to perform this action.')); } /** @var ProfileForm $profileForm */ $profileForm = $this->module->createFormModel('ProfileForm', 'manage'); $profileForm->detachBehavior('captcha'); if ($id !== null) { $profileForm->setIdentity($identity = $this->loadModel($id)); $profileForm->setAttributes($identity->getIdentityAttributes()); } $loadedProfile = $profileForm->load($_POST); /** @var PasswordForm $passwordForm */ $passwordForm = $this->module->createFormModel('PasswordForm', 'register'); $loadedPassword = isset($_POST[$passwordForm->formName()]) && trim($_POST[$passwordForm->formName()]['newPassword']) !== '' && $passwordForm->load($_POST); if (Yii::$app->request->isAjax) { Yii::$app->response->format = \yii\web\Response::FORMAT_JSON; $models = []; if ($loadedProfile) { $models[] = $profileForm; } if ($loadedPassword) { //$models[] = $passwordForm; } return \yii\widgets\ActiveForm::validateMultiple($models); } /** * @todo Check for detailed auth items */ $canUpdateAttributes = Yii::$app->user->can('usr.update.attributes'); $canUpdatePassword = Yii::$app->user->can('usr.update.password'); $canUpdateAuth = Yii::$app->user->can('usr.update.auth'); $flashes = ['success' => [], 'error' => []]; if ($loadedProfile) { if ($profileForm->getIdentity() instanceof PictureIdentityInterface && !empty($profileForm->pictureUploadRules)) { $profileForm->picture = \yii\web\UploadedFile::getInstance($profileForm, 'picture'); } $updatePassword = $canUpdatePassword && $loadedPassword; if ($profileForm->validate() && (!$updatePassword || $passwordForm->validate())) { $trx = Yii::$app->db->beginTransaction(); $oldEmail = $profileForm->getIdentity()->getEmail(); if ($canUpdateAttributes && !$profileForm->save($this->module->requireVerifiedEmail) || $updatePassword && !$passwordForm->resetPassword($profileForm->getIdentity())) { $trx->rollback(); Yii::$app->session->setFlash('error', Yii::t('usr', 'Failed to register a new user.') . ' ' . Yii::t('usr', 'Try again or contact the site administrator.')); } else { if ($canUpdateAuth) { $this->updateAuthItems($id, $profileForm); } $trx->commit(); if ($this->module->requireVerifiedEmail && $oldEmail != $profileForm->getIdentity()->email) { if ($this->sendEmail($profileForm, 'verify')) { Yii::$app->session->setFlash('success', Yii::t('usr', 'An email containing further instructions has been sent to the provided email address.')); } else { Yii::$app->session->setFlash('error', Yii::t('usr', 'Failed to send an email.') . ' ' . Yii::t('usr', 'Try again or contact the site administrator.')); } } if (!Yii::$app->session->hasFlash('success')) { Yii::$app->session->setFlash('success', Yii::t('manager', 'User account has been successfully created or updated.')); } return $this->redirect(['index']); } } } return $this->render('update', ['id' => $id, 'profileForm' => $profileForm, 'passwordForm' => $passwordForm]); }
/** * Updates an existing Order model. * If update is successful, the browser will be redirected to the 'view' page. * @param integer $id * @return mixed */ public function actionUpdate($id) { $modelOrder = $this->findModel($id); $modelsItems = $this->getModelItems($modelOrder->orderId); $modelOrder->scenario = 'managerAdd'; //$modelsItems = $modelOrder->items; $customers_model = new Customers(); $customers_base = $arr_keys = $arr_vals = array(); $good_base = $customers_model->find()->where(['isWork' => 1])->orderBy('id')->asArray()->all(); foreach ($good_base as $key => $value) { array_push($arr_keys, $value["id"]); array_push($arr_vals, $value["customerName"]); } $customers_base = array_combine(array($arr_keys), array($arr_vals)); if ($modelOrder->load(Yii::$app->request->post())) { echo "== post request<br/>"; $oldIDs = ArrayHelper::map($modelsItems, 'id', 'orderId'); echo "== oldIDs are=<br/>"; print_r($oldIDs); $modelsItems = OrderDetail::createMultiple(OrderDetail::classname(), $modelsItems); Model::loadMultiple($modelsItems, Yii::$app->request->post()); echo "== deletedIDs are=<br/>"; print_r($deletedIDs); $deletedIDs = array_diff($oldIDs, array_filter(ArrayHelper::map($modelsItems, 'id', 'orderId'))); // ajax validation if (Yii::$app->request->isAjax) { Yii::$app->response->format = Response::FORMAT_JSON; return ArrayHelper::merge(ActiveForm::validateMultiple($modelsItems), ActiveForm::validate($modelOrder)); } // validate all models $valid = $modelOrder->validate(); $valid = print_r(Model::validateMultiple($modelsItems)) && $valid; echo "== valid is= " . $valid . "<br/>"; if ($valid) { $transaction = \Yii::$app->db->beginTransaction(); echo "==(trasaction) start<br/>"; try { if ($flag = $modelOrder->save(false)) { if (!empty($deletedIDs)) { echo "==(trasaction) delete oldIDs<br/>"; OrderDetail::deleteAll(['orderId' => $deletedIDs]); } echo "==(trasaction) modelItems post data are=<br/>"; foreach ($modelsItems as $modelItems) { echo "==(trasaction) save model item<br/>"; $modelItems->orderId = $modelOrder->orderId; if (!($flag = $modelItems->save(false))) { echo "======(trasaction) rollback<br/>"; $transaction->rollBack(); break; } } } if ($flag) { $transaction->commit(); echo "==(trasaction) all ok. start redirect<br/>"; return $this->redirect(['view', 'orderId' => $modelOrder->orderId]); } } catch (Exception $e) { echo "======(trasaction) rollback catch way<br/>"; $transaction->rollBack(); } } } return $this->render('update', ['modelOrder' => $modelOrder, 'modelsItems' => empty($modelsItems) ? [new OrderDetail()] : $modelsItems, 'customers_base' => $customers_base]); }
/** * Updates an existing Page model. * If update is successful, the browser will be redirected to the 'view' page. * @param integer $id * @param integer $langId * @return mixed */ public function actionUpdate($id) { $class = $this->modelClass; $models = $class::findAll(['id' => $id]); if (!$models) { throw new HttpException('404'); } if (\Yii::$app->request->isAjax && $class::loadMultiple($models, \Yii::$app->request->post())) { \Yii::$app->response->format = Response::FORMAT_JSON; return ActiveForm::validateMultiple($models); } if ($class::loadMultiple($models, $_POST) && $class::validateMultiple($models)) { foreach ($models as $model) { $model->save(); } $model->updateAliasOther(); return $this->redirect($this->generateRedirectParams($model, $this->redirectUpdate)); } $renderMethod = \Yii::$app->request->get('partial') ? 'renderPartial' : 'render'; $renderMethod = \Yii::$app->request->isAjax ? 'renderPartial' : $renderMethod; return $this->{$renderMethod}('update', ['models' => $models, 'model' => current($models)]); }
/** * Updates an existing Stockin model. * If update is successful, the browser will be redirected to the 'view' page. * @param integer $id * @return mixed */ public function actionUpdate($id) { $model = $this->findModel($id); $modelDetails = $model->stockinDetails; if ($model->load(Yii::$app->request->post())) { $oldIDs = ArrayHelper::map($modelDetails, 'id', 'id'); $modelDetails = Stockin::createMultiple(StockinDetail::classname(), $modelDetails); Stockin::loadMultiple($modelDetails, Yii::$app->request->post()); $deleteIDS = array_diff($oldIDs, array_filter(ArrayHelper::map($modelDetails, 'id', 'id'))); //ajax validation if (Yii::$app->request->isAjax) { Yii::$app->response->format = Response::FORMAT_JSON; return ArrayHelper::merge(ActiveForm::validateMultiple($modelDetails), ActiveForm::validate($model)); } // set the time if ($model->time) { date_default_timezone_set("Asia/ShangHai"); $model->time .= " " . date("H:i:s"); } //validate all models $valid = $model->validate(); $valid = Stockin::validateMultiple($modelDetails) && $valid; if ($valid) { $transcation = Yii::$app->db->beginTransaction(); try { if ($flag = $model->save(false)) { if (!empty($deleteIDS)) { StockinDetail::deleteAll(['id' => $deleteIDS]); } foreach ($modelDetails as $modelDetail) { $modelDetail->stockin_id = $model->id; if (!($flag = $modelDetail->save(false))) { $transcation->rollBack(); } } } if ($flag) { $transcation->commit(); return $this->redirect(['view', 'id' => $model->id]); } } catch (Exception $e) { $transcation->rollBack(); } } } return $this->render('update', ['model' => $model, 'modelDetails' => empty($modelDetails) ? [new StockinDetail()] : $modelDetails]); }
/** * @inheritDoc */ protected function runTabular($models) { return ActiveForm::validateMultiple($models); }
/** * Updates an existing Term model. * If update is successful, the browser will be redirected to the 'view' page. * @param integer $id * @return mixed */ public function actionUpdate($id) { $languages = Yii::$app->params['languages']; // Load the model with default values $model = $this->findModel($id); $returnOptions = ['model' => $model]; try { 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); // Create an array of translation models $translationModels = []; foreach ($languages as $languageId => $languageName) { $translationModels[$languageId] = $model->getTranslation($languageId); } // Populate the translation models Model::loadMultiple($translationModels, $post); // Validate the model and translation models $response = array_merge(ActiveForm::validate($model), ActiveForm::validateMultiple($translationModels)); // Return validation in JSON format Yii::$app->response->format = Response::FORMAT_JSON; return $response; // Normal request, save models } else { // Wrap the everything in a database transaction $transaction = Yii::$app->db->beginTransaction(); // Save the main model if (!$model->load($post) || !$model->save()) { return $this->render('update', $returnOptions); } // Save the translations foreach ($languages as $languageId => $languageName) { $data = $post['Lang'][$languageId]; // Set the translation language and attributes $model->language = $languageId; $model->name = $data['name']; $model->content = $data['content']; if (!$model->saveTranslation()) { return $this->render('update', $returnOptions); } } $transaction->commit(); // Switch back to the main language $model->language = Yii::$app->language; // Set flash message Yii::$app->getSession()->setFlash('term', Yii::t('app', '{item} has been updated', ['item' => $model->name])); // Take appropriate action based on the pushed button if (isset($post['close'])) { return $this->redirect(['index']); } elseif (isset($post['new'])) { return $this->redirect(['create']); } else { return $this->redirect(['update', 'id' => $model->id]); } } } } catch (Exception $e) { if (isset($transaction)) { $transaction->rollBack(); } // Set flash message Yii::$app->getSession()->setFlash('term-error', $e->getMessage()); } return $this->render('update', $returnOptions); }