コード例 #1
0
ファイル: OfferController.php プロジェクト: kot-ezhva/ygin
 public function actionIndex()
 {
     $offer = BaseActiveRecord::newModel('Offer');
     $offerModelClass = get_class($offer);
     $products = array();
     $transaction = null;
     // собираем данные, пришедшие от клиента
     if (isset($_POST[$offerModelClass])) {
         $offer->attributes = $_POST[$offerModelClass];
         //если данные пришли не аяксом, то стартуем транзакцию
         if (!isset($_POST['ajax'])) {
             Yii::app()->db->setAutoCommit(false);
             $transaction = Yii::app()->db->beginTransaction();
         }
         $products = $this->getProducts();
     }
     // валидация формы ajax
     if (isset($_POST['ajax']) && $_POST['ajax'] === 'offerForm') {
         $validateResult = CActiveForm::validate($offer, null, false);
         //Если валидация формы заказа прошла успешно, то валидируем выбранные товары
         if ($validateResult == '[]') {
             echo CActiveForm::validateTabular($products, null, false);
         } else {
             echo $validateResult;
         }
         Yii::app()->end();
     }
     // сохраняем
     if (isset($_POST[$offerModelClass])) {
         $valid = true;
         foreach ($products as $product) {
             $valid = $product->validate() && $valid;
             if (!$valid) {
                 break;
             }
         }
         if (count($products) == 0) {
             $valid = false;
             $offer->addError('offer_text', 'Для оформления заявки необходимо выбрать хотя бы один товар.');
         }
         if ($valid && $offer->validate()) {
             // Формируем текст заявки:
             foreach ($products as $product) {
                 $offerProduct = BaseActiveRecord::newModel('OfferProduct');
                 //Модель-связь многие-ко-многим м/у заказом и товарами
                 $offerProduct->id_product = $product->id_product;
                 $offerProduct->amount = $product->countInCart;
                 $offer->amount += $product->countInCart * $product->retail_price;
                 $offer->addRelatedRecord('offerProducts', $offerProduct, true);
             }
             $offer->offer_text = $this->renderPartial('/offerText', array('products' => $products), true);
             $offer->onAfterSave = array($this, 'sendMessage');
             $offer->save();
             if ($transaction != null) {
                 $transaction->commit();
             }
             if (Yii::app()->daShop->useOnlinePayment) {
                 $this->pay($offer);
             }
             Yii::app()->user->setFlash('offer-success', 'Спасибо, Ваш заказ успешно отправлен.');
             ShopModule::clearProductsFromCookie();
             $this->redirect(Yii::app()->createUrl(ShopModule::ROUTE_MAIN));
         } else {
             // вообще сюда попадать в штатных ситуациях не должны
             // только если кул хацкер резвится
             Yii::app()->user->setFlash('offer-message', CHtml::errorSummary($offer, '<p>Не удалось отправить заявку</p>'));
         }
     } else {
         $products = ShopModule::getProductsFromCookie();
     }
     $this->render('/offer', array('products' => $products, 'offer' => $offer, 'showPrice' => Yii::app()->getModule('shop')->showPrice));
 }
