Example #1
0
 public function upd()
 {
     session_start();
     new ValidationModel($_POST, 15, 90, 2, 255);
     $model = new Model();
     $model->update($_POST, $_GET['id']);
     header("Location: /PHP/Show/student/{$_GET['id']}");
 }
Example #2
0
 public function add()
 {
     session_start();
     new ValidationModel($_POST, 15, 90, 2, 255);
     $model = new Model();
     $model->addNew($_POST);
     $_SESSION['msg'] = 'student added';
     header("Location: student");
 }
Example #3
0
 /**
  * Save model or fail by showing errors.
  *
  * @param App\Models\Model $model
  * @return void
  */
 public function saveOrFail(Model $model)
 {
     if (!$model->save()) {
         $class = class_basename($model);
         $console = $this instanceof Seeder ? $this->command : $this;
         $errors = implode("\n- ", $model->getErrors()->all());
         $console->error("\n{$class} could not be seeded:");
         $console->line('- ' . $errors);
         $console->comment("\n{$class} attributes:");
         $console->line($model->toJson(JSON_PRETTY_PRINT));
         exit;
     }
 }
Example #4
0
 public function save(array $options = array())
 {
     if (!$this->sn) {
         $this->sn = $this->genOrderSN();
     }
     parent::save($options);
 }
Example #5
0
 public static function remove($id = null)
 {
     parent::remove($id);
     UsersProfilesModel::remove(array('user_id' => $id));
     UsersServicesModel::remove(array('user_id' => $id));
     UsersCredentialsModel::remove(array('user_id' => $id));
 }
Example #6
0
 protected static function boot()
 {
     parent::boot();
     static::deleting(function ($photo) {
         UploadFile::destroy($photo->file_id);
     });
 }
Example #7
0
 protected static function boot()
 {
     parent::boot();
     static::deleting(function ($file) {
         Storage::delete($file->getAttributeFromArray('file_path'));
     });
 }
Example #8
0
 /**
  * Required in every model. Please do not edit!
  *
  * @param array $params
  */
 public function __construct($params = array())
 {
     if ($params) {
         parent::__construct($params);
     } elseif (isset($this->settings)) {
         unset($this->settings);
     }
 }
Example #9
0
 public function save($options = [])
 {
     if ($this->isDirty()) {
         $changed = $this->getDirty();
         if ($changed['password']) {
             $this->password = \Hash::make($changed['password']);
         }
     }
     parent::save($options);
 }
Example #10
0
 public function edit()
 {
     $model = Model::find($this->request->id);
     if (!$model) {
         $this->redirect('Models::index');
     }
     if ($this->request->data && $model->save($this->request->data)) {
         $this->redirect(array('Models::view', 'args' => array($model->id)));
     }
     return compact('model');
 }
 public function __construct(UserTableModel $userTableModel, $id = NULL)
 {
     parent::__construct();
     if (is_null($this->userTableModel)) {
         $this->userTableModel = $userTableModel;
     }
     if (!is_null($id)) {
         $this->id = $id;
         $this->userTableModel->setId($id);
     }
 }
Example #12
0
 public static function login(array $data)
 {
     $admini = Admini::findOne(['username' => $data['username']]);
     if (!$admini) {
         return ['username', '账号不存在'];
     }
     if (!parent::equalPassword($data['password'], $admini->password)) {
         return ['password', '密码不正确'];
     }
     return $admini;
 }
 /**
  * handle event
  *
  * @param string $event
  *
  * @return bool
  */
 protected function handleEvent($event)
 {
     if ($event == self::EVENT_CREATING) {
         $this->setAttribute('salt', $this->_makeSalt());
         $this->setAttribute('password', $this->_encryptPassword());
     } elseif ($event == self::EVENT_UPDATING) {
         if ($this->isDirty(['password'])) {
             $this->setAttribute('password', $this->_encryptPassword());
         }
     }
     return parent::handleEvent($event);
 }
