コード例 #1
1
ファイル: ModeloController.php プロジェクト: rodespsan/LMEC
 /**
  * Creates a new model.
  * If creation is successful, the browser will be redirected to the 'view' page.
  */
 public function actionCreate()
 {
     $model = new Modelo();
     // Uncomment the following line if AJAX validation is needed
     // $this->performAjaxValidation($model);
     if (isset($_POST['Modelo'])) {
         $model->attributes = $_POST['Modelo'];
         if ($model->save()) {
             if (!empty($_POST['yt1'])) {
                 Yii::app()->user->setFlash('modelo-created', "¡El modelo <b><i>&quot;{$model->name}&quot;</i></b> fue creado exitosamente!");
                 //$this->redirect(array('create'));
                 $modelSaved = $model;
                 $model = new Modelo();
                 $model->equipment_type_id = $modelSaved->equipment_type_id;
                 $model->brand_id = $modelSaved->brand_id;
             } else {
                 $this->redirect(array('view', 'id' => $model->id));
             }
         }
     }
     if (EquipmentType::model()->count('active = 1') == 0 && Brand::model()->count('active = 1') == 0) {
         throw new CHttpException('', 'Primero debe ' . CHtml::link('crear un Tipo de Equipo', array('equipmentType/create')) . ' y ' . CHtml::link('crear una Marca', array('brand/create')) . '.');
     } else {
         if (EquipmentType::model()->count('active = 1') == 0) {
             throw new CHttpException('', 'Primero debe ' . CHtml::link('crear un Tipo de Equipo', array('equipmentType/create')) . '.');
         } else {
             if (Brand::model()->count('active = 1') == 0) {
                 throw new CHttpException('', 'Primero debe ' . CHtml::link('crear una Marca', array('brand/create')) . '.');
             } else {
                 $this->render('create', array('model' => $model));
             }
         }
     }
 }
コード例 #2
0
ファイル: ItemController.php プロジェクト: conghua1013/yii
 public function actionIndex()
 {
     $product_id = intval($_REQUEST['id']);
     $pInfo = Product::model()->getProductInfoById($product_id);
     if (empty($pInfo)) {
         $this->redirect('/?from=no_goods');
         //跳转到首页
     }
     $brandInfo = '';
     if ($pInfo['brand_id']) {
         $brandInfo = Brand::model()->findByPk($pInfo['brand_id']);
     }
     $stock = Product::model()->getProductStock($product_id, $pInfo['is_multiple']);
     $attrList = ProductAttributes::model()->getProductAttrNameList();
     $extendAttrList = ProductExtend::model()->getProductExtendAttrs($product_id);
     $is_like = Like::model()->getLikeStatus($this->user_id, $product_id);
     $cake = Category::model()->getCakeLine($pInfo['cat_id']);
     //获取商品的面包屑
     $viewData = array();
     $viewData['pInfo'] = $pInfo;
     $viewData['brandInfo'] = $brandInfo;
     $viewData['is_like'] = $is_like;
     $viewData['cake'] = $cake;
     $viewData['stock'] = $stock;
     $viewData['attrList'] = $attrList;
     $viewData['extendAttrList'] = $extendAttrList;
     $this->render('item/index', $viewData);
 }
コード例 #3
0
ファイル: BrandController.php プロジェクト: conghua1013/yii
 /**
  * 品牌详情页面(带商品列表)
  */
 public function actionDetail()
 {
     $_REQUEST['id'] = intval($_REQUEST['id']);
     if (empty($_REQUEST['id'])) {
         $this->redirect('/?from=brand_empty');
     }
     $brandInfo = Brand::model()->getBrandInfoForWeb($_REQUEST['id']);
     if (empty($brandInfo)) {
         $this->redirect('/?from=brand_empty');
     }
     $result = Brand::model()->getBrandProductByPageForWeb($_REQUEST);
     if (empty($result) || $result['count'] <= 0) {
         $this->redirect('/?from=brand_product_empty');
     }
     $filter = $result['filter'];
     $urlStr = '/brand/' . $_REQUEST['id'];
     $pages = '';
     $pageShort = '';
     if ($result['count'] > 0) {
         $pages = Common::instance()->get_page_list($result['count'], $filter['p'], $filter['page_size'], $urlStr);
         $pageShort = Common::instance()->get_page_short($result['count'], $filter['p'], $filter['page_size'], $urlStr);
     }
     $viewData = array();
     $viewData['brandInfo'] = $brandInfo;
     $viewData['list'] = $result['list'];
     $viewData['count'] = $result['count'];
     $viewData['filter'] = $result['filter'];
     $viewData['pages'] = $pages;
     $viewData['pageShort'] = $pageShort;
     $this->render('brand/detail', $viewData);
 }
コード例 #4
0
 public function run()
 {
     Yii::import($this->import);
     $data = CHtml::listData(Brand::model()->findAll(array('order' => 'title')), 'id', 'title');
     $data[0] = '';
     ksort($data);
     echo CJavaScript::jsonEncode($data);
 }
コード例 #5
0
 public function loadModel($id)
 {
     $model = Brand::model()->findByPk($id);
     if ($model === null) {
         throw new CHttpException(404, 'The requested page does not exist.');
     }
     return $model;
 }
コード例 #6
0
 public function actionIndex()
 {
     $brand_id = isset($_GET['brand_id']) ? $_GET['brand_id'] : 0;
     $productCategoryOptions = ProductCategory::model()->byBrandOptions($brand_id);
     // 产品
     $criteria = new CDbCriteria();
     $criteria->compare('t.is_released', 1);
     $productarr = Product::model()->localized()->findAll($criteria);
     $brand = array();
     if ($brand_id != 0) {
         $criteria = new CDbCriteria();
         $criteria->compare('t.brand_id', $brand_id);
         $criteria->order = 'sort_order ASC';
         $brand = Brand::model()->localized()->find($criteria);
         $productCategoryOptions = ProductCategory::model()->byBrandOptions($brand_id);
         // 产品
         $criteria = new CDbCriteria();
         $criteria->compare('t.brand_id', $brand_id);
         $productarr = Product::model()->localized()->findAll($criteria);
     }
     $products = array();
     foreach ($productarr as $model) {
         $products[] = $model->attributes;
     }
     // 广告图
     $criteria = new CDbCriteria();
     $criteria->compare('t.banner_position_id', 1);
     $banner = Banner::model()->localized()->find($criteria);
     $brands = array();
     $criteria = new CDbCriteria();
     $criteria->select = 'brand_id,title';
     $criteria->compare('t.is_released', 1);
     $brandsarr = Brand::model()->localized()->findAll($criteria);
     foreach ($brandsarr as $model) {
         $brands[$model->brand_id] = $model->title;
     }
     $series = array();
     $criteria = new CDbCriteria();
     $criteria->select = 'series_id,title';
     $criteria->compare('t.is_released', 1);
     $seriesarr = ProductSeries::model()->localized()->findAll($criteria);
     foreach ($seriesarr as $model) {
         $series[$model->series_id] = $model->title;
     }
     $categorys = array();
     $criteria = new CDbCriteria();
     $criteria->select = 'category_id,name';
     $criteria->compare('t.is_released', 1);
     $categorysarr = ProductCategory::model()->localized()->findAll($criteria);
     foreach ($categorysarr as $model) {
         $categorys[$model->category_id] = $model->name;
     }
     $this->layout = 'main';
     $this->pageTitle = Yii::t('common', '产品中心') . SEPARATOR . Setting::getValueByCode('inside_title', true);
     $this->render('index', array('brand_id' => $brand_id, 'brand' => $brand, 'products' => $products, 'brands' => $brands, 'series' => $series, 'categorys' => $categorys, 'productCategoryOptions' => $productCategoryOptions, 'banner' => $banner));
 }
コード例 #7
0
ファイル: Brand.php プロジェクト: rahmanjis/yii-catalog
 /**
  * @static Return brands list for category, sorted by brand goods count
  * @param $category_id
  * @return Brand[] brands, whose goods belongs to the category
  */
 public static function GetCategoryBrands($category_id)
 {
     $brands = Brand::model()->with(array('goodsCount' => array('condition' => 'category_id=' . $category_id)))->findAll();
     foreach ($brands as $i => $brand) {
         if ($brand->goodsCount == 0) {
             unset($brands[$i]);
         }
     }
     usort($brands, 'CAlexHelper::CompareGoodsCount');
     return $brands;
 }
コード例 #8
0
ファイル: ProductController.php プロジェクト: conghua1013/yii
 public function actionEdit()
 {
     if (empty($_POST)) {
         $pInfo = Product::model()->findByPk($_REQUEST['id']);
         $categorys = Category::model()->getSelectCategoryForProductEdit();
         //可选分类列表
         $brands = Brand::model()->getSelectBrandForProductEdit();
         //可选品牌列表
         $productAttributes = ProductAttributes::model()->getProductAttrTree();
         $pImages = ProductImage::model()->findAllByAttributes(array('product_id' => $_REQUEST['id']));
         $stocks = ProductStock::model()->findAllByAttributes(array('product_id' => $_REQUEST['id']));
         $attrList = array();
         foreach ($productAttributes as $row) {
             if ($row['child']) {
                 $attrList += $row['child'];
             }
         }
         $viewData = array();
         $viewData['categorys'] = $categorys;
         $viewData['brands'] = $brands;
         $viewData['pInfo'] = $pInfo;
         $viewData['pImages'] = $pImages;
         $viewData['stocks'] = $stocks;
         $viewData['attrList'] = $attrList;
         $viewData['productAttributes'] = $productAttributes;
         $this->render('edit', $viewData);
         exit;
     }
     $res = array('statusCode' => 200, 'message' => '修改成功!');
     $transaction = Yii::app()->shop->beginTransaction();
     try {
         $productId = $this->saveProduct();
         //保存商品的基本信息
         $this->saveProductCategory($productId);
         //保存商品的分类信息
         $this->saveProductExtend($productId);
         //保存商品的扩展信息
         $this->saveProductStock($productId);
         //保存商品的库存信息
         // $this->saveProductAttr($productId); //保存商品的属性信息
         $transaction->commit();
     } catch (exception $e) {
         $transaction->rollback();
         $res['statusCode'] = 300;
         $res['message'] = '修改失败!【' . $e->getMessage() . '】';
     }
     $res['navTabId'] = 'productList';
     $res['callbackType'] = 'closeCurrent';
     $res['forwardUrl'] = '/manage/product/index';
     $this->ajaxDwzReturn($res);
 }
