Ejemplo n.º 1
0
 /**
  * 设置显示状态
  * @param $brand_id
  * @param int $status
  * @return bool|int
  */
 public function setStatus($brand_id, $status = 1)
 {
     if (!in_array($status, [0, 1])) {
         return false;
     }
     return Brand::updateAll(['status' => $status], 'brand_id = :brand_id', [':brand_id' => $brand_id]);
 }
Ejemplo n.º 2
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]);
 }
Ejemplo n.º 3
0
 protected function findById($id)
 {
     if (($model = Brand::findOne($id)) !== null) {
         return $model;
     } else {
         throw new NotFoundHttpException('请求页面不存在');
     }
 }
Ejemplo n.º 4
0
 /**
  * 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;
 }
Ejemplo n.º 5
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;
 }
Ejemplo n.º 6
0
 /**
  * Finds the Brand model based on its primary key value.
  * If the model is not found, a 404 HTTP exception will be thrown.
  * @param integer $id
  * @return Brand the loaded model
  * @throws NotFoundHttpException if the model cannot be found
  */
 protected function findModel($id)
 {
     if (($model = Brand::findOne($id)) !== null) {
         return $model;
     } else {
         throw new NotFoundHttpException('The requested page does not exist.');
     }
 }
Ejemplo n.º 7
0
 public function getBrand()
 {
     return $this->hasOne(Brand::className(), ['id' => 'brand_id']);
 }
Ejemplo n.º 8
0
        <?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']);
Ejemplo n.º 9
0
 /**
  * 修改热销状态
  * @param int $brand_id
  * @param int $status
  */
 public function actionHot($brand_id, $status = 1)
 {
     if (!$this->is_access('brand/update')) {
         exit;
     }
     $model = new Brand();
     if ($model->setHot($brand_id, $status)) {
         echo '1';
     } else {
         echo '0';
     }
 }
