Example #1
0
 /**
  * Updates an existing Product 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);
     $modelCategory = new Category();
     $categoriesArray = ArrayHelper::map(Category::find()->all(), 'id', 'name');
     $modelLinkProduct = LinkProduct::find()->where(['id_product' => $id])->orderBy('id_category')->all();
     $subCategoriesArray = SubCategory::find()->all();
     if ($model->load(Yii::$app->request->post()) && $model->save()) {
         LinkProduct::deleteAll(['id_product' => $id]);
         foreach (Yii::$app->request->post()['category'] as $key => $id) {
             //var_dump($id.'---');
             if (Yii::$app->request->post()['subCategory' . $id]) {
                 foreach (Yii::$app->request->post()['subCategory' . $id] as $keySub => $idSub) {
                     //$linkProductArray = array($model->id,$id,$idSub);
                     $modelLinkProduct = new LinkProduct();
                     //var_dump($keySub.$idSub );echo "<br>";
                     $modelLinkProduct->id_product = $model->id;
                     $modelLinkProduct->id_category = $id;
                     $modelLinkProduct->id_sub_category = $idSub;
                     $modelLinkProduct->save();
                 }
             } else {
                 $modelLinkProduct = new LinkProduct();
                 //var_dump($keySub.$idSub );echo "<br>";
                 $modelLinkProduct->id_product = $model->id;
                 $modelLinkProduct->id_category = $id;
                 $modelLinkProduct->id_sub_category = 0;
                 $modelLinkProduct->save();
             }
         }
         return $this->redirect(['view', 'id' => $model->id]);
     } else {
         $modelLinkProduct = LinkProduct::find()->where(['id_product' => $id])->orderBy('id_category')->all();
         //            var_dump(ArrayHelper::map($modelLinkProduct,'id','id_product'));die();
         return $this->render('update', ['model' => $model, 'categoriesArray' => $categoriesArray, 'subCategoriesArray' => $subCategoriesArray, 'modelLinkProductCategory' => ArrayHelper::map($modelLinkProduct, 'id', 'id_category'), 'modelLinkProductSubCategory' => ArrayHelper::map($modelLinkProduct, 'id', 'id_sub_category')]);
     }
 }