コード例 #9
0
 public function actionView()
 {
     $previd = 0;
     // 上一个品牌
     $nextid = 0;
     // 下一个品牌
     $brand = null;
     $prevname = '';
     $nextname = '';
     $products = null;
     if (isset($_GET['id'])) {
         $id = Yii::app()->request->getQuery('id');
         // 浏览数量加1
         $brandModel = Brand::model()->findByPk($id);
         $brandModel->view_count += 1;
         $brandModel->update();
         $brand = Brand::model()->localized()->findByPk($id);
         $criteria = new CDbCriteria();
         $criteria->compare('t.is_released', 1);
         $criteria->compare('t.brand_id', $id);
         $products = Product::model()->localized()->findAll($criteria);
         $criteria = new CDbCriteria();
         $criteria->compare('t.is_released', 1);
         $criteria->order = 'sort_order ASC';
         $brands = Brand::model()->localized()->findAll($criteria);
         foreach ($brands as $key => $value) {
             if ($value->brand_id == $id && $key != 0) {
                 $previd = isset($brands[$key - 1]) ? $brands[$key - 1]['brand_id'] : 0;
                 $nextid = isset($brands[$key + 1]) ? $brands[$key + 1]['brand_id'] : 0;
                 $prevname = isset($brands[$key - 1]) ? $brands[$key - 1]['title'] : '';
                 $nextname = isset($brands[$key + 1]) ? $brands[$key + 1]['title'] : '';
             } else {
                 if ($value->brand_id == $id && $key == 0) {
                     $nextid = isset($brands[$key + 1]) ? $brands[$key + 1]['brand_id'] : 0;
                     $nextname = isset($brands[$key + 1]) ? $brands[$key + 1]['title'] : '';
                 }
             }
         }
     }
     if (empty($brand)) {
         throw new CHttpException(404);
     }
     // 广告图
     $criteria = new CDbCriteria();
     $criteria->compare('t.banner_position_id', 2);
     $banner = Banner::model()->localized()->find($criteria);
     $this->pageTitle = Yii::t('common', '品牌中心') . SEPARATOR . Setting::getValueByCode('inside_title', true);
     $this->render('view', array('brand' => $brand, 'banner' => $banner, 'previd' => $previd, 'nextid' => $nextid, 'prevname' => $prevname, 'nextname' => $nextname, 'products' => $products));
 }
コード例 #10
0
 public function actionSearch()
 {
     $keyword = $_GET['keyword'] ? trim($_GET['keyword']) : "";
     $num = 0;
     $products = null;
     $brands = null;
     // 品牌搜索
     $criteria = new CDbCriteria();
     $criteria->addSearchCondition('t.title', $keyword, true, 'OR');
     $criteria->addSearchCondition('t.sub_content', $keyword, true, 'OR');
     $criteria->addSearchCondition('t.content', $keyword, true, 'OR');
     if ($_GET['lang'] === 'en') {
         $criteria->addSearchCondition('localized.title', $keyword, true, 'OR');
         $criteria->addSearchCondition('localized.sub_content', $keyword, true, 'OR');
         $criteria->addSearchCondition('localized.content', $keyword, true, 'OR');
     }
     $brands = Brand::model()->localized()->findAll($criteria);
     // 产品搜索
     $criteria = new CDbCriteria();
     $criteria->select = 't.series_id';
     $criteria->addSearchCondition('t.title', $keyword, true, 'OR');
     $criteria->addSearchCondition('t.norms', $keyword, true, 'OR');
     $criteria->addSearchCondition('t.series_model', $keyword, true, 'OR');
     $criteria->addSearchCondition('t.content', $keyword, true, 'OR');
     if ($_GET['lang'] === 'en') {
         $criteria->select = 'localized.owner_id as series_id';
         $criteria->addSearchCondition('localized.title', $keyword, true, 'OR');
         $criteria->addSearchCondition('localized.norms', $keyword, true, 'OR');
         $criteria->addSearchCondition('localized.series_model', $keyword, true, 'OR');
         $criteria->addSearchCondition('localized.content', $keyword, true, 'OR');
     }
     $serieids = ProductSeries::model()->localized()->findAll($criteria);
     $ids = array();
     foreach ($serieids as $key => $value) {
         $ids[] = $value->series_id;
     }
     $criteria = new CDbCriteria();
     if (!empty($ids)) {
         $criteria->addInCondition('t.series_id', $ids);
     }
     $criteria->addSearchCondition('t.name', $keyword, true, 'OR');
     if ($_GET['lang'] === 'en') {
         $criteria->addSearchCondition('localized.name', $keyword, true, 'OR');
     }
     $products = Product::model()->localized()->findAll($criteria);
     $num = count($products) + count($brands);
     $this->pageTitle = Yii::t('common', '首页') . SEPARATOR . Setting::getValueByCode('inside_title', true);
     $this->render('search', array('keyword' => $keyword, 'brands' => $brands, 'products' => $products, 'num' => $num));
 }
コード例 #11
0
ファイル: Region.php プロジェクト: kinghinds/kingtest2
 public static function getSelects()
 {
     static $level = 0;
     $items = array();
     $criteria = new CDbCriteria();
     $criteria->compare('t.is_released', 1);
     $models = self::model()->localized(null, false)->findAll($criteria);
     foreach ($models as $model) {
         $criteria = new CDbCriteria();
         $criteria->compare('region_id', $model->primaryKey);
         $brands = Brand::model()->findAll($criteria);
         if (count($brands) > 0) {
             $items[$model->primaryKey] = $model->title;
         }
     }
     return $items;
 }
コード例 #12
0
ファイル: ServicedetailController.php プロジェクト: zwq/unpei
 public function actionDetail()
 {
     //$model = Dealer::model()->find("userID=:userID", array(":userID" => $_GET['dealer']));
     $organID = Yii::app()->request->getParam("dealer");
     $model = Organ::model()->with('dealer')->findByPK($organID);
     //主营品牌
     $brands = Brand::model()->findAll("OrganID = {$organID}");
     $data = array();
     foreach ($brands as $key => $brand) {
         $data[$key]['brandname'] = $brand['BrandName'];
     }
     //主营车系
     $dealerv = DealerVehicles::model()->findAll("OrganID=:userID", array(":userID" => $organID));
     //主营品类
     $cpnames = OrganCpname::model()->findAll('OrganID=:userID', array(':userID' => $organID));
     // 机构照片
     $photosql = 'select * from `{{organ_photo}}` where OrganID=' . $organID;
     $organphotos = Yii::app()->jpdb->createCommand($photosql)->queryAll();
     $this->render("detail", array('model' => $model, 'organphotos' => $organphotos, 'dealerv' => $dealerv, 'showcpnames' => $cpnames, 'data' => $data));
 }
コード例 #13
0
 public function actionIndex($id)
 {
     $model = ModelCategory::model()->findAll('category_id = :num', array(':num' => $id));
     $modelBrand = new Brand();
     $modelCategory = new ModelCategory();
     if (isset($_POST['ids'])) {
         ModelCategory::model()->deleteAll('brand_id = :brand_id', array(':brand_id' => $_POST['ids']));
         Brand::model()->findByPk($_POST['ids'])->delete();
         $this->refresh();
     }
     if (isset($_POST['yt0'])) {
         $modelBrand->attributes = $_POST['Brand'];
         $modelBrand->save();
         $modelCategory->category_id = $id;
         $modelCategory->brand_id = $modelBrand->id;
         if ($modelCategory->save()) {
             Yii::app()->user->setFlash('status', 'Бренд добавлен');
         }
         $this->refresh();
     }
     $this->render('index', array('model' => $model, 'modelBrand' => $modelBrand, 'idkey' => $id));
 }
コード例 #14
0
 /**
  * Updates a particular model.
  * If update is successful, the browser will be redirected to the 'view' page.
  * @param integer $id the ID of the model to be updated
  */
 public function actionUpdate($id)
 {
     $model = $this->loadModel($id);
     $modelsBrands = Brand::model()->findAll();
     $brandsArray = CHtml::listData($modelsBrands, 'id', 'brand_name');
     $modelsPlatforms = Platforms::model()->findAll();
     $platformsArray = CHtml::listData($modelsPlatforms, 'id', 'name');
     // Uncomment the following line if AJAX validation is needed
     // $this->performAjaxValidation($model);
     if (isset($_POST['buttonCancel'])) {
         $this->redirect(array('admin'));
     }
     if (isset($_POST['Device'])) {
         $model->attributes = $_POST['Device'];
         /*GARENTE QUE O NOME DO DEVICE SEMPRE SEJA SALVO EM MAIÚSCULO*/
         $model->description = strtoupper($model->description);
         if ($model->save()) {
             $this->redirect(array('admin', 'id' => $model->id));
         }
     }
     $this->render('update', array('model' => $model, 'brandsArray' => $brandsArray, 'platformsArray' => $platformsArray));
 }
コード例 #15
0
 public function actionBatchUnCommend()
 {
     $idList = Yii::app()->request->getPost('brand_id', array());
     if (count($idList) > 0) {
         $criteria = new CDbCriteria();
         $criteria->addInCondition('brand_id', $idList);
         $brands = Brand::model()->findAll($criteria);
         $flag = 0;
         foreach ($brands as $brand) {
             $brand->is_recommend = 0;
             if ($brand->save()) {
                 $flag++;
             }
         }
         if ($flag > 0) {
             $this->setFlashMessage('品牌取消推荐成功');
         } else {
             $this->setFlashMessage('品牌取消推荐失败', 'warn');
         }
     } else {
         $this->setFlashMessage('没有记录被选中', 'warn');
     }
     $this->redirect(array('index'));
 }
コード例 #16
0
ファイル: index.php プロジェクト: kinghinds/kingtest2
		<?php 
echo Helper::fieldTips('如果你已知道数据编号,可用 #编号 来搜索数据,如:#12');
?>
		<?php 
echo CHtml::endForm();
?>
	</div>
	
	<div class="clearfix">

		<?php 
echo CHtml::form(array('batchDelete'), 'post', array('id' => "form", 'onsubmit' => 'batchDelete("确认要删除选中数据吗?", this, "brand_id[]"); return false;'));
?>

		<?php 