コード例 #2
0
ファイル: DesignController.php プロジェクト: schrapps/risksur
 /**
  * actionAddMultipleComponents
  * @access public
  * @return void
  */
 public function actionAddMultipleComponents()
 {
     Yii::log("actionAddMultipleComponents DesignController called", "trace", self::LOG_CAT);
     $component = new ComponentHead();
     $componentDetails = new ComponentDetails();
     //$currentDesignId = Yii::app()->session['surDesign']['id']; // Current selected design
     $settings = Yii::app()->tsettings;
     $risksurSettings = $settings->getSettings();
     $multipleRowsToShow = $risksurSettings->multipleComponentsRows;
     //$errorMessage = "";
     $errorStatus = "";
     $dataArray = [];
     $dataArray['formType'] = 'Create';
     $attributeArray = [];
     if (!empty(Yii::app()->session['surDesign'])) {
         $returnArray = self::getElementsAndDynamicAttributes([], true);
         //var_dump($returnArray); die;
         $elements = $returnArray['elements'];
         $model = new DesignForm();
         $model->setProperties($returnArray['dynamicDataAttributes']);
         $model->setAttributeLabels($returnArray['dynamicLabels']);
         $model->setRules($returnArray['dynamicRules']);
         // generate the components form
         $form = new CForm($elements, $model);
         $formHeader = new CForm($elements, $model);
         // ajax request to add a new row
         if ($form->submitted('newComponent')) {
             $modelArray = [];
             foreach (range(0, count($_POST['DesignForm']) - 1) as $index) {
                 $modelArray[$index] = $model;
             }
             //print_r($form->model); die;
             $modelErrors = CJSON::decode(CActiveForm::validateTabular($modelArray));
             $valid = true;
             if (!empty($modelErrors)) {
                 $valid = false;
                 $errorArray = [];
                 foreach ($modelErrors as $errorKey => $error) {
                     //print_r($error); die;
                     $keyArray = explode('_', $errorKey);
                     $errorArray[$keyArray[2]] = 'Row ' . $keyArray[1] . ' ' . $error[0];
                 }
                 $model->addErrors($errorArray);
                 //die;
             }
             //				print_r($_POST['DesignForm']);
             //				print_r($valid); die;
             //$items=$this->getItemsToUpdate();
             if ($valid) {
                 foreach ($_POST['DesignForm'] as $i => $row) {
                     $model->setAttributes($row);
                     //$_POST['ComponentsForm'][$i];
                     //						$valid = $model->validate() && $valid;
                     //add the models with attributes to the model array
                     $postedModelArray[] = $model;
                     $component->setIsNewRecord(true);
                     $component->componentId = null;
                     $component->componentName = $val = $model->componentName;
                     $component->frameworkId = Yii::app()->session['surDesign']['id'];
                     //save the componentHead values
                     //var_dump($data); die;
                     $component->save();
                     $componentId = $component->componentId;
                     // fetch the form data
                     foreach ($model->getAttributes() as $key => $val) {
                         //ignore the attribute arrays
                         if (!is_array($key) && !is_array($val)) {
                             if ($key != "componentName") {
                                 $componentDetails->setIsNewRecord(true);
                                 $componentDetails->componentDetailId = null;
                                 $componentDetails->componentId = $componentId;
                                 $params = explode("_", $key);
                                 $componentDetails->subFormId = $params[1];
                                 $componentDetails->value = $val;
                                 $componentDetails->save();
                             }
                         }
                     }
                 }
                 //	die;
                 Yii::app()->user->setFlash('success', Yii::t("translation", "Components successfully created"));
                 $this->redirect(['listComponents']);
             }
         }
         // check if there was a post and the muliple forms are invalid
         $modelArray = [];
         for ($i = 0; $i < $multipleRowsToShow; $i++) {
             // number of model records to show by default on the view
             $modelArray[] = $model;
         }
         if (isset($postedModelArray[0])) {
             $modelArray = $postedModelArray;
         }
         if (Yii::app()->request->isAjaxRequest && isset($_GET['index'])) {
             $this->renderPartial('_tabularInputAsTable', ['errorStatus' => $errorStatus, 'elements' => $elements, 'dataArray' => $dataArray, 'model' => $model, 'form' => $form, 'index' => $_GET['index']]);
             return;
         }
         //var_dump($formHeader->getElements()); die;
         $this->render('multipleComponent', ['errorStatus' => $errorStatus, 'elements' => $elements, 'dataArray' => $dataArray, 'modelArray' => $modelArray, 'form' => $form, 'formHeader' => $formHeader]);
         return;
     }
     Yii::app()->user->setFlash('notice', Yii::t("translation", "Please select a surveillance system first"));
     $this->redirect('listComponents');
     return;
 }