Example #14
0
 protected static function boot()
 {
     parent::boot();
     // static::updating(function ($product) {
     //     $changed = $product->isDirty() ? $product->getDirty() : false;
     //     if ($changed && $changed['options']) {
     //         // maintain stock
     //         print_r($changed['options']);
     //     }
     // });
     static::deleting(function ($product) {
         $ids = ProductPhoto::select()->where('product_id', '=', $product->id)->lists('id');
         ProductPhoto::destroy($ids->toArray());
     });
 }
Example #15
0
 public function student()
 {
     $model = new Model();
     return new Response('ShowView.html.twig', array('info' => $model->showOne($_GET['id'])));
 }
Example #16
0
 /**
  * Updates an existing Cals 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);
     $modelsCalitems = $model->calitem;
     if ($model->load(Yii::$app->request->post()) && $model->save()) {
         $oldIDs = ArrayHelper::map($modelsCalitems, 'id', 'id');
         $modelsCalitems = Model::createMultiple(Calitems::classname(), $modelsCalitems);
         Model::loadMultiple($modelsCalitems, Yii::$app->request->post());
         $deletedIDs = array_diff($oldIDs, array_filter(ArrayHelper::map($modelsCalitems, 'id', 'id')));
         $valid = $model->validate();
         $valid = Model::validateMultiple($modelsCalitems) && $valid;
         if ($valid) {
             $transaction = \Yii::$app->db->beginTransaction();
             try {
                 if ($flag = $model->save(false)) {
                     if (!empty($deletedIDs)) {
                         Calitems::deleteAll(['id' => $deletedIDs]);
                     }
                     foreach ($modelsCalitems as $modelCalitems) {
                         $modelCalitems->cal_id = $model->id;
                         if (!($flag = $modelCalitems->save(false))) {
                             $transaction->rollBack();
                             break;
                         }
                     }
                 }
                 if ($flag) {
                     $transaction->commit();
                     return $this->redirect(['view', 'id' => $model->id]);
                 }
             } catch (Exception $e) {
                 $transaction->rollBack();
             }
         }
     } else {
         return $this->render('update', ['model' => $model, 'modelsCalitems' => empty($modelsCalitems) ? [new Calitems()] : $modelsCalitems]);
     }
 }
 /**
  * Updates an existing Tour 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);
     $modelsCustomField = $model->customFields;
     if ($model->load(Yii::$app->request->post())) {
         $oldIDs = ArrayHelper::map($modelsCustomField, 'id', 'id');
         $modelsCustomField = Model::createMultiple(CustomField::classname(), $modelsCustomField);
         Model::loadMultiple($modelsCustomField, Yii::$app->request->post());
         $deletedIDs = array_diff($oldIDs, array_filter(ArrayHelper::map($modelsCustomField, 'id', 'id')));
         // ajax validation
         if (Yii::$app->request->isAjax) {
             Yii::$app->response->format = Response::FORMAT_JSON;
             return ArrayHelper::merge(ActiveForm::validateMultiple($modelsCustomField), ActiveForm::validate($model));
         }
         // validate all models
         $valid = $model->validate();
         $valid = Model::validateMultiple($modelsCustomField) && $valid;
         if ($valid) {
             $transaction = \Yii::$app->db->beginTransaction();
             try {
                 if ($flag = $model->save(false)) {
                     if (!empty($deletedIDs)) {
                         CustomField::deleteAll(['id' => $deletedIDs]);
                     }
                     foreach ($modelsCustomField as $modelCustomField) {
                         $modelCustomField->tour_id = $model->id;
                         if (!($flag = $modelCustomField->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, 'modelsCustomField' => empty($modelsCustomField) ? [new CustomField()] : $modelsCustomField]);
 }
Example #18
0
 public function index()
 {
     $model = new Model();
     return new Response("HomeView.html.twig", array('data' => $model->showAll()));
 }
Example #19
0
 /**
  * {@inheritdoc}
  */
 public function __construct(array $attributes = [])
 {
     parent::__construct($attributes);
     // Initialize listify with the scope of the current step guide.
     $this->initListify(['scope' => $this->guide()]);
 }