Ejemplo n.º 10
0
?>

    <?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) {
Ejemplo n.º 11
0
 /**
  * @param integer $id
  * @return mixed
  */
 public function actionUpdate($id)
 {
     if (!$this->is_access('goods/update')) {
         Yii::$app->session->setFlash('error', $this->errorInfo);
         return $this->redirect($this->redirectUrl);
     }
     $model = $this->findModel($id);
     $GoodsGallery = new GoodsGallery();
     $post = Yii::$app->request->post();
     if ($model->load($post)) {
         $GoodsGallery->load($post);
         if ($model->validate() && $GoodsGallery->validate()) {
             // 商品封面图片
             if ($_FILES['Goods']['error']['goods_img'] === 0) {
                 $model->goods_img = File::uploadImage($model, 'goods_img', 'shop');
                 $model->goods_thumb = Images::thumb('./' . $model->goods_img, 250, 250);
             }
             if ($model->save(false)) {
                 // 商品相册
                 if ($_FILES['GoodsGallery']['error']['img_url'][0] === 0) {
                     $img_url = File::uploadImages($GoodsGallery, 'img_url', 'goods');
                     $GoodsGallery->addData($model->goods_id, $img_url);
                 }
                 // 商品属性
                 GoodsAttr::addData($model->goods_id);
             }
             Yii::$app->session->setFlash('success', '编辑成功');
         }
         return $this->redirect(['index']);
     } else {
         // 商品分类
         $Category = new Category();
         $categoryList = $Category->parent(0, false);
         // 品牌
         $Brand = new Brand();
         $brandList = $Brand->getLists();
         // 商品类型
         $GoodsType = new GoodsType();
         $goodsTypeList = $GoodsType->dropList();
         // 相册
         $goodsGalleryList = $GoodsGallery->getGoodsGallery($id);
         Yii::$app->view->params['meta_title'] = '编辑商品';
         return $this->render('update', ['model' => $model, 'GoodsGallery' => $GoodsGallery, 'categoryList' => $categoryList, 'brandList' => $brandList, 'goodsTypeList' => $goodsTypeList, 'goodsGalleryList' => $goodsGalleryList]);
     }
 }
Ejemplo n.º 12
0
    <?php 
echo \common\widgets\Alert::widget();
?>
    <div class="box">
        <div class="content">
            <div class="brand-create">

                <h1><?php 
echo Html::encode($this->title);
?>
</h1>
<!--                --><?php 
// echo $this->render('_search', ['model' => $searchModel]);
?>

                <p>
                    <?php 
echo Html::a('Create Brand', ['create'], ['class' => 'btn btn-success']);
?>
                </p>

                <?php 
echo GridView::widget(['dataProvider' => $dataProvider, 'emptyText' => 'You don\'t have any brands', 'filterModel' => $searchModel, 'columns' => [['class' => 'yii\\grid\\SerialColumn'], ['attribute' => 'title', 'filter' => AutoComplete::widget(['model' => $searchModel, 'attribute' => 'title', 'options' => ['class' => 'form-control'], 'clientOptions' => ['source' => Brand::getAutoCompleteItems('title')]])], ['class' => 'yii\\grid\\ActionColumn', 'template' => '{update}{delete}']]]);
?>


            </div>
        </div>
    </div>
</div>
Ejemplo n.º 13
0
 /**
  * batch export product
  * @param integer $id
  * @return mixed
  */
 public function actionExport()
 {
     //if(!Yii::$app->user->can('viewYourAuth')) throw new ForbiddenHttpException(Yii::t('app', 'No Auth'));
     $format = Product::getImportExportFormat();
     $products = Product::find()->orderBy(['id' => SORT_ASC])->all();
     $str = '';
     // 生成csv标题行
     $product = new Product();
     $start = true;
     foreach ($format as $column) {
         if ($start) {
             $str .= '"' . iconv('utf-8', 'gb2312', $product->attributeLabels()[$column]) . '"';
             $start = false;
         } else {
             $str .= ',"' . iconv('utf-8', 'gb2312', $product->attributeLabels()[$column]) . '"';
         }
     }
     $str .= ',' . iconv('utf-8', 'gb2312', Yii::t('app', 'Thumbs')) . ',' . iconv('utf-8', 'gb2312', Yii::t('app', 'Images'));
     $str .= "\n";
     foreach ($products as $row) {
         // 导出 product表中的数据
         $start = true;
         foreach ($format as $column) {
             $value = '';
             if ($column == 'category_id') {
                 if ($row[$column] > 0) {
                     $category = Category::findOne($row[$column]);
                     $value = iconv('utf-8', 'gb2312', $category->name);
                 }
             } elseif ($column == 'brand_id') {
                 if ($row[$column] > 0) {
                     $brand = Brand::findOne($row[$column]);
                     $value = iconv('utf-8', 'gb2312', $brand->name);
                 }
             } else {
                 $value = iconv('utf-8', 'gb2312', $row[$column]);
             }
             if ($start) {
                 $str .= '"' . $value . '"';
                 $start = false;
             } else {
                 $str .= ',"' . str_replace("\"", "\"\"", $value) . '"';
             }
         }
         // 导出product_image表中的数据
         $start = true;
         $strThumb = $strImage = '';
         $productImages = ProductImage::find()->where(['product_id' => $row->id])->all();
         foreach ($productImages as $item) {
             if ($start) {
                 $strThumb .= $item->thumb;
                 $strImage .= $item->image;
                 $start = false;
             } else {
                 $strThumb .= '|' . $item->thumb;
                 $strImage .= '|' . $item->image;
             }
         }
         $str .= ',"' . $strThumb . '","' . $strImage . '"';
         $str .= "\n";
     }
     $filename = date('Ymd') . '.csv';
     header("Content-type:text/csv");
     header("Content-Disposition:attachment;filename=" . $filename);
     header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
     header('Expires:0');
     header('Pragma:public');
     echo $str;
 }
Ejemplo n.º 14
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]);
 }
Ejemplo n.º 15
0
/* @var $properties \common\models\ProductProperty[] */
/* @var $videos \common\models\ProductVideo[] */
?>

<div class="product-form">

    <?php 
$form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data'], 'id' => 'product-form', 'enableAjaxValidation' => true]);
?>
    <h2>Base info</h2>
    <div class="col-md-12 row">
        <?php 
echo $form->field($model, 'category_id')->dropDownList(Category::getRubricsDropDownItems(), ['prompt' => 'Select category']);
?>
        <?php 
echo $form->field($model, 'brand_id')->dropDownList(Brand::getDropDownItems(), ['prompt' => 'Select brand']);
?>
        <?php 
echo $form->field($model, 'title')->textInput();
?>
        <?php 
if ($model->main_photo) {
    ?>
            <?php 
    echo Html::img($model->getMainImagePath(), ['style' => 'max-height: 160px']);
    ?>
        <?php 
}
?>
        <?php 
echo $form->field($model, 'main_photo')->fileInput()->label(!$model->isNewRecord ? 'Main photo (if not choose - old image will be set)' : 'Main Photo');