$this->widget('zii.widgets.grid.CGridView', array('pager' => array('cssFile' => false), 'cssFile' => false, 'htmlOptions' => array('class' => 'list-view'), 'itemsCssClass' => 'list tree-table', 'loadingCssClass' => 'list-view-loading', 'dataProvider' => $dataProvider, 'selectableRows' => 2, 'columns' => array(array('class' => 'CCheckBoxColumn', 'id' => 'brand_id', 'headerHtmlOptions' => array('style' => 'width:20px;'), 'htmlOptions' => array('align' => 'center')), array('name' => 'brand_id', 'headerHtmlOptions' => array('style' => 'width:80px;'), 'htmlOptions' => array('align' => 'center')), array('name' => 'image_path', 'header' => '缩略图', 'value' => 'CHtml::image($data->getBrandFileUrl(),$data->brand_id,array("width"=>200,"height"=>100))', 'type' => 'raw', 'headerHtmlOptions' => array('style' => 'width:20%;'), 'htmlOptions' => array('class' => 'id-column', 'align' => 'center')), array('name' => 'title', 'value' => '$data->getI18nColumn("title", true)', 'evaluateHtmlOptions' => true, 'htmlOptions' => array('class' => '"{$data->getClass($data->is_recommend)}"'), 'type' => 'html'), array('name' => 'region_id', 'value' => '$data->region!=null?$data->region->title:"未知"', 'headerHtmlOptions' => array('style' => 'width:80px;'), 'htmlOptions' => array('align' => 'center')), array('class' => 'CButtonColumn', 'header' => Brand::model()->getAttributeLabel('sort_order'), 'headerHtmlOptions' => array('style' => 'width:100px;'), 'htmlOptions' => array('align' => 'center'), 'template' => '{sort_first} {sort_previous} {sort_next} {sort_last} {sort_specify}', 'buttons' => array('sort_first' => array('label' => '置顶', 'url' => 'array("sortFirst", "id" => $data->primaryKey)', 'click' => 'function(){ Sort.toFirst(this); return false; }', 'imageUrl' => 'image/sort_first.png'), 'sort_previous' => array('label' => '向上', 'url' => 'array("sortPrevious", "id" => $data->primaryKey)', 'click' => 'function(){ Sort.toPrevious(this); return false; }', 'imageUrl' => 'image/sort_previous.png'), 'sort_next' => array('label' => '向下', 'url' => 'array("sortNext", "id" => $data->primaryKey)', 'click' => 'function(){ Sort.toNext(this); return false; }', 'imageUrl' => 'image/sort_next.png'), 'sort_last' => array('label' => '置低', 'url' => 'array("sortLast", "id" => $data->primaryKey)', 'click' => 'function(){ Sort.toLast(this); return false; }', 'imageUrl' => 'image/sort_last.png'), 'sort_specify' => array('label' => '指定位置', 'url' => 'array("sortSpecify", "id" => $data->primaryKey)', 'click' => 'function(){ Sort.toSpecify(this); return false; }', 'imageUrl' => 'image/sort_specify.png')), 'visible' => Yii::app()->user->checkAccess('updateBrand')), array('name' => 'sort_order', 'header' => Brand::model()->getAttributeLabel('sort_order') . '2', 'headerHtmlOptions' => array('style' => 'width:90px;'), 'htmlOptions' => array('align' => 'center'), 'value' => 'CHtml::textField("sort_order_" . $data->primaryKey, $data->sort_order, array("class" => "sort-field"))', 'type' => 'raw', 'visible' => Yii::app()->user->checkAccess('updateBrand')), array('class' => 'CButtonColumn', 'header' => '操作', 'headerHtmlOptions' => array('style' => 'width:100px;'), 'htmlOptions' => array('align' => 'center'), 'template' => '{update} {delete} {common}', 'buttons' => array('common' => array('label' => '首页推荐', 'imageUrl' => Yii::app()->request->baseUrl . '/image/common.gif', 'url' => 'array("commend", "id" => $data->primaryKey)'), 'update' => array('url' => 'array("update", "id" => $data->primaryKey, "return_url" => Yii::app()->request->url)', 'visible' => 'Yii::app()->user->checkAccess("updateBrand")'), 'delete' => array('visible' => 'Yii::app()->user->checkAccess("deleteBrand")'))))));
?>

		<?php 
if (Yii::app()->user->checkAccess('deleteBrand')) {
    ?>
		<input type="submit" value="删除选中项" />	
		<input type="button" value="推荐选中项" onclick="recommendFn();" />
		<input type="button" value="取消推荐选中项" onclick="unRecommendFn();" />
		<?php 
}
?>

		<?php 
echo CHtml::endForm();
?>
コード例 #17
0
 protected function getCatalog()
 {
     /* Украсть католог с http://www.carexpert.ru/
     		/* С концептами, но без ранее выпускавшихся моделей */
     $brands = Brand::model()->findAll();
     foreach ($brands as $brand) {
         $brand_title = $brand->title;
         $brand_alias = $brand->alias;
         $ch = curl_init();
         // set URL and other appropriate options
         curl_setopt($ch, CURLOPT_URL, 'http://www.carexpert.ru/' . $brand->alias . '.htm');
         #d('http://www.carexpert.ru/'.$brand->alias.'.htm');
         curl_setopt($ch, CURLOPT_HEADER, 0);
         curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
         // grab URL and pass it to the browser
         $html = curl_exec($ch);
         // close cURL resource, and free up system resources
         curl_close($ch);
         $html = iconv('windows-1251', 'UTF-8', $html);
         preg_match_all('|(/models/(.*)\\.htm)(:?[^"]*)>(.*)</a|Ui', $html, $out, PREG_PATTERN_ORDER);
         foreach ($out[1] as $i => $m) {
             $model_title = $out[4][$i];
             $model_alias = $out[2][$i];
             $ch = curl_init();
             // set URL and other appropriate options
             curl_setopt($ch, CURLOPT_URL, 'http://www.carexpert.ru' . $m);
             #d('http://www.carexpert.ru'.$m);
             curl_setopt($ch, CURLOPT_HEADER, 0);
             curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
             // grab URL and pass it to the browser
             $html = curl_exec($ch);
             // close cURL resource, and free up system resources
             curl_close($ch);
             $html = iconv('windows-1251', 'UTF-8', $html);
             preg_match_all('|(/models/tech/(.*)\\.htm)(:?[^"]*)>(.*)</a|Ui', $html, $out1, PREG_PATTERN_ORDER);
             #d($brand_title.' '.$brand_alias);
             #d($model_title.' '.$model_alias);
             #d($out1, true);
             foreach ($out1[1] as $i1 => $t) {
                 $mod_title = $out1[4][$i1];
                 $mod_alias = $out1[2][$i1];
                 $ch = curl_init();
                 // set URL and other appropriate options
                 curl_setopt($ch, CURLOPT_URL, 'http://www.carexpert.ru' . $t);
                 d('http://www.carexpert.ru' . $t);
                 curl_setopt($ch, CURLOPT_HEADER, 0);
                 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                 // grab URL and pass it to the browser
                 $html = curl_exec($ch);
                 // close cURL resource, and free up system resources
                 curl_close($ch);
                 $html = iconv('windows-1251', 'UTF-8', $html);
                 preg_match_all("|Общие данные(.*)</table>|siU", $html, $out3, PREG_PATTERN_ORDER);
                 $tmp = new Tmp();
                 $tmp->brand = trim($brand_title);
                 $tmp->brand_alias = trim($brand_alias);
                 $tmp->model = trim($model_title);
                 $tmp->model_alias = trim($model_alias);
                 $tmp->mod = trim($mod_title);
                 $tmp->mod_alias = trim($mod_alias);
                 $tmp->techs_table = '<table><tr><td>' . $out3[0][0];
                 $tmp->url = 'http://www.carexpert.ru' . $t;
                 if (!Tmp::model()->exists('url=:url', array(':url' => $tmp->url))) {
                     $tmp->save();
                 }
                 $tmp->save();
             }
         }
     }
 }
コード例 #18
0
ファイル: Category.php プロジェクト: conghua1013/yii
 /**
  * 获取分类的品牌选项
  * @param $filter
  * @return string
  */
 public function getOptionBrands($filter)
 {
     $field = 'p.brand_id as id';
     $group = 'p.brand_id';
     $list = Yii::app()->shop->createCommand()->select($field)->from('bg_product p')->leftJoin('bg_category c', 'p.cat_id = c.id')->where($filter['option_where'])->group($group)->queryAll();
     if (empty($list)) {
         return '';
     }
     $brandList = Brand::model()->getBrandList();
     foreach ($list as &$value) {
         $value['brand_name'] = isset($brandList[$value['id']]) ? $brandList[$value['id']]['brand_name'] : '';
     }
     return $list;
 }
コード例 #19
0
 /**
  * 切换品牌状态
  * @return bool
  */
 public function ActionAjaxChangeBrandValid()
 {
     $id = $_POST['id'];
     // 获取要修改的品牌ID
     $valid = $_POST['valid'];
     // 获取该品牌当前的状态 [0:禁用 / 1:启用]
     $valid = $valid == 0 ? 1 : 0;
     $brand_model = Brand::model();
     $brand_info = $brand_model->findByPk($id);
     // 查询更改的品牌信息
     // 执行更新
     if ($brand_info->updateByPk($id, array('Valid' => $valid)) > 0) {
         // 添加操作日志 [S]
         $log = Yii::app()->user->name . '于 ' . date('Y-m-d H:i:s', time()) . ' ' . ($valid == 0 ? '禁用了' : '启用了') . ' 【' . $brand_info['BrandName'] . '】 品牌';
         OperationLogManage::AddOperationLog($log);
         // 添加日志
         // 添加操作日志 [E]
         echo true;
     } else {
         echo false;
     }
 }
コード例 #20
0
ファイル: _form.php プロジェクト: rodespsan/LMEC
						$("#Order_equipment_type_id").children().remove();
						$("#Order_equipment_type_id").append( new Option("Seleccionar"));
						$("#Order_brand_id > option[value=]").attr("selected","selected");
					}')));
?>
		<?php 
echo $form->error($model, 'equipment_type_id');
?>
	</div>
	
	<div class="row">
		<?php 
echo $form->labelEx($model, 'brand_id');
?>
		<?php 