Example #20
0
 public function __construct()
 {
     parent::__construct();
 }
Example #21
0
 public function update(Model $model)
 {
     $this->checkStatus();
     $table = $model->getTable();
     $model = (object) array_filter((array) $model);
     $model->update = array_filter((array) $model->update);
     foreach ($model as $key => $value) {
         if ($key !== "table" && $key !== "Adapter" && $key !== "update" && $key !== "created_at") {
             $values[$key . "='" . $value . "'"] = null;
         }
     }
     if (count($model->update) > 0) {
         foreach ($model->update as $key => $value) {
             $update[$key . "='" . $value . "'"] = $value;
         }
     } else {
         return false;
     }
     $query = " UPDATE `{$table}` SET " . implode(",", array_keys($update)) . " WHERE ";
     $query .= " " . implode(" AND ", array_keys($values)) . " ";
     return $this->db->query($query);
 }
Example #22
0
 private function notHas($uid, $app, $feature)
 {
     $app = App::find()->select(['id', 'name'])->where(['code' => $app])->asArray()->one();
     $role = RoleUser::find()->select(['rid', 'rname'])->where(['uid' => $uid])->asArray()->all();
     $roleid = array();
     foreach ($role as $vr) {
         $roleid[] = $vr['rid'];
     }
     $roleid = implode(',', $roleid);
     $scopes = Rule::find()->select(['model_id', 'scope_id'])->where(['aid' => $app['id']])->andWhere(['feature_code' => $feature])->andWhere("role_id not in({$roleid})")->asArray()->all();
     $feature = Feature::find()->select(['name'])->where(['code' => $feature])->asArray()->one();
     // delete repeat data
     $unique = array();
     foreach ($scopes as $k => $vs) {
         $unique[$k] = $vs['model_id'] . ',' . $vs['scope_id'];
     }
     $scope = array_unique($unique);
     $result = array();
     foreach ($scope as $k => $v) {
         $result[] = $scopes[$k];
     }
     $final = array();
     foreach ($result as $k => $vu) {
         $model = Model::find()->select(['name'])->where(['id' => $vu['model_id']])->asArray()->one();
         $scope = Scope::find()->select(['name', 'attribute'])->where(['id' => $vu['scope_id']])->asArray()->one();
         $final[$k]['model'] = $model['name'];
         $final[$k]['feature'] = $feature['name'];
         $final[$k]['scope'] = $scope['name'];
         $final[$k]['scope_attribute'] = $scope['attribute'];
     }
     return $final;
 }
 /**
  * Updates an existing RceExamen 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);
     $modelsPago = $model->pagos;
     $modelsBitacora = $model->bitacoras;
     $modelsExamenes = $model->rceExamenExamens;
     foreach ($modelsExamenes as $modelExamen) {
         $examen = Examen::find()->where(['id' => $modelExamen->examen_id])->one();
         $modelExamen->descripcion = $examen->descripcion;
         $modelExamen->observaciones = $examen->observaciones;
     }
     if ($model->load(Yii::$app->request->post())) {
         $oldIDsPago = ArrayHelper::map($modelsPago, 'id', 'id');
         $modelsPago = Model::createMultiple(Pago::classname(), $modelsPago);
         Model::loadMultiple($modelsPago, Yii::$app->request->post());
         $deletedIDsPago = array_diff($oldIDsPago, array_filter(ArrayHelper::map($modelsPago, 'id', 'id')));
         $oldIDsExamen = ArrayHelper::map($modelsExamenes, 'id', 'id');
         $modelsExamenes = Model::createMultiple(Examen::classname(), $modelsExamenes);
         Model::loadMultiple($modelsExamenes, Yii::$app->request->post());
         $deletedIDsExamen = array_diff($oldIDsExamen, array_filter(ArrayHelper::map($modelsExamenes, 'id', 'id')));
         // validate all models
         $valid = $model->validate();
         $valid = Model::validateMultiple($modelsPago) && $valid;
         $valid = Model::validateMultiple($modelsBitacora) && $valid;
         $valid = Model::validateMultiple($modelsExamenes) && $valid;
         if ($valid) {
             $transaction = \Yii::$app->db->beginTransaction();
             try {
                 if ($flag = $model->save(false)) {
                     if (!empty($deletedIDsPago)) {
                         Pago::deleteAll(['id' => $deletedIDsPago]);
                     } else {
                         if (!empty($deletedIDsBitacora)) {
                             Bitacora::deleteAll(['id' => $deletedIDsBitacora]);
                         } else {
                             if (!empty($deletedIDsREE)) {
                                 RceExamenExamen::deleteAll(['id' => $deletedIDsREE]);
                             }
                         }
                     }
                     foreach ($modelsPago as $modelPago) {
                         $modelPago->rce_examen_id = $model->id;
                         if (!($flag = $modelPago->save(false))) {
                             $transaction->rollBack();
                             break;
                         }
                     }
                     foreach ($modelsBitacora as $modelBitacora) {
                         $modelBitacora->rce_examen_id = $model->id;
                         if (!($flag = $modelBitacora->save(false))) {
                             $transaction->rollBack();
                             break;
                         }
                     }
                     $reserva = Reserva::find()->where(['id' => $model->reserva_id])->one();
                     $hora = Hora::find()->where(['id' => $reserva->hora_medica_id])->one();
                     $examenes = HoraExamenSolicitado::find()->where(['hora_id' => $hora->id])->all();
                     for ($i = 0; $i < count($examenes); ++$i) {
                         $examen = Examen::find()->where(['id' => $examenes[$i]->examen_id])->one();
                         $modelsExamenes[$i] = new RceExamenExamen();
                         $modelsExamenes[$i]->rce_examen_id = $model->id;
                         $modelsExamenes[$i]->examen_id = $examenes[$i]->examen_id;
                         $modelsExamenes[$i]->monto_a_pagar = $examen->monto;
                         if (!($flag = $modelsExamenes[$i]->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, 'modelsPago' => empty($modelsPago) ? [new Pago()] : $modelsPago, 'modelsBitacora' => empty($modelsBitacora) ? [new Bitacora()] : $modelsBitacora, 'modelsExamenes' => empty($modelsExamenes) ? [new RceExamenExamen()] : $modelsExamenes]);
 }
Example #24
0
 function __construct()
 {
     parent::__construct();
     $this->setData(['sideBarData' => IndexWidgets::sideBarMenuWidget(), 'footerData' => IndexWidgets::footerWidget()]);
     Helper::redirectChecker();
 }
Example #25
0
 public function actionUpdateD($id)
 {
     $modelTransaksi = $this->findModel($id);
     $modelsTransaksiItem = $modelTransaksi->addresses;
     if ($modelTransaksi->load(Yii::$app->request->post())) {
         $oldIDs = ArrayHelper::map($modelsTransaksiItem, 'id', 'id');
         $modelsTransaksiItem = Model::createMultiple(TransaksiItem::classname(), $modelsTransaksiItem);
         Model::loadMultiple($modelsTransaksiItem, Yii::$app->request->post());
         $deletedIDs = array_diff($oldIDs, array_filter(ArrayHelper::map($modelsTransaksiItem, 'id', 'id')));
         // ajax validation
         if (Yii::$app->request->isAjax) {
             Yii::$app->response->format = Response::FORMAT_JSON;
             return ArrayHelper::merge(ActiveForm::validateMultiple($modelsTransaksiItem), ActiveForm::validate($modelTransaksi));
         }
         // validate all models
         $valid = $modelTransaksi->validate();
         $valid = Model::validateMultiple($modelsTransaksiItem) && $valid;
         if ($valid) {
             $transaction = \Yii::$app->db->beginTransaction();
             try {
                 if ($flag = $modelTransaksi->save(false)) {
                     if (!empty($deletedIDs)) {
                         TransaksiItem::deleteAll(['id' => $deletedIDs]);
                     }
                     foreach ($modelsTransaksiItem as $modelAddress) {
                         $modelAddress->customer_id = $modelTransaksi->id;
                         if (!($flag = $modelAddress->save(false))) {
                             $transaction->rollBack();
                             break;
                         }
                     }
                 }
                 if ($flag) {
                     $transaction->commit();
                     return $this->redirect(['view', 'id' => $modelTransaksi->id]);
                 }
             } catch (Exception $e) {
                 $transaction->rollBack();
             }
         }
     }
     return $this->render('_formD', ['modelTransaksi' => $modelTransaksi, 'modelsTransaksiItem' => empty($modelsTransaksiItem) ? [new Address()] : $modelsTransaksiItem]);
 }
 /**
  * Creates a new Curriculos model.
  * If creation is successful, the browser will be redirected to the 'view' page.
  * @return mixed
  */
 public function actionCreate()
 {
     $this->layout = 'main-curriculos';
     $model = new Curriculos();
     $curriculosEndereco = new CurriculosEndereco();
     $curriculosFormacao = new CurriculosFormacao();
     $modelsComplemento = [new CurriculosComplemento()];
     $modelsEmpregos = [new CurriculosEmpregos()];
     if (isset($_COOKIE['PHPSESSID']) && !empty($_COOKIE['PHPSESSID'])) {
         session_id($_COOKIE['PHPSESSID']);
     }
     session_start();
     //session numero de edital e do id do processo
     $session = Yii::$app->session;
     $model->edital = $session["numeroEdital"];
     $id = $session["id"];
     $model->data = date('Y-m-d H:i:s');
     //NÚMERO DE INSCRIÇÃO 'ANO CORRENTE + 000000 + ID DO CANDIDATO'
     $query_id = "SELECT max(id) as id FROM curriculos LIMIT 1";
     $last_id = Curriculos::findBySql($query_id)->all();
     foreach ($last_id as $value) {
         $incremento = $value['id'];
         $incremento++;
     }
     $model->numeroInscricao = date('Y') . '00000' . $incremento;
     $curriculosEndereco->curriculos_id = $incremento;
     $curriculosFormacao->curriculos_id = $incremento;
     //localizando somente os cargos que fazem parte do edital selecionado
     $cargos = Cargos::find()->innerJoinWith('cargosProcessos')->where(['processo_id' => $id])->AndWhere('cargo_id = idcargo')->all();
     //Caso não tenha puxado nenhum edital, será redirecionado para a página de processo seletivo
     if ($model->edital == NULL) {
         return $this->redirect('http://www.am.senac.br/trabsenac.php');
     }
     if ($model->load(Yii::$app->request->post()) && $curriculosEndereco->load(Yii::$app->request->post()) && $curriculosFormacao->load(Yii::$app->request->post()) && Model::validateMultiple([$model, $curriculosEndereco, $curriculosFormacao])) {
         //Calcular a idade do candidato
         $datetime1 = new \DateTime($model->datanascimento, new \DateTimeZone('UTC'));
         $datetime2 = new \DateTime();
         $diff = $datetime1->diff($datetime2);
         $model->idade = $diff->y;
         $model->save(false);
         // skip validation as model is already validated
         $curriculosEndereco->curriculos_id = $model->id;
         $curriculosFormacao->curriculos_id = $model->id;
         $curriculosEndereco->save(false);
         $curriculosFormacao->save(false);
         //ENVIA E-MAIL DA INSCRIÇÃO PARA O CANDIDATO
         Yii::$app->mailer->compose()->setFrom(['*****@*****.**' => 'Processo Seletivo - Senac AM'])->setTo($model->email)->setSubject('Inscrição para o Edital: ' . $model->edital)->setTextBody('Prezado Candidato, confirmamos o envio de seu currículo para concorrer a vaga de ' . $model->cargo . ' para o Edital ' . $model->edital . ' ')->setHtmlBody("Prezado Senhor(a), <strong>" . $model->nome . "</strong><br><br>" . "Recebemos a sua inscrição em nosso processo de seleção com sucesso para o Edital: <strong>" . $model->edital . " </strong>e pedimos que acompanhe em nosso site o resultado das próximas etapas.<br><br>" . "<strong><font color='red'><center>NÃO RESPONDA A ESSE E-MAIL!!!!</center></font></strong><br><br>" . "<strong>INFORMAÇÕES GERAIS</STRONG><br><br>" . "<strong>Número de Inscrição: </strong><font color='red'>" . $model->numeroInscricao . "</font><br><br>" . "<strong>Data do envio: </strong> " . $model->data . "<br>" . "<strong>Processo Seletivo: </strong> " . $model->edital . "<br>" . "<strong>Cargo: </strong> " . $model->cargo . "<br><br>")->send();
         //Inserir vários cursos complementares
         $modelsComplemento = Model::createMultiple(CurriculosComplemento::classname());
         Model::loadMultiple($modelsComplemento, Yii::$app->request->post());
         //Inserir vários emprgos anteriores
         $modelsEmpregos = Model::createMultiple(CurriculosEmpregos::classname());
         Model::loadMultiple($modelsEmpregos, Yii::$app->request->post());
         // validate all models
         $valid = $model->validate();
         $valid = Model::validateMultiple($modelsComplemento) && $valid;
         $valid2 = $model->validate();
         $valid_empregos = Model::validateMultiple($modelsEmpregos) && $valid2;
         if ($valid && $valid_empregos) {
             $transaction = \Yii::$app->db->beginTransaction();
             try {
                 if ($flag = $model->save(false)) {
                     foreach ($modelsComplemento as $modelComplemento) {
                         //cursos complementares
                         $modelComplemento->curriculos_id = $model->id;
                         if (!($flag = $modelComplemento->save(false))) {
                             $transaction->rollBack();
                             break;
                         }
                     }
                     foreach ($modelsEmpregos as $modelEmpregos) {
                         //empregos anteriores
                         $modelEmpregos->curriculos_id = $model->id;
                         if (!($flag = $modelEmpregos->save(false))) {
                             $transaction->rollBack();
                             break;
                         }
                     }
                 }
                 if ($flag) {
                     $transaction->commit();
                     return $this->redirect('http://www.am.senac.br/trabsenac_success.php');
                 }
             } catch (Exception $e) {
                 $transaction->rollBack();
             }
         }
         return $this->redirect('http://www.am.senac.br/trabsenac_success.php');
     } else {
         return $this->render('create', ['model' => $model, 'cargos' => $cargos, 'curriculosEndereco' => $curriculosEndereco, 'curriculosFormacao' => $curriculosFormacao, 'modelsComplemento' => empty($modelsComplemento) ? [new CurriculosComplemento()] : $modelsComplemento, 'modelsEmpregos' => empty($modelsEmpregos) ? [new CurriculosEmpregos()] : $modelsEmpregos]);
     }
 }
