コード例 #1
0
 public function actionView($id)
 {
     if ($id <= 0) {
         $this->goHome();
     }
     $allCategory = Category::find()->asArray()->all();
     $arrayCategoryIdName = ArrayHelper::map($allCategory, 'id', 'name');
     $arrSubCat = Category::getArraySubCatalogId($id, $allCategory);
     /****** 价格筛选 ****/
     $result = (new Query())->select('min(price) as min, max(price) as max')->from('product')->where(['category_id' => $arrSubCat, 'status' => Status::STATUS_ACTIVE])->one();
     $min = $result['min'];
     $max = $result['max'];
     if ($max > $min && $max > 0) {
         // 计算跨度
         $priceGrade = 0.0001;
         for ($i = -2; $i < log10($max); $i++) {
             $priceGrade *= 10;
         }
         $span = ceil(($max - $min) / 5 / $priceGrade) * $priceGrade;
         if ($span == 0) {
             $span = $priceGrade;
         }
         // 计算价格的起点和终点
         for ($i = 1; $min > $span * $i; $i++) {
         }
         for ($j = 1; $min > $span * ($i - 1) + $priceGrade * $j; $j++) {
         }
         $priceFilter['start'] = $span * ($i - 1) + $priceGrade * ($j - 1);
         for (; $max >= $span * $i; $i++) {
         }
         $priceFilter['end'] = $span * $i + $priceGrade * ($j - 1);
         $priceFilter['span'] = $span;
     }
     /****** 价格筛选 end ****/
     /****** 品牌筛选 start ****/
     $result = (new Query())->select('distinct(brand_id)')->from('product')->where(['category_id' => $arrSubCat, 'status' => Status::STATUS_ACTIVE])->all();
     $ids = ArrayHelper::map($result, 'brand_id', 'brand_id');
     $brandFilter = Brand::find()->where(['id' => $ids])->orderBy(['name' => SORT_ASC])->all();
     /****** 品牌筛选 end ****/
     $query = Product::find()->where(['category_id' => $arrSubCat, 'status' => Status::STATUS_ACTIVE]);
     // 如果选择了价格区间
     if (Yii::$app->request->get('max')) {
         $min = intval(Yii::$app->request->get('min'));
         $max = intval(Yii::$app->request->get('max'));
         if ($min >= 0 && $max) {
             $query->andWhere(['and', ['>', 'price', $min], ['<=', 'price', $max]]);
         }
     }
     // 如果选择了品牌
     if (Yii::$app->request->get('brand_id')) {
         $brandId = intval(Yii::$app->request->get('brand_id'));
         if ($brandId >= 0) {
             $query->andWhere(['brand_id' => $brandId]);
         }
     }
     // 侧边热销商品
     $sameCategoryProducts = Product::find()->where(['category_id' => $id])->orderBy(['sales' => SORT_DESC])->limit(5)->all();
     $dataProvider = new ActiveDataProvider(['query' => $query, 'pagination' => ['defaultPageSize' => Yii::$app->params['defaultPageSizeProduct']], 'sort' => ['defaultOrder' => ['created_at' => SORT_DESC]]]);
     return $this->render('view', ['model' => $this->findModel($id), 'allCategory' => $allCategory, 'arrayCategoryIdName' => $arrayCategoryIdName, 'products' => $dataProvider->getModels(), 'pagination' => $dataProvider->pagination, 'priceFilter' => isset($priceFilter) ? $priceFilter : null, 'brandFilter' => $brandFilter, 'sameCategoryProducts' => $sameCategoryProducts]);
 }
コード例 #2
0
ファイル: BrandServiceImpl.php プロジェクト: xiaomige/giishop
 public function query(BrandDto $brandDto, array $pageParams, array $sortParams)
 {
     $query = Brand::find();
     //增加filter
     $pagination = new Pagination(array_merge($pageParams, ['totalCount' => $query->count()]));
     $sort = new Sort(['defaultOrder' => $sortParams]);
     $provider = new ActiveDataProvider(['query' => $query, 'pagination' => $pagination, 'sort' => $sort]);
     return ['models' => ArrayHelper::toArray($provider->getModels()), 'pagination' => $pagination];
 }