echo $form->dropDownList($model, 'brand_id', CHtml::listData(Brand::model()->findAll(array('condition' => 'active=1', 'order' => 'name')), 'id', 'name'), array('prompt' => 'Seleccionar', 'ajax' => array('type' => 'POST', 'url' => CController::createUrl('order/modelsFromBrand'), 'data' => array('Order[brand_id]' => 'js:this.value', 'Order[equipment_type_id]' => 'js:  $("#Order_equipment_type_id").val()'), 'success' => 'js:function(dataType){
						jsonObject = JSON.parse(dataType);
						
						$("#Order_model_id").children().remove();
						$("#Order_model_id").append( new Option("Seleccionar", 0));
						
						for(i=0; i< jsonObject.models_options.length; i++){
							$("#Order_model_id").append( new Option(
								jsonObject.models_options[i].name,
								jsonObject.models_options[i].id
							));
						}
					}', 'error' => 'js:function(dataType){
						$("#Order_equipment_type_id").children().remove();
						$("#Order_equipment_type_id").append( new Option("Seleccionar"));
						$("#Order_brand_id > option[value=]").attr("selected","selected");
コード例 #21
0
 /**
  * 类型添加
  */
 public function actionCreate()
 {
     if ($_POST) {
         $GoodsType = new GoodsType();
         $GoodsType->attributes = $this->post('Type');
         $type_brand_attributes = $this->post('TypeBrand');
         //商品类型主表修改
         $result = $GoodsType->save();
         if (!$result) {
             $GoodsType = new GoodsType();
             $this->message('error', CHtml::errorSummary($GoodsType), $this->createUrl('index'));
         }
         $type_id = Yii::app()->db->getLastInsertID();
         //类型-品牌
         if ($type_brand_attributes) {
             $TypeBrand = new TypeBrand();
             $result = $TypeBrand->brand_type_update($type_id, $type_brand_attributes);
             if (!$result) {
                 $this->message('error', CHtml::errorSummary($TypeBrand), $this->createUrl('index'));
             }
         }
         //类型-扩展属性
         $type_props_attributes = $this->post('TypeProps');
         if (isset($type_props_attributes['props_id']) && $type_props_attributes['props_id']) {
             $GoodsTypePropsRelation = new GoodsTypePropsRelation();
             $result = $GoodsTypePropsRelation->props_update($type_id, $type_props_attributes['props_id']);
             if (!$result) {
                 $this->message('error', CHtml::errorSummary($GoodsTypePropsRelation), $this->createUrl('index'));
             }
         }
         //类型-规格
         $type_props_spec = $this->post('Spec');
         if (isset($type_props_spec['spec_id']) && $type_props_spec['spec_id']) {
             $GoodsTypeSpec = new GoodsTypeSpec();
             $result = $GoodsTypeSpec->spec_update($type_id, $type_props_spec['spec_id']);
             if (!$result) {
                 $this->message('error', CHtml::errorSummary($GoodsTypeSpec), $this->createUrl('index'));
             }
         }
         $this->message('success', '创建成功', $this->createUrl('index'));
     }
     //品牌列表
     $model['brand_list'] = Brand::model()->findAll('disabled = :disabled', array(':disabled' => 'false'));
     //规格
     $model['spec_list'] = Specification::model()->findAll('disabled = :disabled', array(':disabled' => 'false'));
     $this->render('create', array('model' => $model));
 }
コード例 #22
0
 public function actionIndex($id = false)
 {
     $models = new CsvUpload();
     if ($id == 1) {
         if (isset($_POST['CsvUpload']['photo_img'])) {
             if ($files = CUploadedFile::getInstances($models, 'photo_img')) {
                 $array = array();
                 foreach ($files as $img) {
                     $filename = $img->name;
                     $img->saveAs('upload/images' . '/' . $filename);
                 }
             }
         }
         if (isset($_POST['yt0'])) {
             $brand = ModelCategory::model()->findAll('category_id = :id', array(':id' => $id));
             $arr = array();
             foreach ($brand as $item) {
                 $arr[] = $item->brand_id;
             }
             $criteria = new CDbCriteria();
             $criteria->addInCondition('brand_id', $arr);
             $model = Models::model()->findAll($criteria);
             foreach ($model as $item) {
                 $array_model_id[] = $item->id;
             }
             if (isset($array_model_id[0])) {
                 $criteria_model_id = new CDbCriteria();
                 $criteria_model_id->addInCondition('model_id', $array_model_id);
                 $characteristics = CharacteristicValue::model()->findAll($criteria_model_id);
                 $file_name = 'export.csv';
                 // название файла
                 $file = fopen($file_name, "w");
                 // открываем файл для записи, если его нет, то создаем его в текущей папке, где расположен скрипт
                 $csv_file = array('Артикул', 'Название бренда', 'Название модели', 'Цена', 'Старая цена', 'Главная фотография', 'Другие фотографии', 'Количество', 'Описание', 'Сопутствующие товары', 'Топ продаж', 'Акция', 'Новинка', 'Лучшая цена', 'Тип', 'Форм-фактор', 'Операционная система', 'Количество SIM-карт', 'Стандарты связи', 'Формат SIM-карты', 'Материал корпуса', 'Степень защиты', 'Цвет', 'Диагональ экрана', 'Разрешение экрана', 'Тип экрана', 'Количество цветов экрана', 'Тип процессора', 'Количесво ядер', 'Частота процессора', 'Основная камера', 'Фронтальная камера', 'Встроенная вспышка', 'Оперативная память', 'Встроенная память', 'Поддержка карт памяти', 'Wi-Fi', 'Bluetooth', 'GPS', 'NFC', 'MP3-проигрыватель', 'FM-тюнер', 'SMS/MMS/Email', 'Интерфейс', 'Разъем для наушников', 'Емкость аккумулятора', 'Размеры и вес', 'Комплектация', 'Гарантийный срок', 'Возврат и обмен товара', 'Дополнительно');
                 $csv_file = explode("^", iconv('UTF-8', 'Windows-1251', implode("^", $csv_file)));
                 fputcsv($file, $csv_file, ";");
                 // записываем в файл заголовки
                 foreach ($model as $item) {
                     $csv_file = array($item->vendor_code, $item->brandModel->brand, $item->model_name, $item->price, $item->old_price, $item->photo, is_array(json_decode($item->photo_other)) ? implode(', ', json_decode($item->photo_other)) : json_decode($item->photo_other), $item->quantity, $item->description, is_array(json_decode($item->accessories)) ? implode(', ', json_decode($item->accessories)) : $item->accessories, $item->top, $item->promotion, $item->novelty, $item->bestPrice);
                     foreach ($characteristics as $characteristic) {
                         if ($item->id == $characteristic->model_id) {
                             if (isset($characteristic->value)) {
                                 array_push($csv_file, $characteristic->value);
                             } else {
                                 array_push($csv_file, "");
                             }
                         }
                     }
                     $csv_file = explode("^", iconv('UTF-8', 'Windows-1251', implode("^", $csv_file)));
                     fputcsv($file, $csv_file, ";");
                     // записываем в файл строки
                 }
                 fclose($file);
                 // закрываем файл
                 // задаем заголовки. то есть задаем всплывающее окошко, которое позволяет нам сохранить файл.
                 header('Content-type: application/csv');
                 // указываем, что это csv документ
                 header("Content-Disposition: attachment; filename=" . $file_name);
                 // указываем файл, с которым будем работать
                 readfile($file_name);
                 // считываем файл
                 unlink($file_name);
                 // удаляем файл. то есть когда вы сохраните файл на локальном компе, то после он удалится с сервера
                 Yii::app()->end();
             } else {
                 Yii::app()->user->setFlash('status', 'База пустая!');
             }
         }
         // загрузка из файла
         if (isset($_POST['CsvUpload'])) {
             $brand = ModelCategory::model()->findAll('category_id = :id', array(':id' => $id));
             $arr = array();
             foreach ($brand as $item) {
                 $arr[] = $item->brand_id;
             }
             $criteria = new CDbCriteria();
             $criteria->addInCondition('id', $arr);
             $model = Brand::model()->findAll($criteria);
             // получаем данные из формы
             if ($file = CUploadedFile::getInstance($models, 'csv')) {
                 $extension = strtolower($file->extensionName);
                 $filename = 'import_csv';
                 $basename = $filename . '.' . $extension;
                 $file->saveAs('upload/csv' . '/' . $basename);
                 $path_csv = Yii::app()->request->baseUrl . 'upload/csv/' . $basename;
                 if (($handle = fopen($path_csv, "r")) !== false) {
                     $modelCharacteristicValue = new CharacteristicValue();
                     $modelCharacteristics = Characteristics::model()->findAll('category_id = :id', array(':id' => $id));
                     $modelModelsOld = Models::model()->findAll();
                     $counter = 0;
                     while (($data = fgetcsv($handle, 5000, ";")) !== false) {
                         $brand_tel = iconv('Windows-1251', 'UTF-8', $data[1]);
                         $counter++;
                         if ($counter == 1) {
                             continue;
                         }
                         // если есть такой бренд, то продолжаем
                         $modelModels = new Models();
                         $i = 0;
                         foreach ($model as $item) {
                             if (trim(strtolower($item->brand)) == trim(strtolower($brand_tel))) {
                                 $i = 1;
                                 $modelModels->brand_id = $item->id;
                                 $brand_id_update = $item->id;
                             }
                         }
                         // если бренда нет, идем на следующую итерацию
                         if ($i == 0) {
                             continue;
                         }
                         $reset_while = 0;
                         foreach ($modelModelsOld as $itemid) {
                             $vendor = iconv('Windows-1251', 'UTF-8', isset($data[0]) ? $data[0] : '');
                             //если запись уже есть в базе, обновляем
                             if ($itemid->vendor_code == $vendor) {
                                 $description = iconv('Windows-1251', 'UTF-8', isset($data[8]) ? $data[8] : '');
                                 $cena = str_replace(",", '.', isset($data[3]) ? $data[3] : '');
                                 $cena = preg_replace("/[^x\\d|*\\.]/", "", $cena);
                                 $old_cena = str_replace(",", '.', isset($data[4]) ? $data[4] : '');
                                 $old_cena = preg_replace("/[^x\\d|*\\.]/", "", $old_cena);
                                 //$accessories = iconv('Windows-1251', 'UTF-8', $data[9]);
                                 $model_name = iconv('Windows-1251', 'UTF-8', isset($data[2]) ? $data[2] : '');
                                 $photo_other = explode(',', mb_convert_encoding(isset($data[6]) ? $data[6] : '', 'UTF-8'));
                                 $photo_other_arr = array();
                                 foreach ($photo_other as $item) {
                                     $photo_other_arr[] = trim($item);
                                 }
                                 $acces = explode(',', mb_convert_encoding(isset($data[9]) ? $data[9] : '', 'UTF-8'));
                                 $accessories = array();
                                 foreach ($acces as $item) {
                                     $accessories[] = trim($item);
                                 }
                                 $sql[] = '(\'' . $vendor . '\', 
                                        \'' . $model_name . '\', 
                                        \'"' . $cena . '\', 
                                        \'' . $old_cena . '\', 
                                        \'' . $brand_id_update . '\', 
                                        \'' . (isset($data[5]) ? $data[5] : '') . '\', 
                                        \'' . ($photo_other_arr[0] != '' ? json_encode($photo_other_arr) : '') . '\',
                                        \'' . (isset($data[7]) ? $data[7] : '') . '\',
                                        \'' . $description . '\',
                                        \'' . json_encode($accessories) . '\',
                                        \'' . (isset($data[10]) ? $data[10] : '') . '\',
                                        \'' . (isset($data[11]) ? $data[11] : '') . '\',
                                        \'' . (isset($data[12]) ? $data[12] : '') . '\',
                                        \'' . (isset($data[13]) ? $data[13] : '') . '\'
                                        )';
                                 $id_update = $itemid->id;
                                 $j = 14;
                                 foreach ($modelCharacteristics as $k => $items) {
                                     if ($items->parent_id != 0 && isset($data[$j])) {
                                         $value = $data[$j] != '' ? iconv('Windows-1251', 'UTF-8', $data[$j]) : '';
                                         $sql_char[] = '(\'' . $value . '\', \'' . $items->id . '\', \'' . $id_update . '\')';
                                         $j++;
                                     }
                                     if ($j == 51) {
                                         break;
                                     }
                                 }
                                 $reset_while = 1;
                             }
                         }
                         // если обновили, пропускаем итерацию
                         if ($reset_while == 1) {
                             continue;
                         }
                         // если нет, записываем новые данные
                         $vendor = iconv('Windows-1251', 'UTF-8', isset($data[0]) ? $data[0] : '');
                         $model_name = iconv('Windows-1251', 'UTF-8', isset($data[2]) ? $data[2] : '');
                         $modelModels->vendor_code = $vendor;
                         $modelModels->model_name = $model_name;
                         $cena = str_replace(",", '.', isset($data[3]) ? $data[3] : '');
                         $cena = preg_replace("/[^x\\d|*\\.]/", "", $cena);
                         $old_cena = str_replace(",", '.', isset($data[4]) ? $data[4] : '');
                         $old_cena = preg_replace("/[^x\\d|*\\.]/", "", $old_cena);
                         $photo_other = explode(',', mb_convert_encoding(isset($data[6]) ? $data[6] : '', 'UTF-8'));
                         $photo_other_arr = array();
                         foreach ($photo_other as $item) {
                             $photo_other_arr[] = trim($item);
                         }
                         $acces = explode(',', mb_convert_encoding(isset($data[9]) ? $data[9] : '', 'UTF-8'));
                         $accessories = array();
                         foreach ($acces as $item) {
                             $accessories[] = trim($item);
                         }
                         $modelModels->price = $cena;
                         $modelModels->old_price = $old_cena;
                         $modelModels->photo = isset($data[5]) ? $data[5] : '';
                         $modelModels->photo_other = $photo_other_arr[0] != '' ? json_encode($photo_other_arr) : '';
                         $modelModels->quantity = isset($data[7]) ? $data[7] : '';
                         $description = iconv('Windows-1251', 'UTF-8', isset($data[8]) ? $data[8] : '');
                         $modelModels->description = $description;
                         $modelModels->accessories = json_encode($accessories);
                         $modelModels->top = isset($data[10]) ? $data[10] : '';
                         $modelModels->promotion = isset($data[11]) ? $data[11] : '';
                         $modelModels->novelty = isset($data[12]) ? $data[12] : '';
                         $modelModels->bestPrice = isset($data[13]) ? $data[13] : '';
                         if ($modelModels->save(false)) {
                             $id_model = $modelModels->id;
                             $j = 14;
                             foreach ($modelCharacteristics as $k => $item) {
                                 if ($item->parent_id != 0 && isset($data[$j])) {
                                     $modelCharacteristicValue->id = false;
                                     $modelCharacteristicValue->isNewRecord = true;
                                     $value = $data[$j] ? iconv('Windows-1251', 'UTF-8', $data[$j]) : '';
                                     $modelCharacteristicValue->value = $value;
                                     $modelCharacteristicValue->characteristic_id = $item->id;
                                     $modelCharacteristicValue->model_id = $id_model;
                                     if ($modelCharacteristicValue->save(false)) {
                                         $j++;
                                     }
                                 }
                                 if ($j == 51) {
                                     break;
                                 }
                             }
                         }
                     }
                     fclose($handle);
                     unlink($path_csv);
                 }
                 if (isset($sql[0])) {
                     $sql_implode = implode(', ', $sql);
                     $sql_query_models = 'INSERT INTO cms_temp_models (vendor_code,
                                                                       model_name,
                                                                       price,
                                                                       old_price,
                                                                       brand_id,
                                                                       photo,
                                                                       photo_other,
                                                                       quantity,
                                                                       description,
                                                                       accessories,
                                                                       top,
                                                                       promotion,
                                                                       novelty,
                                                                       bestPrice
                                                                       ) VALUES ' . $sql_implode;
                     $connection = Yii::app()->db;
                     $connection->createCommand($sql_query_models)->execute();
                     $sql_query_update = 'update cms_models u
                     inner join cms_temp_models s on
                         u.vendor_code = s.vendor_code
                     set u.model_name = s.model_name,
                         u.price = s.price,
                         u.old_price = s.old_price,
                         u.brand_id = s.brand_id,
                         u.photo = s.photo,
                         u.photo_other = s.photo_other,
                         u.quantity = s.quantity,
                         u.description = s.description,
                         u.accessories = s.accessories,
                         u.top = s.top,
                         u.promotion = s.promotion,
                         u.novelty = s.novelty,
                         u.bestPrice = s.bestPrice';
                     $connection->createCommand($sql_query_update)->execute();
                     $connection->createCommand()->truncateTable('cms_temp_models');
                     if (isset($sql_char)) {
                         $sql_implode_char = implode(', ', $sql_char);
                         $sql_query_models = 'INSERT INTO cms_temp_characteristicValue (value, characteristic_id, model_id) 
                                              VALUES ' . $sql_implode_char;
                         $connection = Yii::app()->db;
                         $connection->createCommand($sql_query_models)->execute();
                         $sql_query_update_char = 'UPDATE cms_characteristicValue u
                         INNER JOIN cms_temp_characteristicValue s ON
                             (u.characteristic_id = s.characteristic_id) AND (u.model_id = s.model_id)
                         SET u.value = s.value';
                         $connection->createCommand($sql_query_update_char)->execute();
                         $connection->createCommand()->truncateTable('cms_temp_characteristicValue');
                     }
                 }
                 // сообщение о завершении загрузки
                 Yii::app()->user->setFlash('status', 'Файл загружен, данные добавлены!');
             }
         }
     }
     if ($id == 2) {
         if (isset($_POST['CsvUpload']['photo_img'])) {
             if ($files = CUploadedFile::getInstances($models, 'photo_img')) {
                 $array = array();
                 foreach ($files as $img) {
                     $filename = $img->name;
                     //$filename = mb_convert_encoding($filename, 'Windows-1251', 'UTF-8');
                     $img->saveAs('upload/images' . '/' . $filename);
                 }
             }
         }
         if (isset($_POST['yt0'])) {
             $brand = ModelCategory::model()->findAll('category_id = :id', array(':id' => $id));
             $arr = array();
             foreach ($brand as $item) {
                 $arr[] = $item->brand_id;
             }
             $criteria = new CDbCriteria();
             $criteria->addInCondition('brand_id', $arr);
             $model = Models::model()->findAll($criteria);
             foreach ($model as $item) {
                 $array_model_id[] = $item->id;
             }
             if (isset($array_model_id[0])) {
                 $criteria_model_id = new CDbCriteria();
                 $criteria_model_id->addInCondition('model_id', $array_model_id);
                 $characteristics = CharacteristicValue::model()->findAll($criteria_model_id);
                 $file_name = 'export.csv';
                 // название файла
                 $file = fopen($file_name, "w");
                 // открываем файл для записи, если его нет, то создаем его в текущей папке, где расположен скрипт
                 $csv_file = array('Артикул', 'Название бренда', 'Название модели', 'Цена', 'Старая цена', 'Главная фотография', 'Другие фотографии', 'Количество', 'Описание', 'Сопутствующие товары', 'Топ продаж', 'Акция', 'Новинка', 'Лучшая цена', 'Тип', 'Операционная система', 'Количество SIM-карт', 'Стандарты связи', 'Материал корпуса', 'Цвет', 'Диагональ экрана', 'Разрешение экрана', 'Тип экрана', 'Тип процессора', 'Количесво ядер', 'Частота процессора', 'Основная камера', 'Фронтальная камера', 'Оперативная память', 'Встроенная память', 'Поддержка карт памяти', 'Wi-Fi', 'Bluetooth', 'GPS', 'NFC', 'Интерфейс', 'Разъем для наушников', 'Емкость аккумулятора', 'Размеры и вес', 'Комплектация', 'Гарантийный срок', 'Возврат и обмен товара', 'Дополнительно');
                 $csv_file = explode("^", iconv('UTF-8', 'Windows-1251', implode("^", $csv_file)));
                 fputcsv($file, $csv_file, ";");
                 // записываем в файл заголовки
                 foreach ($model as $item) {
                     $csv_file = array($item->vendor_code, $item->brandModel->brand, $item->model_name, $item->price, $item->old_price, $item->photo, is_array(json_decode($item->photo_other)) ? implode(', ', json_decode($item->photo_other)) : json_decode($item->photo_other), $item->quantity, $item->description, is_array(json_decode($item->accessories)) ? implode(', ', json_decode($item->accessories)) : $item->accessories, $item->top, $item->promotion, $item->novelty, $item->bestPrice);
                     foreach ($characteristics as $characteristic) {
                         if ($item->id == $characteristic->model_id) {
                             if (isset($characteristic->value)) {
                                 array_push($csv_file, $characteristic->value);
                             } else {
                                 array_push($csv_file, "");
                             }
                         }
                     }
                     $csv_file = explode("^", iconv('UTF-8', 'Windows-1251', implode("^", $csv_file)));
                     fputcsv($file, $csv_file, ";");
                     // записываем в файл строки
                 }
                 fclose($file);
                 // закрываем файл
                 // задаем заголовки. то есть задаем всплывающее окошко, которое позволяет нам сохранить файл.
                 header('Content-type: application/csv');
                 // указываем, что это csv документ
                 header("Content-Disposition: attachment; filename=" . $file_name);
                 // указываем файл, с которым будем работать
                 readfile($file_name);
                 // считываем файл
                 unlink($file_name);
                 // удаляем файл. то есть когда вы сохраните файл на локальном компе, то после он удалится с сервера
                 Yii::app()->end();
             } else {
                 Yii::app()->user->setFlash('status', 'База пустая!');
             }
         }
         if (isset($_POST['CsvUpload'])) {
             $brand = ModelCategory::model()->findAll('category_id = :id', array(':id' => $id));
             $arr = array();
             foreach ($brand as $item) {
                 $arr[] = $item->brand_id;
             }
             $criteria = new CDbCriteria();
             $criteria->addInCondition('id', $arr);
             $model = Brand::model()->findAll($criteria);
             // получаем данные из формы
             if ($file = CUploadedFile::getInstance($models, 'csv')) {
                 $extension = strtolower($file->extensionName);
                 $filename = 'import_csv';
                 $basename = $filename . '.' . $extension;
                 $file->saveAs('upload/csv' . '/' . $basename);
                 $path_csv = Yii::app()->request->baseUrl . 'upload/csv/' . $basename;
                 if (($handle = fopen($path_csv, "r")) !== false) {
                     $modelCharacteristicValue = new CharacteristicValue();
                     $modelCharacteristics = Characteristics::model()->findAll('category_id = :id', array(':id' => $id));
                     $modelModelsOld = Models::model()->findAll();
                     $counter = 0;
                     while (($data = fgetcsv($handle, 5000, ";")) !== false) {
                         $brand_pl = iconv('Windows-1251', 'UTF-8', $data[1]);
                         $counter++;
                         if ($counter == 1) {
                             continue;
                         }
                         // если есть такой бренд, то продолжаем
                         $modelModels = new Models();
                         $i = 0;
                         foreach ($model as $item) {
                             if (trim(strtolower($item->brand)) == trim(strtolower($brand_pl))) {
                                 $i = 1;
                                 $modelModels->brand_id = $item->id;
                                 $brand_id_update = $item->id;
                             }
                         }
                         // если бренда нет, идем на следующую итерацию
                         if ($i == 0) {
                             continue;
                         }
                         $reset_while = 0;
                         foreach ($modelModelsOld as $itemid) {
                             //если запись уже есть в базе, обновляем
                             $vendor = iconv('Windows-1251', 'UTF-8', isset($data[0]) ? $data[0] : '');
                             //если запись уже есть в базе, обновляем
                             if ($itemid->vendor_code == $vendor) {
                                 $description = iconv('Windows-1251', 'UTF-8', isset($data[8]) ? $data[8] : '');
                                 $cena = str_replace(",", '.', isset($data[3]) ? $data[3] : '');
                                 $cena = preg_replace("/[^x\\d|*\\.]/", "", $cena);
                                 $old_cena = str_replace(",", '.', isset($data[4]) ? $data[4] : '');
                                 $old_cena = preg_replace("/[^x\\d|*\\.]/", "", $old_cena);
                                 //$accessories = iconv('Windows-1251', 'UTF-8', $data[9]);
                                 $model_name = iconv('Windows-1251', 'UTF-8', isset($data[2]) ? $data[2] : '');
                                 $photo_other = explode(',', mb_convert_encoding(isset($data[6]) ? $data[6] : '', 'UTF-8'));
                                 $photo_other_arr = array();
                                 foreach ($photo_other as $item) {
                                     $photo_other_arr[] = trim($item);
                                 }
                                 $acces = explode(',', mb_convert_encoding(isset($data[9]) ? $data[9] : '', 'UTF-8'));
                                 $accessories = array();
                                 foreach ($acces as $item) {
                                     $accessories[] = trim($item);
                                 }
                                 $sql[] = '(\'' . $vendor . '\', 
                                        \'' . $model_name . '\', 
                                        \'"' . $cena . '\', 
                                        \'' . $old_cena . '\', 
                                        \'' . $brand_id_update . '\', 
                                        \'' . (isset($data[5]) ? $data[5] : '') . '\', 
                                        \'' . ($photo_other_arr[0] != '' ? json_encode($photo_other_arr) : '') . '\',
                                        \'' . (isset($data[7]) ? $data[7] : '') . '\',
                                        \'' . $description . '\',
                                        \'' . json_encode($accessories) . '\',
                                        \'' . (isset($data[10]) ? $data[10] : '') . '\',
                                        \'' . (isset($data[11]) ? $data[11] : '') . '\',
                                        \'' . (isset($data[12]) ? $data[12] : '') . '\',
                                        \'' . (isset($data[13]) ? $data[13] : '') . '\'
                                        )';
                                 $id_update = $itemid->id;
                                 $j = 14;
                                 foreach ($modelCharacteristics as $k => $items) {
                                     if ($items->parent_id != 0 && isset($data[$j])) {
                                         $value = iconv('Windows-1251', 'UTF-8', $data[$j]);
                                         $sql_char[] = '(\'' . $value . '\', \'' . $items->id . '\', \'' . $id_update . '\')';
                                         $j++;
                                     }
                                     if ($j == 44) {
                                         break;
                                     }
                                 }
                                 $reset_while = 1;
                             }
                         }
                         // если обновили, пропускаем итерацию
                         if ($reset_while == 1) {
                             continue;
                         }
                         // если нет, записываем новые данные
                         $vendor = iconv('Windows-1251', 'UTF-8', isset($data[0]) ? $data[0] : '');
                         $model_name = iconv('Windows-1251', 'UTF-8', isset($data[2]) ? $data[2] : '');
                         $modelModels->vendor_code = $vendor;
                         $modelModels->model_name = $model_name;
                         $cena = str_replace(",", '.', isset($data[3]) ? $data[3] : '');
                         $cena = preg_replace("/[^x\\d|*\\.]/", "", $cena);
                         $old_cena = str_replace(",", '.', isset($data[4]) ? $data[4] : '');
                         $old_cena = preg_replace("/[^x\\d|*\\.]/", "", $old_cena);
                         $photo_other = explode(',', mb_convert_encoding(isset($data[6]) ? $data[6] : '', 'UTF-8'));
                         $photo_other_arr = array();
                         foreach ($photo_other as $item) {
                             $photo_other_arr[] = trim($item);
                         }
                         $acces = explode(',', mb_convert_encoding(isset($data[9]) ? $data[9] : '', 'UTF-8'));
                         $accessories = array();
                         foreach ($acces as $item) {
                             $accessories[] = trim($item);
                         }
                         $modelModels->price = $cena;
                         $modelModels->old_price = $old_cena;
                         $modelModels->photo = isset($data[5]) ? $data[5] : '';
                         $modelModels->photo_other = $photo_other_arr[0] != '' ? json_encode($photo_other_arr) : '';
                         $modelModels->quantity = isset($data[7]) ? $data[7] : '';
                         $description = iconv('Windows-1251', 'UTF-8', isset($data[8]) ? $data[8] : '');
                         $modelModels->description = $description;
                         $modelModels->accessories = json_encode($accessories);
                         $modelModels->top = isset($data[10]) ? $data[10] : '';
                         $modelModels->promotion = isset($data[11]) ? $data[11] : '';
                         $modelModels->novelty = isset($data[12]) ? $data[12] : '';
                         $modelModels->bestPrice = isset($data[13]) ? $data[13] : '';
                         if ($modelModels->save(false)) {
                             $id_model = $modelModels->id;
                             $j = 14;
                             foreach ($modelCharacteristics as $k => $item) {
                                 if ($item->parent_id != 0 && isset($data[$j])) {
                                     $modelCharacteristicValue->id = false;
                                     $modelCharacteristicValue->isNewRecord = true;
                                     $value = iconv('Windows-1251', 'UTF-8', $data[$j]);
                                     $modelCharacteristicValue->value = $value;
                                     $modelCharacteristicValue->characteristic_id = $item->id;
                                     $modelCharacteristicValue->model_id = $id_model;
                                     if ($modelCharacteristicValue->save(false)) {
                                         $j++;
                                     }
                                 }
                                 if ($j == 44) {
                                     break;
                                 }
                             }
                         }
                     }
                     fclose($handle);
                     unlink($path_csv);
                 }
                 if (isset($sql[0])) {
                     $sql_implode = implode(', ', $sql);
                     $sql_query_models = 'INSERT INTO cms_temp_models (vendor_code,
                                                                       model_name,
                                                                       price,
                                                                       old_price,
                                                                       brand_id,
                                                                       photo,
                                                                       photo_other,
                                                                       quantity,
                                                                       description,
                                                                       accessories,
                                                                       top,
                                                                       promotion,
                                                                       novelty,
                                                                       bestPrice
                                                                       ) VALUES ' . $sql_implode;
                     $connection = Yii::app()->db;
                     $connection->createCommand($sql_query_models)->execute();
                     $sql_query_update = 'update cms_models u
                     inner join cms_temp_models s on
                         u.vendor_code = s.vendor_code
                     set u.model_name = s.model_name,
                         u.price = s.price,
                         u.old_price = s.old_price,
                         u.brand_id = s.brand_id,
                         u.photo = s.photo,
                         u.photo_other = s.photo_other,
                         u.quantity = s.quantity,
                         u.description = s.description,
                         u.accessories = s.accessories,
                         u.top = s.top,
                         u.promotion = s.promotion,
                         u.novelty = s.novelty,
                         u.bestPrice = s.bestPrice';
                     $connection->createCommand($sql_query_update)->execute();
                     $connection->createCommand()->truncateTable('cms_temp_models');
                     if (isset($sql_char)) {
                         $sql_implode_char = implode(', ', $sql_char);
                         $sql_query_models = 'INSERT INTO cms_temp_characteristicValue (value, characteristic_id, model_id) 
                                              VALUES ' . $sql_implode_char;
                         $connection = Yii::app()->db;
                         $connection->createCommand($sql_query_models)->execute();
                         $sql_query_update_char = 'UPDATE cms_characteristicValue u
                         INNER JOIN cms_temp_characteristicValue s ON
                             (u.characteristic_id = s.characteristic_id) AND (u.model_id = s.model_id)
                         SET u.value = s.value';
                         $connection->createCommand($sql_query_update_char)->execute();
                         $connection->createCommand()->truncateTable('cms_temp_characteristicValue');
                     }
                 }
                 // сообщение о завершении загрузки
                 Yii::app()->user->setFlash('status', 'Файл загружен, данные добавлены!');
             }
         }
     }
     if ($id == 3) {
         if (isset($_POST['CsvUpload']['photo_img'])) {
             if ($files = CUploadedFile::getInstances($models, 'photo_img')) {
                 $array = array();
                 foreach ($files as $img) {
                     $filename = $img->name;
                     $img->saveAs('upload/images' . '/' . $filename);
                 }
             }
         }
         if (isset($_POST['yt0'])) {
             $brand = ModelCategory::model()->findAll('category_id = :id', array(':id' => $id));
             $arr = array();
             foreach ($brand as $item) {
                 $arr[] = $item->brand_id;
             }
             $criteria = new CDbCriteria();
             $criteria->addInCondition('brand_id', $arr);
             $model = Models::model()->findAll($criteria);
             foreach ($model as $item) {
                 $array_model_id[] = $item->id;
             }
             if (isset($array_model_id[0])) {
                 $criteria_model_id = new CDbCriteria();
                 $criteria_model_id->addInCondition('model_id', $array_model_id);
                 $characteristics = CharacteristicValue::model()->findAll($criteria_model_id);
                 $file_name = 'export.csv';
                 // название файла
                 $file = fopen($file_name, "w");
                 // открываем файл для записи, если его нет, то создаем его в текущей папке, где расположен скрипт
                 $csv_file = array('Артикул', 'Название бренда', 'Название модели', 'Цена', 'Старая цена', 'Главная фотография', 'Другие фотографии', 'Количество', 'Описание', 'Сопутствующие товары', 'Топ продаж', 'Акция', 'Новинка', 'Лучшая цена', 'Тип', 'Операционная система', 'Материал корпуса', 'Цвет', 'Диагональ дисплея', 'Покрытие экрана', 'Разрешение дисплея', 'Процессор', 'Тип процессора', 'Количество ядер', 'Тип графическго адаптера', 'Объем видеокарты', 'Тип видеокарты', 'Объем оперативной памяти', 'Тип оперативной памяти', 'Объем дисков HDD', 'Объем дисков SSD', 'Оптический привод', 'Веб-камера', 'Микрофон', 'Встроенные динамики', 'WiFi', 'Bluetooth', 'Сетевой адаптер Ethernet', 'USB 2.0', 'USB 3.0', 'VGA', 'HDMI', 'Аудиоразъем', 'Разъем для микрофона', 'Емкость аккумулятора', 'Размеры и вес', 'Комплектация', 'Гарантийный срок', 'Возврат и обмен товара', 'Дополнительно');
                 $csv_file = explode("^", iconv('UTF-8', 'Windows-1251', implode("^", $csv_file)));
                 fputcsv($file, $csv_file, ";");
                 // записываем в файл заголовки
                 foreach ($model as $item) {
                     $csv_file = array(trim($item->vendor_code), trim($item->brandModel->brand), trim($item->model_name), trim($item->price), trim($item->old_price), trim($item->photo), is_array(json_decode($item->photo_other)) ? implode(', ', json_decode($item->photo_other)) : json_decode($item->photo_other), trim($item->quantity), trim($item->description), is_array(json_decode($item->accessories)) ? implode(', ', json_decode($item->accessories)) : $item->accessories, trim($item->top), trim($item->promotion), trim($item->novelty), trim($item->bestPrice));
                     foreach ($characteristics as $characteristic) {
                         if ($item->id == $characteristic->model_id) {
                             if (isset($characteristic->value)) {
                                 array_push($csv_file, $characteristic->value);
                             } else {
                                 array_push($csv_file, "");
                             }
                         }
                     }
                     $csv_file = explode("^", iconv('UTF-8', 'Windows-1251', implode("^", $csv_file)));
                     fputcsv($file, $csv_file, ";");
                     // записываем в файл строки
                 }
                 fclose($file);
                 // закрываем файл
                 // задаем заголовки. то есть задаем всплывающее окошко, которое позволяет нам сохранить файл.
                 header('Content-type: application/csv');
                 // указываем, что это csv документ
                 header("Content-Disposition: attachment; filename=" . $file_name);
                 // указываем файл, с которым будем работать
                 readfile($file_name);
                 // считываем файл
                 unlink($file_name);
                 // удаляем файл. то есть когда вы сохраните файл на локальном компе, то после он удалится с сервера
                 Yii::app()->end();
             } else {
                 Yii::app()->user->setFlash('status', 'База пустая!');
             }
         }
         // загрузка из файла
         if (isset($_POST['CsvUpload'])) {
             $brand = ModelCategory::model()->findAll('category_id = :id', array(':id' => $id));
             $arr = array();
             foreach ($brand as $item) {
                 $arr[] = $item->brand_id;
             }
             $criteria = new CDbCriteria();
             $criteria->addInCondition('id', $arr);
             $model = Brand::model()->findAll($criteria);
             // получаем данные из формы
             if ($file = CUploadedFile::getInstance($models, 'csv')) {
                 $extension = strtolower($file->extensionName);
                 $filename = 'import_csv';
                 $basename = $filename . '.' . $extension;
                 $file->saveAs('upload/csv' . '/' . $basename);
                 $path_csv = Yii::app()->request->baseUrl . 'upload/csv/' . $basename;
                 if (($handle = fopen($path_csv, "r")) !== false) {
                     $modelCharacteristicValue = new CharacteristicValue();
                     $modelCharacteristics = Characteristics::model()->findAll('category_id = :id', array(':id' => $id));
                     $modelModelsOld = Models::model()->findAll();
                     $counter = 0;
                     while (($data = fgetcsv($handle, 5000, ";")) !== false) {
                         $brand_tel = iconv('Windows-1251', 'UTF-8', $data[1]);
                         $counter++;
                         if ($counter == 1) {
                             continue;
                         }
                         // если есть такой бренд, то продолжаем
                         $modelModels = new Models();
                         $i = 0;
                         foreach ($model as $item) {
                             if (trim(strtolower($item->brand)) == trim(strtolower($brand_tel))) {
                                 $i = 1;
                                 $modelModels->brand_id = $item->id;
                                 $brand_id_update = $item->id;
                             }
                         }
                         // если бренда нет, идем на следующую итерацию
                         if ($i == 0) {
                             continue;
                         }
                         $reset_while = 0;
                         foreach ($modelModelsOld as $itemid) {
                             $vendor = iconv('Windows-1251', 'UTF-8', isset($data[0]) ? $data[0] : '');
                             //если запись уже есть в базе, обновляем
                             if ($itemid->vendor_code == $vendor) {
                                 $description = iconv('Windows-1251', 'UTF-8', isset($data[8]) ? $data[8] : '');
                                 $cena = str_replace(",", '.', isset($data[3]) ? $data[3] : '');
                                 $cena = preg_replace("/[^x\\d|*\\.]/", "", $cena);
                                 $old_cena = str_replace(",", '.', isset($data[4]) ? $data[4] : '');
                                 $old_cena = preg_replace("/[^x\\d|*\\.]/", "", $old_cena);
                                 //$accessories = iconv('Windows-1251', 'UTF-8', $data[9]);
                                 $model_name = iconv('Windows-1251', 'UTF-8', isset($data[2]) ? $data[2] : '');
                                 $photo_other = explode(',', mb_convert_encoding(isset($data[6]) ? $data[6] : '', 'UTF-8'));
                                 $photo_other_arr = array();
                                 foreach ($photo_other as $item) {
                                     $photo_other_arr[] = trim($item);
                                 }
                                 $acces = explode(',', mb_convert_encoding(isset($data[9]) ? $data[9] : '', 'UTF-8'));
                                 $accessories = array();
                                 foreach ($acces as $item) {
                                     $accessories[] = trim($item);
                                 }
                                 $sql[] = '(\'' . $vendor . '\', 
                                        \'' . $model_name . '\', 
                                        \'"' . $cena . '\', 
                                        \'' . $old_cena . '\', 
                                        \'' . $brand_id_update . '\', 
                                        \'' . (isset($data[5]) ? $data[5] : '') . '\', 
                                        \'' . ($photo_other_arr[0] != '' ? json_encode($photo_other_arr) : '') . '\',
                                        \'' . (isset($data[7]) ? $data[7] : '') . '\',
                                        \'' . $description . '\',
                                        \'' . json_encode($accessories) . '\',
                                        \'' . (isset($data[10]) ? $data[10] : '') . '\',
                                        \'' . (isset($data[11]) ? $data[11] : '') . '\',
                                        \'' . (isset($data[12]) ? $data[12] : '') . '\',
                                        \'' . (isset($data[13]) ? $data[13] : '') . '\'
                                        )';
                                 $id_update = $itemid->id;
                                 $j = 14;
                                 foreach ($modelCharacteristics as $k => $items) {
                                     if ($items->parent_id != 0 && isset($data[$j])) {
                                         $value = $data[$j] != '' ? iconv('Windows-1251', 'UTF-8', $data[$j]) : '';
                                         $sql_char[] = '(\'' . trim($value) . '\', \'' . $items->id . '\', \'' . $id_update . '\')';
                                         $j++;
                                     }
                                     if ($j == 50) {
                                         break;
                                     }
                                 }
                                 $reset_while = 1;
                             }
                         }
                         // если обновили, пропускаем итерацию
                         if ($reset_while == 1) {
                             continue;
                         }
                         // если нет, записываем новые данные
                         $vendor = iconv('Windows-1251', 'UTF-8', isset($data[0]) ? $data[0] : '');
                         $model_name = iconv('Windows-1251', 'UTF-8', isset($data[2]) ? $data[2] : '');
                         $modelModels->vendor_code = $vendor;
                         $modelModels->model_name = $model_name;
                         $cena = str_replace(",", '.', isset($data[3]) ? $data[3] : '');
                         $cena = preg_replace("/[^x\\d|*\\.]/", "", $cena);
                         $old_cena = str_replace(",", '.', isset($data[4]) ? $data[4] : '');
                         $old_cena = preg_replace("/[^x\\d|*\\.]/", "", $old_cena);
                         $photo_other = explode(',', mb_convert_encoding(isset($data[6]) ? $data[6] : '', 'UTF-8'));
                         $photo_other_arr = array();
                         foreach ($photo_other as $item) {
                             $photo_other_arr[] = trim($item);
                         }
                         $acces = explode(',', mb_convert_encoding(isset($data[9]) ? $data[9] : '', 'UTF-8'));
                         $accessories = array();
                         foreach ($acces as $item) {
                             $accessories[] = trim($item);
                         }
                         $modelModels->price = $cena;
                         $modelModels->old_price = $old_cena;
                         $modelModels->photo = isset($data[5]) ? $data[5] : '';
                         $modelModels->photo_other = $photo_other_arr[0] != '' ? json_encode($photo_other_arr) : '';
                         $modelModels->quantity = isset($data[7]) ? $data[7] : '';
                         $description = iconv('Windows-1251', 'UTF-8', isset($data[8]) ? $data[8] : '');
                         $modelModels->description = $description;
                         $modelModels->accessories = json_encode($accessories);
                         $modelModels->top = isset($data[10]) ? $data[10] : '';
                         $modelModels->promotion = isset($data[11]) ? $data[11] : '';
                         $modelModels->novelty = isset($data[12]) ? $data[12] : '';
                         $modelModels->bestPrice = isset($data[13]) ? $data[13] : '';
                         if ($modelModels->save(false)) {
                             $id_model = $modelModels->id;
                             $j = 14;
                             foreach ($modelCharacteristics as $k => $item) {
                                 if ($item->parent_id != 0 && isset($data[$j])) {
                                     $modelCharacteristicValue->id = false;
                                     $modelCharacteristicValue->isNewRecord = true;
                                     $value = $data[$j] ? iconv('Windows-1251', 'UTF-8', $data[$j]) : '-';
                                     $modelCharacteristicValue->value = $value;
                                     $modelCharacteristicValue->characteristic_id = $item->id;
                                     $modelCharacteristicValue->model_id = $id_model;
                                     if ($modelCharacteristicValue->save(false)) {
                                         $j++;
                                     }
                                 }
                                 if ($j == 51) {
                                     break;
                                 }
                             }
                         }
                     }
                     fclose($handle);
                     unlink($path_csv);
                 }
                 if (isset($sql[0])) {
                     $sql_implode = implode(', ', $sql);
                     $sql_query_models = 'INSERT INTO cms_temp_models (vendor_code,
                                                                       model_name,
                                                                       price,
                                                                       old_price,
                                                                       brand_id,
                                                                       photo,
                                                                       photo_other,
                                                                       quantity,
                                                                       description,
                                                                       accessories,
                                                                       top,
                                                                       promotion,
                                                                       novelty,
                                                                       bestPrice
                                                                       ) VALUES ' . $sql_implode;
                     $connection = Yii::app()->db;
                     $connection->createCommand($sql_query_models)->execute();
                     $sql_query_update = 'update cms_models u
                     inner join cms_temp_models s on
                         u.vendor_code = s.vendor_code
                     set u.model_name = s.model_name,
                         u.price = s.price,
                         u.old_price = s.old_price,
                         u.brand_id = s.brand_id,
                         u.photo = s.photo,
                         u.photo_other = s.photo_other,
                         u.quantity = s.quantity,
                         u.description = s.description,
                         u.accessories = s.accessories,
                         u.top = s.top,
                         u.promotion = s.promotion,
                         u.novelty = s.novelty,
                         u.bestPrice = s.bestPrice';
                     $connection->createCommand($sql_query_update)->execute();
                     $connection->createCommand()->truncateTable('cms_temp_models');
                     if (isset($sql_char)) {
                         $sql_implode_char = implode(', ', $sql_char);
                         $sql_query_models = 'INSERT INTO cms_temp_characteristicValue (value, characteristic_id, model_id) 
                                              VALUES ' . $sql_implode_char;
                         $connection = Yii::app()->db;
                         $connection->createCommand($sql_query_models)->execute();
                         $sql_query_update_char = 'UPDATE cms_characteristicValue u
                         INNER JOIN cms_temp_characteristicValue s ON
                             (u.characteristic_id = s.characteristic_id) AND (u.model_id = s.model_id)
                         SET u.value = s.value';
                         $connection->createCommand($sql_query_update_char)->execute();
                         $connection->createCommand()->truncateTable('cms_temp_characteristicValue');
                     }
                 }
                 // сообщение о завершении загрузки
                 Yii::app()->user->setFlash('status', 'Файл загружен, данные добавлены!');
             }
         }
     }
     if (isset($_POST['del'])) {
         $brand = ModelCategory::model()->findAll('category_id = :id', array(':id' => $id));
         $arr = array();
         foreach ($brand as $item) {
             $arr[] = $item->brand_id;
         }
         $criteria = new CDbCriteria();
         $criteria->addInCondition('brand_id', $arr);
         $model = Models::model()->findAll($criteria);
         $del = Models::model()->deleteAll($criteria);
         $arr_val = array();
         foreach ($model as $item) {
             $arr_val[] = $item->id;
         }
         $criteria_val = new CDbCriteria();
         $criteria_val->addInCondition('model_id', $arr_val);
         $val = CharacteristicValue::model()->deleteAll($criteria_val);
         Yii::app()->user->setFlash('status', 'Данные удалены!');
         $this->refresh();
     }
     $this->render('index', array('id' => $id, 'models' => $models));
 }