Example #27
0
 public function __construct()
 {
     parent::__construct();
     $this->song = new Song();
 }
Example #28
0
 public function getModel()
 {
     return $this->hasOne(Model::className(), ['id' => 'model_id'])->asArray();
 }
Example #29
0
 private function notHas($uid, $app)
 {
     $app = App::find()->where(['code' => $app])->asArray()->one();
     $role = RoleUser::find()->where(['uid' => $uid])->asArray()->all();
     $roleid = array();
     foreach ($role as $vr) {
         $roleid[] = $vr['rid'];
     }
     $roleid = implode(',', $roleid);
     $rule = Rule::find()->select(['aid', 'role_id', 'model_id', 'feature_id', 'scope_id'])->where("role_id not in({$roleid})")->andWhere(['aid' => $app['id']])->asArray()->all();
     $result = array();
     $unique = array();
     foreach ($rule as $k => $vu) {
         $apps = App::find()->select(['name'])->where(['id' => $vu['aid']])->asArray()->one();
         $result[$k]['app'] = $apps['name'];
         $roles = Role::find()->select(['name'])->where(['id' => $vu['role_id']])->asArray()->one();
         $result[$k]['role'] = $roles['name'];
         $model = Model::find()->select(['name'])->where(['id' => $vu['model_id']])->asArray()->one();
         $result[$k]['model'] = $model['name'];
         $feature = Feature::find()->select(['name'])->where(['id' => $vu['feature_id']])->asArray()->one();
         $result[$k]['feature'] = $feature['name'];
         $scopes = Rule::find()->select(['scope_id'])->where(['aid' => $vu['aid'], 'role_id' => $vu['role_id'], 'model_id' => $vu['model_id'], 'feature_id' => $vu['feature_id']])->asArray()->all();
         foreach ($scopes as $ks => $vs) {
             $scope = Scope::find()->select(['name', 'attribute'])->where(['id' => $vs['scope_id']])->asArray()->one();
             $result[$k]['scope'][$ks]['name'] = $scope['name'];
             $result[$k]['scope'][$ks]['attribute'] = $scope['attribute'];
         }
         $unique[$k] = $vu['aid'] . $vu['role_id'] . $model['name'] . $feature['name'];
     }
     // delete the repeat elements
     $unique = array_unique($unique);
     $res = array();
     foreach ($unique as $kq => $vq) {
         $res[] = $result[$kq];
     }
     return $res;
 }