コード例 #3
0
ファイル: BrandSearch.php プロジェクト: CTaiDeng/funshop
 /**
  * Creates data provider instance with search query applied
  *
  * @param array $params
  *
  * @return ActiveDataProvider
  */
 public function search($params)
 {
     $query = Brand::find();
     $query->orderBy(['created_at' => SORT_DESC]);
     $dataProvider = new ActiveDataProvider(['query' => $query]);
     if ($this->load($params) && !$this->validate()) {
         return $dataProvider;
     }
     $query->andFilterWhere(['id' => $this->id, 'sort_order' => $this->sort_order, 'status' => $this->status, 'created_at' => $this->created_at, 'updated_at' => $this->updated_at]);
     $query->andFilterWhere(['like', 'name', $this->name])->andFilterWhere(['like', 'logo', $this->logo])->andFilterWhere(['like', 'description', $this->description])->andFilterWhere(['like', 'url', $this->url]);
     return $dataProvider;
 }
コード例 #4
0
 /**
  * Creates data provider instance with search query applied
  *
  * @param array $params
  *
  * @return ActiveDataProvider
  */
 public function search($params)
 {
     $query = Brand::find();
     $dataProvider = new ActiveDataProvider(['query' => $query, 'pagination' => ['pageSize' => self::PAGINATION_SIZE]]);
     $this->load($params);
     if (!$this->validate()) {
         // uncomment the following line if you do not want to return any records when validation fails
         // $query->where('0=1');
         return $dataProvider;
     }
     $query->andFilterWhere(['id' => $this->id]);
     $query->andFilterWhere(['like', 'title', $this->title]);
     return $dataProvider;
 }
コード例 #5
0
ファイル: BrandController.php プロジェクト: wordnews/wei_shop
 /**
  * Lists all Brand models.
  * @return mixed
  */
 public function actionIndex($brand_name = '')
 {
     if (!$this->is_access('brand/index')) {
         Yii::$app->session->setFlash('error', $this->errorInfo);
         return $this->redirect($this->redirectUrl);
     }
     if (empty($brand_name)) {
         $query = Brand::find();
     } else {
         $query = Brand::find()->where("brand_name like '%{$brand_name}%'");
     }
     $dataProvider = new ActiveDataProvider(['query' => $query]);
     Yii::$app->view->params['meta_title'] = '商品品牌';
     return $this->render('index', ['dataProvider' => $dataProvider]);
 }
コード例 #6
0
ファイル: index.php プロジェクト: liangdabiao/funshop
        <?php 
echo Html::a(Yii::t('app', 'Create ') . Yii::t('app', 'Product'), ['create'], ['class' => 'btn btn-success']);
?>
        <?php 
echo Html::a(Yii::t('app', 'Batch ') . Yii::t('app', 'Delete'), '#', ['class' => 'btn btn-danger', 'id' => 'batchDelete']);
?>
    </p>

    <?php 
echo GridView::widget(['dataProvider' => $dataProvider, 'filterModel' => $searchModel, 'columns' => [['class' => 'yii\\grid\\CheckboxColumn'], 'id', ['attribute' => 'category_id', 'value' => function ($model) {
    return $model->category->name;
}, 'filter' => Html::activeDropDownList($searchModel, 'category_id', ArrayHelper::map(Category::get(0, Category::find()->asArray()->all()), 'id', 'label'), ['class' => 'form-control', 'prompt' => Yii::t('app', 'Please Filter')])], 'name', 'sku', 'stock', 'market_price', 'price', ['attribute' => 'type', 'format' => 'html', 'value' => function ($model) {
    return \common\models\ProductType::labels($model->type);
}], ['attribute' => 'brand_id', 'value' => function ($model) {
    return $model->brand ? $model->brand->name : '-';
}, 'filter' => Html::activeDropDownList($searchModel, 'type', ArrayHelper::map(\common\models\Brand::find()->all(), 'id', 'name'), ['class' => 'form-control', 'prompt' => Yii::t('app', 'Please Filter')])], ['attribute' => 'status', 'format' => 'html', 'value' => function ($model) {
    if ($model->status === Status::STATUS_ACTIVE) {
        $class = 'label-success';
    } elseif ($model->status === Status::STATUS_INACTIVE) {
        $class = 'label-warning';
    } else {
        $class = 'label-danger';
    }
    return '<span class="label ' . $class . '">' . Status::labels($model->status) . '</span>';
}, 'filter' => Html::activeDropDownList($searchModel, 'status', Status::labels(), ['class' => 'form-control', 'prompt' => Yii::t('app', 'PROMPT_STATUS')])], 'created_at:date', ['class' => 'yii\\grid\\ActionColumn']]]);
?>

</div>

<?php 
$urlBatchDelete = \yii\helpers\Url::to(['/product/batch-delete']);
コード例 #7
0
ファイル: _form.php プロジェクト: CTaiDeng/funshop
?>

    <?php 
echo $form->field($model, 'keywords')->textInput(['maxlength' => 255]);
?>

    <?php 
echo $form->field($model, 'description')->textarea(['rows' => 6]);
?>

    <?php 