コード例 #23
0
ファイル: _form.php プロジェクト: rahmanjis/yii-catalog
echo $form->labelEx($model, 'price');
?>
        <?php 
echo $form->textField($model, 'price', array('size' => 20, 'maxlength' => 30));
?>
        <?php 
echo $form->error($model, 'price');
?>
    </div>

    <div class="row">
        <?php 
echo $form->labelEx($model, 'brand_id');
?>
        <?php 
echo $form->dropDownList($model, 'brand_id', CHtml::listData(Brand::model()->findAll(), 'id', 'name'));
?>
        <?php 
echo $form->error($model, 'brand_id');
?>
    </div>

    <div class="row">
        <?php 
echo $form->labelEx($model, 'category_id');
?>
    <?php 
if (isset($model->id)) {
    $id = $model->id;
} else {
    $id = '0';
コード例 #24
0
?>


<link rel="stylesheet" type="text/css"
	href="<?php 
echo Yii::app()->request->baseUrl;
?>
/css/users.css" />


<div class="infoblock shadow"><h1 style="color:#20B2AA;">Manage Devices</h1></div>
<HR WIDTH=1180 ALIGN=LEFT >


<?php 
$this->widget('bootstrap.widgets.TbBreadcrumb', array('links' => array('Manage Devices')));
?>
<br/>

<div class="well-button">

<?php 
echo TbHtml::Button('<i class="fa fa-arrow-left"></i> Back', array('onclick' => 'js:document.location.href="/mtcontrool"', 'id' => 'b1', 'title' => 'Back', 'color' => TbHtml::BUTTON_COLOR_DEFAULT, 'size' => TbHtml::BUTTON_SIZE_SMALL, 'style' => 'color: green;'));
?>

</div>


<?php 
$this->widget('bootstrap.widgets.TbGridView', array('id' => 'device-grid', 'dataProvider' => $model->search(), 'filter' => $model, 'columns' => array(array('header' => 'Model', 'name' => 'description'), array('header' => 'Brand', 'filter' => CHtml::listData(Brand::model()->findAll(), 'brand_name', 'brand_name'), 'name' => 'id_brand', 'value' => '$data->iDBRAND->brand_name'), array('header' => 'Platform', 'filter' => CHtml::listData(Platforms::model()->findAll(), 'name', 'name'), 'name' => 'id_platform', 'value' => '$data->iDPLATFORM->name'), array('class' => 'bootstrap.widgets.TbButtonColumn', 'template' => '{update}&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp{delete}', 'buttons' => array('update' => array('icon' => 'fa fa-pencil'), 'delete' => array('icon' => 'fa fa-trash-o'))))));
コード例 #25
0
ファイル: index.php プロジェクト: resoul/simicom_com_ua
<div id="main">
    <?php 
if (Yii::app()->getModule('user')->isAdmin()) {
    $this->menu = array(array('label' => 'Создать деталь', 'url' => array('create')), array('label' => 'Создать брэнд', 'url' => array('brand/create')), array('label' => 'Обновить прайс', 'url' => array('file/update/1')), array('label' => 'Создать пользователя', 'url' => array('partner/create')));
    $this->beginWidget('zii.widgets.CPortlet', array());
    $this->widget('zii.widgets.CMenu', array('items' => $this->menu, 'htmlOptions' => array('class' => 'operations')));
    $this->endWidget();
    $this->widget('zii.widgets.grid.CGridView', array('id' => 'product-grid-admin', 'dataProvider' => $model->search(), 'filter' => $model, 'columns' => array(array('name' => 'id', 'value' => '$data->id', 'htmlOptions' => array('width' => '180px'), 'headerHtmlOptions' => array('class' => 'id')), array('name' => 'catalog', 'value' => '$data->catalog', 'htmlOptions' => array('width' => '180px'), 'headerHtmlOptions' => array('class' => 'catalog')), array('name' => 'name', 'value' => '$data->name', 'headerHtmlOptions' => array('class' => 'name')), array('name' => 'brand_id', 'filter' => CHtml::listData(Brand::model()->findAll(array('order' => 'name ASC')), 'id', 'name'), 'value' => '$data->brand->name', 'headerHtmlOptions' => array('class' => 'brand')), array('name' => 'price', 'type' => 'raw', 'value' => 'CHtml::textField("price[$data->price]",$data->price,array("style"=>"width:50px;"))', 'htmlOptions' => array('width' => '80px', 'class' => 'width price-raw'), 'headerHtmlOptions' => array('class' => 'price')), array('class' => 'CButtonColumn', 'template' => '{update}{delete}'))));
} else {
    ?>
    <?php 
    $this->widget('zii.widgets.grid.CGridView', array('id' => 'product-grid', 'dataProvider' => $model->search(), 'filter' => $model, 'columns' => array(array('name' => 'catalog', 'value' => '$data->catalog', 'htmlOptions' => array('width' => '180px'), 'headerHtmlOptions' => array('class' => 'catalog')), array('name' => 'name', 'value' => '$data->name', 'headerHtmlOptions' => array('class' => 'name')), array('name' => 'brand_id', 'filter' => CHtml::listData(Brand::model()->findAll(array('order' => 'name ASC')), 'id', 'name'), 'value' => '$data->brand->name', 'headerHtmlOptions' => array('class' => 'brand')), array('name' => 'price', 'value' => '$data->price', 'htmlOptions' => array('width' => '80px', 'class' => 'width'), 'headerHtmlOptions' => array('class' => 'price')))));
    ?>
    <?php 
}
?>
</div>
<script>
    $(function(){
        var price = null;
        $('#product-grid-admin').on('focus', '.price-raw', function(){
            price = $(this).find('input').val();
        });
        $('#product-grid-admin').on('blur', '.price-raw', function(){
            if($(this).find('input').val() !== price){
                $.post('ajaxupdate?id=' + $(this).closest('tr').find('td:first').text(), {price : $(this).find('input').val()});
            }
        });
    });
</script>
<script>
コード例 #26
0
 public function actionUpdate($id)
 {
     if (Yii::app()->user->checkAccess('updateProductCategory') == false) {
         throw new CHttpException(403);
     }
     $category = ProductCategory::model()->multilingual()->findByPk($id);
     if (is_null($category)) {
         throw new CHttpException(404);
     }
     if (isset($_POST['ProductCategory'])) {
         $category->attributes = Yii::app()->request->getPost('ProductCategory');
         $category->update_time = time();
         foreach ($category->brand_id as $key => $value) {
             $brandname[] = Brand::model()->findByPk($value)->title;
         }
         $category->brand_id = implode(',', $category->brand_id);
         $category->brand_name = implode(',  ', $brandname);
         if ($category->validate() && $category->save()) {
             $this->setFlashMessage(strtr('<strong>{link}</strong> 产品类型修改成功', array('{link}' => CHtml::link($category->name, array('view', 'id' => $category->primaryKey)))));
             $this->redirect($this->getReturnUrl());
         }
     }
     $this->breadcrumbs = array('产品类型' => array('index'), '修改');
     $productCategoryOptions = ProductCategory::model()->getOptions();
     $brandOptions = Brand::model()->getOptions();
     $this->render('create', array('category' => $category, 'productCategoryOptions' => $productCategoryOptions, 'brandOptions' => $brandOptions, 'returnUrl' => $this->getReturnUrl()));
 }
コード例 #27
0
 /**
  * Returns the data model based on the primary key given in the GET variable.
  * If the data model is not found, an HTTP exception will be raised.
  */
 public function loadModel()
 {
     if ($this->_model === null) {
         if (isset($_GET['id'])) {
             $this->_model = Brand::model()->findbyPk($_GET['id']);
         }
         if ($this->_model === null) {
             throw new CHttpException(404, 'The requested page does not exist.');
         }
     }
     return $this->_model;
 }
コード例 #28
0
ファイル: Lists.php プロジェクト: vasitjuntong/carsnru
 public static function brand()
 {
     return CHtml::listData(Brand::model()->desc()->findAll(), 'brand_id', 'name');
 }
コード例 #29
0
 /**
  * 品牌列表Dialog展示
  */
 public function actionSpecial()
 {
     $brand_list = Brand::model()->findAll('disabled = :disabled', array(':disabled' => 'false'), array('select' => 'brand_id,brand_name'));
     $item = array();
     foreach ($brand_list as $v) {
         $row['label'] = $v['brand_name'];
         $row['value'] = $v['brand_name'];
         $row['brand_id'] = $v['brand_id'];
         $item[] = $row;
     }
     echo json_encode($item);
 }
コード例 #30
0
ファイル: _form.php プロジェクト: rodespsan/LMEC
	
	<div class="row">
		<?php 
echo $form->labelEx($model, 'brand_id');
?>
		<!-- <?php 
//echo $form->dropDownList($model,'brand_id',
//CHtml::listData(Brand::model()->findAllByAttributes(array('active'=>'1')),'id','name'),array('prompt'=>'Seleccionar',)
//);
//echo $form->dropDownList($model,'brand_id',
//CHtml::listData(Brand::model()->findAll(),'id','name'),array('prompt'=>'Seleccionar',)
//);
?>
 -->
		<?php 
echo $form->dropDownList($model, 'brand_id', CHtml::listData(Brand::model()->findAll(array('condition' => 'active = 1', 'order' => 'name')), 'id', 'name'), array('empty' => 'Seleccionar'));
?>
		<?php 
echo $form->error($model, 'equipment_type_id');
?>
		<?php 
echo $form->error($model, 'brand_id');
?>
	</div>

	<div class="row">
		<?php 
echo $form->labelEx($model, 'name');
?>
		<?php 
echo $form->textField($model, 'name', array('size' => 60, 'maxlength' => 200));