Example #30
0
 /**
  * Updates an existing Purchase 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->getPurchasesDetails()->all();
     if ($model->load(Yii::$app->request->post())) {
         $oldModelDetails = array();
         foreach ($modelDetails as $modelDetail) {
             $oldModelDetails[$modelDetail->id] = ['item_id' => $modelDetail->item_id, 'quantity' => $modelDetail->quantity];
         }
         $oldIDs = ArrayHelper::map($modelDetails, 'id', 'id');
         $modelDetails = Model::createMultiple(PurchaseDetail::classname(), $modelDetails);
         Model::loadMultiple($modelDetails, Yii::$app->request->post());
         $deletedIDs = array_diff($oldIDs, array_filter(ArrayHelper::map($modelDetails, 'id', 'id')));
         // validate all models
         $valid = $model->validate() & Model::validateMultiple($modelDetails);
         if ($valid) {
             $transaction = \Yii::$app->db->beginTransaction();
             try {
                 if ($flag = $model->save(false)) {
                     if (!empty($deletedIDs)) {
                         $flag = PurchaseDetail::deleteAll(['id' => $deletedIDs]) > 0;
                         if ($flag) {
                             foreach ($deletedIDs as $id) {
                                 $item = Item::findOne($oldModelDetails[$id]['item_id']);
                                 $item->stock -= $oldModelDetails[$id]['quantity'];
                                 if (!($flag = $item->save())) {
                                     $transaction->rollBack();
                                     break;
                                 }
                             }
                         } else {
                             $transaction->rollBack();
                         }
                     }
                     if ($flag) {
                         foreach ($modelDetails as $modelDetail) {
                             $quantity = $modelDetail->quantity;
                             if (!empty($modelDetail->id) && $modelDetail->item_id == $oldModelDetails[$modelDetail->id]['item_id']) {
                                 $quantity -= $oldModelDetails[$modelDetail->id]['quantity'];
                             }
                             $modelDetail->purchase_id = $model->id;
                             if (($flag = $modelDetail->save(false)) && $quantity !== 0) {
                                 $item = Item::findOne($modelDetail->item_id);
                                 $item->stock += $quantity;
                                 $flag = $item->save();
                             }
                             if (!$flag) {
                                 $transaction->rollBack();
                                 break;
                             }
                         }
                     }
                 }
                 if ($flag) {
                     $transaction->commit();
                     return $this->redirect(['index']);
                 }
             } catch (Exception $e) {
                 $transaction->rollBack();
             }
         }
     }
     return $this->render('update', ['model' => $model, 'modelDetails' => empty($modelDetails) ? [new PurchaseDetail()] : $modelDetails]);
 }