echo $form->field($model, 'type')->checkboxList(\common\models\ProductType::labels());
?>

    <?php 
echo $form->field($model, 'brand_id')->dropDownList(ArrayHelper::map(\common\models\Brand::find()->all(), 'id', 'name'), ['prompt' => Yii::t('app', 'Please Select')]);
?>

    <?php 
echo $form->field($model, 'status')->dropDownList(\common\models\Status::labels());
?>

    <?php 
if (!$model->isNewRecord) {
    ?>
        <div class="form-group">
            <?php 
    foreach ($model->productImages as $image) {
        echo '<div style="width:150px; float: left; text-align: center">';
        echo '<a href="' . \Yii::$app->getUrlManager()->createUrl(['product/remove', 'id' => $image->id]) . '" title="' . Yii::t('app', 'Delete') . '" data-confirm="' . Yii::t('app', 'Are you sure you want to delete this item?') . '" data-method="post" data-pjax="0"><span class="glyphicon glyphicon-trash"></span></a><br>';
        if (strpos($image->thumb, 'http://') === null) {
コード例 #8
0
 /**
  * batch import product
  * @param integer $id
  * @return mixed
  */
 public function actionImport()
 {
     //if(!Yii::$app->user->can('viewYourAuth')) throw new ForbiddenHttpException(Yii::t('app', 'No Auth'));
     $format = Product::getImportExportFormat();
     if (Yii::$app->request->post()) {
         $countCreate = $countUpdate = 0;
         $file = UploadedFile::getInstanceByName('importFile');
         $handle = fopen($file->tempName, 'r');
         $result = $this->inputCsv($handle);
         $arrData = [];
         if (count($result) <= 1) {
             Yii::$app->getSession()->setFlash('danger', Yii::t('app', 'No Record, please check file.'));
         } else {
             // 将数据的key从数字变成固定的格式
             for ($i = 1; $i < count($result); $i++) {
                 $j = 0;
                 foreach ($format as $item) {
                     $data[$item] = $result[$i][$j];
                     $j++;
                 }
                 $data['thumbs'] = $result[$i][$j];
                 $data['images'] = $result[$i][$j + 1];
                 array_push($arrData, $data);
             }
             // 处理数据,如果ID大于0,则更新,否则新增
             $line = 2;
             $errorLines = [];
             foreach ($arrData as $item) {
                 if ($item['id'] > 0) {
                     // 已存在的值,则更新数据,以及判断缩略图和图片
                     $model = Product::findOne($item['id']);
                     if ($model === null) {
                         array_push($errorLines, $line);
                         $line++;
                         continue;
                     }
                     foreach ($item as $k => $v) {
                         if ($k == 'id' || $k == 'thumbs' || $k == 'images') {
                             continue;
                         }
                         $model[$k] = iconv('gb2312', 'utf-8', trim($v));
                     }
                     $result = $model->save();
                     if (!$result) {
                         //如果保存失败
                         array_push($errorLines, $line);
                         $line++;
                         continue;
                     }
                     $countUpdate++;
                     if ($item['thumbs'] && $item['images']) {
                         $arrThumb = explode('|', $item['thumbs']);
                         $arrImage = explode('|', $item['images']);
                         $i = 0;
                         $ids = [];
                         foreach ($arrThumb as $thumb) {
                             $thumb = trim($thumb);
                             $image = trim($arrImage[$i]);
                             $productImage = ProductImage::find()->where(['product_id' => $item['id'], 'thumb' => $thumb, 'image' => $image])->one();
                             if ($productImage) {
                                 //如果图片在数据库中已经存在,则假如到ids数组,防止后续被删除
                                 array_push($ids, $productImage->id);
                             } else {
                                 //不存在的话,新增记录并将id加入到ids
                                 $productImage = new ProductImage(['product_id' => $item['id'], 'thumb' => $thumb, 'image' => $image]);
                                 $productImage->save();
                                 array_push($ids, $productImage->id);
                             }
                             $i++;
                         }
                         //删除在ids数组中记录
                         ProductImage::deleteAll(['and', 'product_id=' . $item['id'], ['not in', 'id', $ids]]);
                     }
                 } else {
                     // 新的数据,插入,并将缩略图和图片插入
                     $model = new Product();
                     foreach ($item as $k => $v) {
                         if ($k == 'id' || $k == 'thumbs' || $k == 'images') {
                             continue;
                         }
                         $model[$k] = iconv('gb2312', 'utf-8', trim($v));
                     }
                     // 将分类和品牌转换成对应的ID
                     $category = Category::find()->where(['name' => trim($model->category_id)])->one();
                     $model->category_id = $category ? $category->id : 1;
                     $brand = Brand::find()->where(['name' => trim($model->brand_id)])->one();
                     $model->brand_id = $brand ? $brand->id : 0;
                     $result = $model->save();
                     if (!$result) {
                         //如果保存失败
                         array_push($errorLines, $line);
                         $line++;
                         continue;
                     }
                     $countCreate++;
                     if ($item['thumbs'] && $item['images']) {
                         $arrThumb = explode('|', $item['thumbs']);
                         $arrImage = explode('|', $item['images']);
                         $i = 0;
                         foreach ($arrThumb as $thumb) {
                             $thumb = trim($thumb);
                             $image = trim($arrImage[$i]);
                             if ($thumb && $image) {
                                 // 缩略图和图片都有才加入
                                 $productImage = new ProductImage(['product_id' => $model->id, 'thumb' => $thumb, 'image' => $image]);
                                 $productImage->save();
                             }
                             $i++;
                         }
                     }
                 }
                 $line++;
             }
             if (count($errorLines)) {
                 $strLine = implode(', ', $errorLines);
                 Yii::$app->getSession()->setFlash('danger', Yii::t('app', "Line {strLine} error.", ['strLine' => $strLine]));
             }
             Yii::$app->getSession()->setFlash('success', Yii::t('app', "Import Data Success. Create: {countCreate}  Update: {countUpdate}", ['countCreate' => $countCreate, 'countUpdate' => $countUpdate]));
         }
     }
     return $this->render('import', []);
 }
コード例 #9
0
 /**
  * Creates a new Product model.
  * If creation is successful, the browser will be redirected to the 'view' page.
  * @return mixed
  * @throws Exception
  * @throws \yii\base\Exception
  */
 public function actionCreate()
 {
     //check for categories
     if (!Category::find()->active()->all()) {
         Yii::$app->session->setFlash('error', "You don't have any active categories to add product");
         return $this->redirect('index');
     }
     //check for brand
     if (!Brand::find()->all()) {
         Yii::$app->session->setFlash('error', "You don't have any brands to add product");
         return $this->redirect('index');
     }
     $model = new Product();
     $model->scenario = $model::SCENARIO_CREATE;
     $productVideo = new ProductVideo(['scenario' => ProductVideo::SCENARIO_PRODUCT_ADD]);
     $videos = [$productVideo];
     $productProperty = new ProductProperty(['scenario' => ProductProperty::SCENARIO_PRODUCT_ADD]);
     $properties = [$productProperty];
     if ($model->load($post = Yii::$app->request->post())) {
         $properties = Model::createMultiple(ProductProperty::classname());
         $videos = Model::createMultiple(ProductVideo::classname());
         Model::setScenarios($properties, ProductProperty::SCENARIO_PRODUCT_ADD);
         Model::setScenarios($videos, ProductVideo::SCENARIO_PRODUCT_ADD);
         Model::loadMultiple($properties, Yii::$app->request->post());
         Model::loadMultiple($videos, Yii::$app->request->post());
         Model::validateDuplicates($properties, 'property_id');
         // ajax validation
         if (Yii::$app->request->isAjax) {
             Yii::$app->response->format = Response::FORMAT_JSON;
             return ArrayHelper::merge(ActiveForm::validate($model), ActiveForm::validateMultiple($properties, false), ActiveForm::validateMultiple($videos));
         }
         if ($model->validate() && Model::validateMultiple($properties) && Model::validateMultiple($videos)) {
             $transaction = $model->getDb()->beginTransaction();
             $model->main_photo = UploadedFile::getInstance($model, 'main_photo');
             try {
                 if (!($category = Category::findOne(['id' => $model->category_id]))) {
                     throw new \yii\base\Exception();
                 }
                 if ($model->save(false)) {
                     Model::linkAll($model, $properties, 'productProperties');
                     Model::unsetEmpty($videos, 'video');
                     Model::linkAll($model, $videos, 'videos');
                     $model->savePhotos();
                     $model->upload();
                     $transaction->commit();
                     Yii::$app->session->setFlash('success', 'Product have been created.');
                 } else {
                     $transaction->rollBack();
                     Yii::$app->session->setFlash('error', 'Failed to create product.');
                 }
                 return $this->redirect('index');
             } catch (Exception $e) {
                 Yii::$app->session->setFlash('error', 'Failed to create product.');
                 $transaction->rollBack();
                 return $this->redirect('index');
             }
         }
     }
     $model->clearTmpPhotos();
     $model->setAttribute('active', true);
     return $this->render('create', ['model' => $model, 'videos' => $videos, 'properties' => $properties]);
 }