From 69cb9f8f1b77e6d129dfaf8e61f8012fe8f01dc1 Mon Sep 17 00:00:00 2001 From: Andrew Date: Sat, 21 Aug 2021 22:27:01 +0300 Subject: [PATCH] new filter --- Module.php | 10 +- commands/DevController.php | 29 + components/Filter.php | 95 ++- components/FilterController.php | 6 +- controllers/AjaxController.php | 45 ++ controllers/CatalogController.php | 7 +- .../m180311_192513_shop_product_filter.php | 51 ++ models/CategoryFilter.php | 10 +- models/ProductFilter.php | 38 + models/traits/EavQueryTrait.php | 34 +- widgets/filtersnew3/FilterAsset.php | 24 + widgets/filtersnew3/FiltersWidget.php | 356 ++++++++++ widgets/filtersnew3/assets/js/filter.js | 672 ++++++++++++++++++ widgets/filtersnew3/views/attributes.php | 94 +++ widgets/filtersnew3/views/brand.php | 51 ++ widgets/filtersnew3/views/current.php | 29 + widgets/filtersnew3/views/default.php | 55 ++ widgets/filtersnew3/views/price.php | 86 +++ 18 files changed, 1644 insertions(+), 48 deletions(-) create mode 100644 migrations/m180311_192513_shop_product_filter.php create mode 100644 models/ProductFilter.php create mode 100644 widgets/filtersnew3/FilterAsset.php create mode 100644 widgets/filtersnew3/FiltersWidget.php create mode 100644 widgets/filtersnew3/assets/js/filter.js create mode 100644 widgets/filtersnew3/views/attributes.php create mode 100644 widgets/filtersnew3/views/brand.php create mode 100644 widgets/filtersnew3/views/current.php create mode 100644 widgets/filtersnew3/views/default.php create mode 100644 widgets/filtersnew3/views/price.php diff --git a/Module.php b/Module.php index 5ffd30a8..9e382856 100644 --- a/Module.php +++ b/Module.php @@ -21,6 +21,8 @@ class Module extends WebModule implements BootstrapInterface public $filterViewCurrent = '@shop/widgets/filtersnew/views/current'; public $reviewsCount = 0; public $viewList = ['grid','list']; + + /* public function getImage($dirtyAlias) { //Get params @@ -61,7 +63,7 @@ public function parseImageAlias($parameterized) return ['alias' => $alias, 'size' => $size]; - } + }*/ /** @@ -71,7 +73,7 @@ public function parseImageAlias($parameterized) * * @param $notParsedSize * @return array|null - */ + public function parseSize($notParsedSize) { $sizeParts = explode('x', $notParsedSize); @@ -103,14 +105,14 @@ public function parseSize($notParsedSize) } return $size; - } + }*/ /** * @inheritdoc */ public function bootstrap($app) { - + $rules['filter'] = 'shop/ajax/filter'; $rules['catalog'] = 'shop/default/index'; $rules['search/ajax'] = 'shop/search/ajax'; $rules['notify/'] = 'shop/notify/index'; diff --git a/commands/DevController.php b/commands/DevController.php index a24bb3f0..7ce0ac3c 100644 --- a/commands/DevController.php +++ b/commands/DevController.php @@ -7,8 +7,10 @@ use panix\mod\shop\models\Currency; use panix\mod\shop\models\Product; use panix\mod\shop\models\ProductCategoryRef; +use panix\mod\shop\models\ProductFilter; use Yii; use panix\engine\console\controllers\ConsoleController; +use yii\base\Exception; use yii\helpers\Console; use yii\httpclient\Client; @@ -138,7 +140,34 @@ public function actionIndex() } + public function actionNewFilter() + { + $products = Product::find()->all(); + foreach ($products as $p) { + + foreach ($p->getEavAttributes() as $eavName => $eavOption) { + $data[]=[ + $p->id, + $eavOption + ]; + + /*$f = new ProductFilter(); + $f->product_id = $p->id; + $f->option_id = $eavOption; + try { + $f->save(false); + } catch (Exception $exception) { + }*/ + } + + //print_r($p->getEavAttributes());die; + } + ProductFilter::getDb()->createCommand()->batchInsert(ProductFilter::tableName(), [ + 'product_id', + 'option_id', + ], $data)->execute(); + } private function array_random(array $array, int $n = 1): array { diff --git a/components/Filter.php b/components/Filter.php index 8d811df4..28c50d92 100644 --- a/components/Filter.php +++ b/components/Filter.php @@ -279,7 +279,7 @@ public function getActiveFilters() public function getCategoryAttributesCallback() { $data = []; - + $active = $this->activeAttributes; foreach ($this->_eavAttributes as $attribute) { $data[$attribute->name] = [ 'title' => $attribute->title, @@ -290,13 +290,30 @@ public function getCategoryAttributesCallback() ]; $totalCount = 0; $filtersCount = 0; - foreach ($attribute->getOptions()->cache($this->cacheDuration)->all() as $option) { + foreach ($attribute->getOptions()->all() as $option) { $count = $this->countAttributeProductsCallback($attribute, $option); //$count=1; //if ($count > 1) { + + + $ss = array_key_first($active); + //print_r($ss); +$countText = $count; +if(isset($active[$attribute->name])){ + + //if($active[$attribute->name] != $attribute->name){ + // $countText = '+'.$count; + //} + + if($ss == $attribute->name && $count){ + $countText = '+'.$count; + } +} + $data[$attribute->name]['filters'][] = [ 'title' => $option->value, 'count' => (int)$count, + 'count_text' => $countText, 'data' => unserialize($option->data), 'abbreviation' => ($attribute->abbreviation) ? $attribute->abbreviation : null, 'key' => $attribute->name, @@ -318,6 +335,9 @@ public function getCategoryAttributesCallback() public function getCategoryAttributes() { $data = []; + $active = $this->activeAttributes; + + $first = array_key_first($active); foreach ($this->_eavAttributes as $attribute) { $data[$attribute->name] = [ @@ -332,10 +352,22 @@ public function getCategoryAttributes() foreach ($attribute->getOptions()->cache($this->cacheDuration)->all() as $option) { $count = $this->countAttributeProducts($attribute, $option); //$count=1; + + + //print_r($ss); + $countText = $count; + if(isset($active[$attribute->name])){ + + // if($first == $attribute->name){ + $countText = '+'.$count; + // } + } + //if ($count > 1) { $data[$attribute->name]['filters'][] = [ 'title' => $option->value, 'count' => (int)$count, + 'count_text' => $countText, 'data' => unserialize($option->data), 'abbreviation' => ($attribute->abbreviation) ? $attribute->abbreviation : null, 'key' => $attribute->name, @@ -367,19 +399,38 @@ public function countAttributeProducts($attribute, $option) $model->select('COUNT(*)'); $newData = []; + $newData[$attribute->name][] = $option->id; + $newData2=[]; + $ss = array_key_first($this->activeAttributes); + + foreach ($this->activeAttributes as $key=>$p){ + if($key!=$attribute->name) { + $newData[$key] = $p; + + } + } + + +//print_r($newData);die; //$newData = ArrayHelper::merge($newData,$this->activeAttributes); // echo $model->createCommand()->rawSql; // echo '


'; /** @var EavQueryTrait|ActiveQuery $model */ - //$model->withEavAttributes($newData); - + // $model->withEavAttributes($newData); +//print_r($newData);die; $model->getFindByEavAttributes2($newData); + + + + //$model->applyAttributes($newData2); + // echo $model->createCommand()->rawSql;die; - $model->groupBy = false; + // $model->groupBy(''.Product::tableName().'.`id`'); + // $model->distinct(true); // $model->cache($this->cacheDuration); //$res->distinct(false); // print_r($newData);die; @@ -395,7 +446,7 @@ public function countAttributeProducts($attribute, $option) // $count = Attribute::getDb()->cache(function () use ($model) { // return $model->count(); // }, 1, $dependency); - if ($attribute->name == 'obem') { + if ($attribute->name == 'tip') { //echo $model->createCommand()->rawSql;die; } return $model->createCommand()->queryScalar(); @@ -411,19 +462,30 @@ public function countAttributeProductsCallback($attribute, $option) $model->select('COUNT(*)'); $newData = []; $newData[$attribute->name][] = $option->id; - $firstItem = array_key_first($this->activeAttributes); + // print_r($this->activeAttributes);die; - if ($attribute->name == $firstItem) { - $newData = ArrayHelper::merge($newData, $this->activeAttributes); + $newData2=[]; + foreach ($this->activeAttributes as $key=>$p){ + if($key!=$attribute->name) { + $newData[$key] = $p; + } } + + + + //$newData = ArrayHelper::merge($newData,$this->activeAttributes); + + // echo $model->createCommand()->rawSql; + // echo '


'; /** @var EavQueryTrait|ActiveQuery $model */ - //$model->withEavAttributes($newData); - $model->getFindByEavAttributes3($newData); + // $model->withEavAttributes($newData); - $model->groupBy = false; - $model->cache($this->cacheDuration); - //$res->distinct(false); + $model->getFindByEavAttributes2($newData); + + // $model->groupBy = false; + //$model->cache($this->cacheDuration); + // $res->distinct(true); // print_r($newData);die; @@ -437,8 +499,9 @@ public function countAttributeProductsCallback($attribute, $option) // $count = Attribute::getDb()->cache(function () use ($model) { // return $model->count(); // }, 1, $dependency); - if ($attribute->name == 'obem') { - //echo $model->createCommand()->rawSql;die; + Yii::info($model->createCommand()->rawSql); + if ($attribute->name == 'tip') { + // echo $model->createCommand()->rawSql;die; } return $model->createCommand()->queryScalar(); } diff --git a/components/FilterController.php b/components/FilterController.php index aaa83bbc..8cf41eca 100644 --- a/components/FilterController.php +++ b/components/FilterController.php @@ -67,7 +67,7 @@ class FilterController extends WebController public $per_page; public $filter; - public function actionFilterCallback($category_id) + public function actionFilterCallback() { /** @var Product $productModel */ @@ -75,13 +75,13 @@ public function actionFilterCallback($category_id) $query = $productModel::find(); $query->published(); - +/* if ($category_id) { $category = Category::findOne($category_id); if (!$category) $this->error404(); $query->applyCategories($category); - } + }*/ diff --git a/controllers/AjaxController.php b/controllers/AjaxController.php index 8a295820..6f5df5ef 100644 --- a/controllers/AjaxController.php +++ b/controllers/AjaxController.php @@ -2,8 +2,11 @@ namespace panix\mod\shop\controllers; +use panix\mod\shop\components\Filter; +use panix\mod\shop\models\Category; use Yii; use panix\engine\controllers\WebController; +use yii\helpers\ArrayHelper; class AjaxController extends WebController { @@ -21,4 +24,46 @@ public function actionCurrency($id) return $this->goHome(); } } + + + public function actionFilter() + { + $productModel = Yii::$app->getModule('shop')->model('Product'); + $query = $productModel::find(); + $query->published(); + $category_id=9; + if ($category_id) { + $category = Category::findOne($category_id); + if (!$category) + $this->error404(); + $query->applyCategories($category); + } + $filterPost = Yii::$app->request->post('filter'); + if ($filterPost){ + if(isset($filterPost['brand'])){ + $query->applyBrands($filterPost['brand']); + } + //unset(Yii::$app->request->post('filter')['brand']); + // $query->getFindByEavAttributes3($filterPost); + } +//echo $query->createCommand()->rawSql;die; + + $filter = new Filter($query, $category); + + + //print_r($f->getPostActiveAttributes());die; + $attributes = $filter->getCategoryAttributesCallback(); + $brands = $filter->getCategoryBrandsCallback(); + $total = 0; + $results = ArrayHelper::merge($attributes, ['brand' => $brands]); + + + + // $total = $filter->count(); + return $this->asJson([ + 'textTotal'=>"Показать ".Yii::t('shop/default','PRODUCTS_COUNTER',$total), + 'totalCount' => $total, + 'filters' => $results + ]); + } } diff --git a/controllers/CatalogController.php b/controllers/CatalogController.php index 9b0ea136..3cd207ad 100644 --- a/controllers/CatalogController.php +++ b/controllers/CatalogController.php @@ -29,7 +29,10 @@ class CatalogController extends FilterController public $provider; public $currentUrl; - + public function actionFilterCallback() + { + return $this->asJson(['ok' => true]); + } public function beforeAction($action) { if (Yii::$app->request->headers->has('filter-ajax')) { @@ -51,6 +54,8 @@ public function actionView() $this->query->published(); + + // $cr->with = array('brandActive'); // Скрывать товары если бренд скрыт. //TODO: если у товара не выбран бренд то он тоже скрывается!! need fix diff --git a/migrations/m180311_192513_shop_product_filter.php b/migrations/m180311_192513_shop_product_filter.php new file mode 100644 index 00000000..68dda176 --- /dev/null +++ b/migrations/m180311_192513_shop_product_filter.php @@ -0,0 +1,51 @@ + + * + * Class m180311_192513_shop_product_filter + */ + +use panix\engine\db\Migration; +use panix\mod\shop\models\ProductFilter; + +class m180311_192513_shop_product_filter extends Migration +{ + + public function up() + { + $this->createTable(ProductFilter::tableName(), [ + 'id' => $this->primaryKey(), + 'product_id' => $this->integer()->unsigned()->null(), + 'option_id' => $this->integer()->unsigned()->null(), + ]); + + // $this->addPrimaryKey('{{%shop__product_filter_pk}}', ProductFilter::tableName(), ['product_id', 'option_id']); + /*$this->addForeignKey( + '{{%shop__product_filter_product_id_fk}}', + ProductFilter::tableName(), + 'product_id', + \panix\mod\shop\models\Product::tableName(), + 'id', + 'CASCADE' + ); + + + + $this->addForeignKey( + '{{%shop__product_filter_option_id_fk}}', + ProductFilter::tableName(), + 'option_id', + \panix\mod\shop\models\AttributeOption::tableName(), + 'id', + 'CASCADE' + );*/ + } + + public function down() + { + $this->dropTable(ProductFilter::tableName()); + } + +} diff --git a/models/CategoryFilter.php b/models/CategoryFilter.php index e193aa64..1d254aa2 100644 --- a/models/CategoryFilter.php +++ b/models/CategoryFilter.php @@ -2,26 +2,18 @@ namespace panix\mod\shop\models; - -use panix\mod\shop\components\ExternalFinder; -use panix\mod\sitemap\behaviors\SitemapBehavior; use Yii; -use yii\helpers\ArrayHelper; -use panix\engine\behaviors\nestedsets\NestedSetsBehavior; -use panix\mod\shop\models\translate\CategoryTranslate; use panix\mod\shop\models\query\CategoryQuery; use panix\engine\CMS; use panix\engine\db\ActiveRecord; -use panix\engine\behaviors\UploadFileBehavior; /** - * Class CategoryFilter + * Class CategoryFilter IN DEV * @package panix\mod\shop\models * * @property integer $id * @property integer $category_id * @property integer $option_id - * @property string getMetaTitle() */ class CategoryFilter extends ActiveRecord { diff --git a/models/ProductFilter.php b/models/ProductFilter.php new file mode 100644 index 00000000..e699bfc6 --- /dev/null +++ b/models/ProductFilter.php @@ -0,0 +1,38 @@ +getSafeAttributesArray(); - // } + // $attributes = $this->getSafeAttributesArray(); + // } // $attributes be array of elements: $attribute => $values return $this->getFindByEavAttributes2($attributes); @@ -40,12 +40,12 @@ public function getEavAttributes22222222($attributes = array()) $loadQueue = new CList(); foreach ($attributes as $attribute) { // Check is safe. - // if ($this->hasSafeAttribute($attribute)) { - $values[$attribute] = $attribute; - // If attribute not set and not load, prepare array for loaded. - // if (!$this->preload && $values[$attribute] === NULL) { - // $loadQueue->add($attribute); - // } + // if ($this->hasSafeAttribute($attribute)) { + $values[$attribute] = $attribute; + // If attribute not set and not load, prepare array for loaded. + // if (!$this->preload && $values[$attribute] === NULL) { + // $loadQueue->add($attribute); + // } //} } // If array for loaded not empty, load attributes. @@ -93,7 +93,7 @@ public function getFindByEavAttributes($attributes) } //$this->distinct(true); - $this->groupBy("{$pk}"); + $this->groupBy("{$pk}"); // echo $this->createCommand()->getRawSql();die; return $this; } @@ -103,7 +103,7 @@ public function getFindByEavAttributes2($attributes) $class = $this->modelClass; $pk = $class::tableName() . '.`id`'; $i = 0; - // echo $this->createCommand()->getRawSql();die; + // echo $this->createCommand()->getRawSql();die; foreach ($attributes as $attribute => $values) { // If search models with attribute name with specified values. if (is_string($attribute)) { @@ -120,9 +120,13 @@ public function getFindByEavAttributes2($attributes) $values = array_intersect($cache[$attribute], $values); } - $this->join('JOIN', ProductAttributesEav::tableName().' eavb' . $i, "$pk=`eavb$i`.`entity`"); - // $this->join['eavb' . $i] = ['JOIN', '{{%shop__product_attribute_eav}} eavb' . $i, "$pk=`eavb$i`.`entity`"]; + + // $this->join['eavb' . $i] = ['JOIN', '{{%shop__product_filter}} eavb' . $i, "$pk=`eavb$i`.`product_id`"]; + // $this->andwhere(['IN', "`eavb$i`.`option_id`", $values]); + + $this->join['eavb' . $i] = ['JOIN', '{{%shop__product_attribute_eav}} eavb' . $i, "$pk=`eavb$i`.`entity`"]; $this->andwhere(['IN', "`eavb$i`.`value`", $values]); + $i++; } elseif (is_int($attribute)) { // If search models with attribute name with anything values. $this->join('JOIN', ProductAttributesEav::tableName().' eavb' . $i, "$pk=`eavb$i`.`entity` AND eavb$i.attribute = '$values'"); @@ -132,11 +136,11 @@ public function getFindByEavAttributes2($attributes) - // $this->distinct(true); + // $this->distinct(true); - $this->groupBy("{$pk}"); + // $this->groupBy("{$pk}"); //$this->addGroupBy("{$pk}"); - // echo $this->createCommand()->getRawSql();die; + // echo $this->createCommand()->getRawSql();die; return $this; } diff --git a/widgets/filtersnew3/FilterAsset.php b/widgets/filtersnew3/FilterAsset.php new file mode 100644 index 00000000..2cd00913 --- /dev/null +++ b/widgets/filtersnew3/FilterAsset.php @@ -0,0 +1,24 @@ + 'filter-count']; + //public $showEmpty = false; + public $searchItem = 20; + + /** + * @var \panix\mod\shop\models\query\CategoryQuery + */ + public $model; + public $priceView = 'price'; + public $brandView = 'brand'; + public $attributeView = 'attributes'; + public $query; + public $cacheDuration = 86400; + + + /** + * @var string min/max price in the query + */ + protected $_currentPriceMin, $_currentPriceMax = null; + public $priceMin, $priceMax; + protected $prices = []; + + public function init() + { + $view = $this->getView(); + + $this->priceMax = $this->data->price_max; + $this->priceMin = $this->data->price_min; + + if (Yii::$app->request->get('price')) { + $this->prices = explode('-', Yii::$app->request->get('price')); + } + + FilterAsset::register($view); + } + + + /** + * @return array of attributes used in category + */ + + + public function run() + { + $brands = $this->getCategoryBrands(); + + + $active = $this->data->getActiveFilters(); + + + //echo Html::beginTag('div', ['id' => 'filters']); + // echo Html::beginForm($this->view->context->currentUrl, 'GET', ['id' => 'filter-form']); + + /*echo Html::beginTag('div', ['id' => 'ajax_filter_current']); + if (!empty($active)) { + $url = ($this->model) ? $this->model->getUrl() : ['/' . Yii::$app->requestedRoute]; + echo $this->render(Yii::$app->getModule('shop')->filterViewCurrent, ['active' => $active, 'dataModel' => $this->model, 'url' => $url]); + } + echo Html::endTag('div');*/ + /*if($this->priceView) + echo $this->render($this->priceView, [ + 'priceMin' => $this->priceMin, + 'priceMax' => $this->priceMax, + 'currentPriceMin'=>$this->data->getCurrentMinPrice(), + 'currentPriceMax'=>$this->data->getCurrentMaxPrice(), + ]); + if($this->attributeView) + echo $this->render($this->attributeView, ['attributes' => $this->data->getCategoryAttributes()]); + if($this->brandView) + echo $this->render($this->brandView, ['brands' => $brands]); + + echo Html::submitButton('Применить',['class'=>'btn btn-block btn-primary']); + echo Html::submitButton('Стросить',['class'=>'btn btn-block btn-secondary']);*/ + + // echo Html::endForm(); +//echo $this->data->getCurrentMinPrice();die; + // echo Html::endTag('div'); + // print_r($this->model->id);die; + echo $this->render('default', [ + 'model'=>$this->model, + 'currentUrl' => $this->view->context->currentUrl, + 'refreshUrl' => (($this->model) ? $this->model->getUrl() : ['/' . Yii::$app->requestedRoute]), + 'priceMin' => $this->priceMin, + 'priceMax' => $this->priceMax, + 'currentPriceMin' => $this->data->getCurrentMinPrice(), + 'currentPriceMax' => $this->data->getCurrentMaxPrice(), + 'active' => $active, + 'attributes' => $this->data->getCategoryAttributes(), + 'brands' => $brands + ]); + // var category_id = {$this->model->id}; + $this->view->registerJs(" + + $(function () { + var selector = $('.card .card-collapse'); + selector.collapse({ + toggle: false + }); + var panels = $.cookie(); + + for (var panel in panels) { + if (panel) { + var panelSelector = $('#' + panel); + if (panelSelector) { + var header = panelSelector.parent().find('.card-header'); + if (panelSelector.hasClass('card-collapse')) { + if ($.cookie(panel) === '1') { + panelSelector.collapse('show'); + header.addClass('collapsed').attr('aria-expanded',true); + } else { + panelSelector.collapse('hide'); + header.removeClass('collapsed').attr('aria-expanded',false); + } + } + } + } + } + + selector.on('show.bs.collapse', function () { + var active = $(this).attr('id'); + $(this).parent().find('.card-header').addClass('collapsed'); + + + $.cookie(active, '1'); + + }); + + selector.on('hide.bs.collapse', function () { + var active = $(this).attr('id'); + $(this).parent().find('.card-header').removeClass('collapsed'); + + $.cookie(active, null); + }); + }); + "); + + + } + + + public function getCategoryBrands() + { + + $query = Product::find(); + + if ($this->model) { + $query->applyCategories($this->model); + //$query->andWhere([Product::tableName() . '.main_category_id' => $this->model->id]); + } + + if (Yii::$app->request->get('q') && Yii::$app->requestedRoute == 'shop/search/index') { + $query->applySearch(Yii::$app->request->get('q')); + } + $query->published(); + $queryClone = clone $query; + $queryMan = $queryClone->addSelect(['brand_id', Product::tableName() . '.id']); + $queryMan->joinWith([ + 'brand' => function (\yii\db\ActiveQuery $query) { + $query->andWhere([Brand::tableName() . '.switch' => 1]); + }, + ]); + //$queryMan->->applyMaxPrice($this->convertCurrency(Yii::$app->request->getQueryParam('max_price'))) + //$queryMan->->applyMinPrice($this->convertCurrency(Yii::$app->request->getQueryParam('min_price'))) + + $queryMan->andWhere('brand_id IS NOT NULL'); + $queryMan->groupBy('brand_id'); + + + // $brands = $queryMan->all(); + + + $brands = Brand::getDb()->cache(function ($db) use ($queryMan) { + return $queryMan + //->joinWith('translations as translate') + //->orderBy(['translate.name'=>SORT_ASC]) + ->all(); + }, $this->cacheDuration); + + + //$brands =$queryMan->all(); + //echo $q->createCommand()->rawSql;die; + $data = [ + 'title' => Yii::t('shop/default', 'FILTER_BY_BRAND'), + 'selectMany' => true, + 'filters' => [] + ]; + + if ($brands) { + + foreach ($brands as $m) { + + $m = $m->brand; + + if ($m) { + $query = Product::find(); + $query->published(); + if ($this->model) { + $query->applyCategories($this->model); + //$query->andWhere([Product::tableName() . '.main_category_id' => $this->model->id]); + } + + //$q->applyMinPrice($this->convertCurrency(Yii::app()->request->getQuery('min_price'))) + //$q->applyMaxPrice($this->convertCurrency(Yii::app()->request->getQuery('max_price'))) + $query->applyBrands($m->id); + + if (Yii::$app->request->get('q') && Yii::$app->requestedRoute == 'shop/search/index') { + $query->applySearch(Yii::$app->request->get('q')); + } + + + /*$dependencyQuery = $query; + $dependencyQuery->select('COUNT(*)'); + $dependency = new DbDependency([ + 'sql' => $dependencyQuery->createCommand()->rawSql, + ]); + + $count = Product::getDb()->cache(function () use ($query) { + return $query->count(); + }, 3600 * 24, $dependency);*/ + + + $query->orderBy = false; + $count = $query->cache($this->cacheDuration)->count(); + + $data['filters'][] = [ + 'title' => $m->name, + 'count' => (int)$count, + 'key' => 'brand', + 'queryParam' => $m->id, + ]; + sort($data['filters']); + } else { + die('err brand'); + } + } + } + + return $data; + } + + public function convertCurrency($sum) + { + $cm = Yii::$app->currency; + if ($cm->active->id != $cm->main->id) + return $cm->activeToMain($sum); + return $sum; + } + + public function getCount($filter) + { + //$this->tagCountOptions=[]; + if (isset($filter['key'])) { + $this->tagCountOptions['id'] = 'filter-count-' . $filter['key'] . '-' . $filter['queryParam']; + } + $result = ($filter['count'] > 0) ? $filter['count_text'] : 0; + return ($this->count) ? ' ' . Html::tag($this->tagCount, $result, $this->tagCountOptions) : ''; + } + + public function generateGradientCss($data) + { + $css = ''; + if ($data) { + $css .= "background: {$data[0]['color']};"; + if (count($data) > 1) { + + $res_data = []; + foreach ($data as $k => $color) { + $res_data[] = $color['color']; + } + $res = implode(', ', $res_data); + + if (count($data) == 2) { + $value = "45deg, {$data[0]['color']} 50%, {$data[1]['color']} 50%"; + $css .= "background: -moz-linear-gradient({$value});"; + $css .= "background: -webkit-linear-gradient({$value});"; + $css .= "background: linear-gradient({$value});"; + } elseif (count($data) == 3) { + $value = "45deg, {$data[0]['color']} 0%, {$data[0]['color']} 33%, {$data[1]['color']} 33%, {$data[1]['color']} 66%, {$data[2]['color']} 66%, {$data[2]['color']} 100%"; + $css .= "background: -moz-linear-gradient({$value});"; + $css .= "background: -webkit-linear-gradient({$value});"; + $css .= "background: linear-gradient({$value});"; + } elseif (count($data) == 4) { + $value = "45deg, {$data[0]['color']} 0%, {$data[0]['color']} 25%, {$data[1]['color']} 25%, {$data[1]['color']} 50%, {$data[2]['color']} 50%, {$data[2]['color']} 75%, {$data[3]['color']} 75%, {$data[3]['color']} 100%"; + $css .= "background: -moz-linear-gradient({$value});"; + $css .= "background: -webkit-linear-gradient({$value});"; + $css .= "background: linear-gradient({$value});"; + } elseif (count($data) >= 4) { + $css .= "background: -moz-radial-gradient(farthest-corner at 0% 100%, {$res});"; + $css .= "background: -webkit-radial-gradient(farthest-corner at 0% 100%, {$res});"; + $css .= "background: radial-gradient(farthest-corner at 0% 100%, {$res});"; + } + $css .= "filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='{$data[0]['color']}', endColorstr='{$data[1]['color']}',GradientType=1 );"; + } + } + return $css; + } + + + /** + * @return mixed + */ + public function getCurrentMinPrice() + { + if ($this->_currentPriceMin !== null) + return $this->_currentPriceMin; + + $this->_currentPriceMin = (isset($this->prices[0])) ? $this->prices[0] : Yii::$app->currency->convert($this->priceMin); + + return $this->_currentPriceMin; + } + + /** + * @return mixed + */ + public function getCurrentMaxPrice() + { + if ($this->_currentPriceMax !== null) + return $this->_currentPriceMax; + + $this->_currentPriceMax = (isset($this->prices[1])) ? $this->prices[1] : Yii::$app->currency->convert($this->priceMax); + + return $this->_currentPriceMax; + } +} diff --git a/widgets/filtersnew3/assets/js/filter.js b/widgets/filtersnew3/assets/js/filter.js new file mode 100644 index 00000000..bcd83a8d --- /dev/null +++ b/widgets/filtersnew3/assets/js/filter.js @@ -0,0 +1,672 @@ +(function ($) { + $.fn.serializeObject = function () { + var o = {}; + var a = this.serializeArray(); + $.each(a, function () { + if (o[this.name]) { + if (!o[this.name].push) { + o[this.name] = [o[this.name]]; + } + o[this.name].push(this.value || ''); + } else { + o[this.name] = this.value || ''; + } + }); + return o; + }; +}(jQuery)); + +$(function () { + var selector = $('#filters .card-collapse'); + selector.collapse({ + toggle: false + }); + if ($.fn.cookie) { + var panels = $.cookie(); + + for (var panel in panels) { + //console.log(panel); + if (panel) { + var panelSelector = $('#' + panel); + if (panelSelector) { + if (panelSelector.hasClass('card-collapse')) { + if ($.cookie(panel) === '1') { + panelSelector.collapse('show'); + } else { + panelSelector.collapse('hide'); + } + } + } + } + } + + selector.on('show.bs.collapse', function () { + var active = $(this).attr('id'); + $.cookie(active, '1'); + + }); + + selector.on('hide.bs.collapse', function () { + var active = $(this).attr('id'); + $.cookie(active, null); + }); + } + + + $(document).on('click', '.sorting .radio_item', function () { + $('.sorting').removeClass('open'); + }); +}); + + +var form = $('#filter-form'); +var sortForm = $('#sorting-form'); +var ajaxSelector = $('#listview-ajax'); +var containerFilterCurrent = $('#ajax_filter_current'); +var xhrFilters; +var xhrCallback; +var flagDeletePrices = false; +var global_url; +var newFunction = true; + +function filterCallback(e, objects, target) { + if (xhrCallback && xhrCallback.readyState !== 4) { + xhrCallback.onreadystatechange = null; + xhrCallback.abort(); + //ajaxSelector.removeClass('loading'); + } + + var url = formattedURL(e, objects); + + objects = $.extend(objects, {test: '111'}); + console.debug('FilterCallback: ', objects); + xhrCallback = $.ajax({ + dataType: "json", + url: '/filter', + type: 'POST', + headers: { + "filter-callback-ajax": true + }, + data: objects, + success: function (response) { + + + /*form.find('[aria-describedby^="popover"]') + //.not('[data-toggle="popover-price"]') + .not(target.parent()) + .popover('destroy');*/ + + /*if (!target.parent().attr('aria-describedby')) { + var options = { + placement: 'right', + selector: false, + delay: {'show': 400, 'hide': 600}, + content: function () { + return $('#ocfilter-button').html(); + }, + container: target.parent(), + trigger: 'hover', + html: true + }; + + target.parent().popover(options).popover('show'); + $('#' + target.parent().attr('aria-describedby')).addClass('filter-option-popover'); + } else { + console.log('replaceWith'); + $('#' + target.parent().attr('aria-describedby') + ' button').replaceWith($('#ocfilter-button').html()); + }*/ + + + /*ajaxSelector.html(data.items).toggleClass('loading'); + form.attr('action', data.currentUrl); + containerFilterCurrent.html(data.currentFiltersData).removeClass('loading'); + history.pushState(null, $('title').text(), data.currentUrl); + //console.log('success filter_ajax'); + $('#summary').html(data.totalCount); + $('h1').html(data.pageName); + + jQuery.ias().reinitialize();*/ + + $('#ocfilter-button button').text(response.textTotal); + + $.each(response.filters, function (name, filters) { + + $('#filter-' + name + ' input[type="checkbox"]:not(:checked)').attr('disabled', 'disabled'); + + $('#filter-' + name + ' li').addClass('disabled'); + + $.each(filters.filters, function (index, data) { + var count = data.count; + var selector = $('#filter_' + name + '_' + data.queryParam); + + + if (data.count) { + //if (!$('#filter_' + name + '_' + data.queryParam).is('checked')) { + // count = '+' + count; + //} + if (selector.prop('checked')) { + $('#filter-count-' + name + '-' + data.queryParam).html(''); + } else { + $('#filter-count-' + name + '-' + data.queryParam).html(data.count_text); + } + + $('#filter_' + name + '_' + data.queryParam).removeAttr('disabled'); + $('#filter_' + name + '_' + data.queryParam).closest('li').removeClass('disabled'); + // $('#filter_' + name + '_' + data.queryParam).parent('div').parent('li').removeClass('filter-disabled'); + } else { + if (!selector.prop('checked')) { + $('#filter-count-' + name + '-' + data.queryParam).html(data.count_text); + }else{ + $('#filter_' + name + '_' + data.queryParam).closest('li').removeClass('disabled'); + //$('#filter_' + name + '_' + data.queryParam).attr('disabled', 'disabled'); + } + } + }); + + }); + // $(target).removeAttr('disabled'); + }, + beforeSend: function () { + //ajaxSelector.toggleClass('loading'); + } + }); +} + +function filter_ajax(e, objects) { + if (xhrFilters && xhrFilters.readyState !== 4) { + xhrFilters.onreadystatechange = null; + xhrFilters.abort(); + ajaxSelector.removeClass('loading'); + } + + //if (url === undefined) { + var url = formattedURL(e, objects); + //var url = current_url; + // } + + console.debug('Event: ' + e.type, objects); + xhrFilters = $.ajax({ + dataType: "json", + url: url, + type: 'POST', + headers: { + "filter-ajax": true + }, + data: $('#filter-form input[type="checkbox"],#filter-form input[type="radio"]').serialize(), + success: function (data) { + ajaxSelector.html(data.items).toggleClass('loading'); + form.attr('action', data.currentUrl); + containerFilterCurrent.html(data.currentFiltersData).removeClass('loading'); + history.pushState(null, $('title').text(), data.currentUrl); + //console.log('success filter_ajax'); + $('#summary').html(data.totalCount); + $('h1').html(data.pageName); + + if ((typeof $.fn.ias !== 'undefined')) { + var ias = jQuery.ias(); + if (ias) { + console.debug('ias plugin > reinitialize:', ias); + ias.reinitialize(); + } + } else { + // pjax.state = data.currentUrl; + if ($.pjax) { + console.log('dsa'); + // $.pjax({url: url, container: '#pjax-catalog', timeout: false, state: data.currentUrl}); + // $.pjax.reload('#pjax-sales', {url: url,timeout:false,state:data.currentUrl}) + } + } + + + }, + beforeSend: function () { + ajaxSelector.toggleClass('loading'); + } + }); +} + + +/* + var xhrCurrentFilter; + function currentFilters(url) { + var containerFilterCurrent = $('#ajax_filter_current'); + if (xhrCurrentFilter && xhrCurrentFilter.readyState !== 4) { + xhrCurrentFilter.onreadystatechange = null; + xhrCurrentFilter.abort(); + } + + xhrCurrentFilter = $.ajax({ + type: 'GET', + url: url, + data:{render:'active-filters'}, + beforeSend: function () { + containerFilterCurrent.addClass('loading'); + }, + success: function (data) { + containerFilterCurrent.html(data).removeClass('loading'); + $('#filter-form').attr('action',data.full_url); + } + }); + } + */ +function getSerializeObjects() { + + var formObject = form.serializeObject(); + return $.extend(formObject, sortForm.serializeObject()) +} + +function getSerialize() { + + return $.extend(form.serialize(), sortForm.serialize()) +} + +function formattedURL(e, objects) { + var uri = current_url; + var valuesList; + delete objects[yii.getCsrfParam()]; + //delete objects.min_price; + delete objects.default_price; + + $.each(objects, function (name, values) { + if (values !== '') { + + //var matches = name.match(/filter\[([a-zA-Z0-9-_]+)\]\[]|/i); + var matches = name.match(/filter\[([a-zA-Z0-9-_]+)\]\[]/i); + var slides = name.match(/slide\[(?[a-zA-Z0-9-_]+)\]\[]/i); + + + //if (e.type == 'slidestop') { + + + // } else { + valuesList = (values instanceof Array) ? '/' + values.join(',') : '/' + values; + if (name === 'sort') { + + uri += '/sort' + valuesList; + + } else { + if (matches) { + uri += '/' + matches[1] + valuesList; + } else { + if (slides) { + + valuesList = (values instanceof Array) ? '/' + values.join('-') : '/' + values; + var defaultMin = $('#min_' + slides.groups.name).data('default'); + var defaultMax = $('#max_' + slides.groups.name).data('default'); + + //No add to url default values + if ((Number.parseInt(values[0]) > defaultMin) || (Number.parseInt(values[1]) < defaultMax)) { // && (defaultMax < Number.parseInt(values[1])) + uri += '/' + slides.groups.name + '' + valuesList; + } + + } else { + uri += '/' + name + valuesList; + } + + } + // uri += ((matches) ? '/' + matches[1] : '/' + name) + valuesList; + } + // } + + + } + }); + + //console.debug(uri); + // console.log(uri, 'formattedURL', objects); + return uri; +} + + +function arrayRemove(arr, value) { + return arr.filter(function (ele) { + return ele != value; + }); +} + +console.debugging = true; + +console.debug = function () { + if (!console.debugging) return; + var mainArguments = Array.prototype.slice.call(arguments); + mainArguments.unshift("[Filter]"); + console.log.apply(this, mainArguments); +}; + + +$(function () { + var action; + var width = $(window).width(); + var isMobile = (width < 768) ? true : false; + var showReset = false; + var showApply = false; + + $(document).on('filter:apply', function (e) { + flagDeletePrices = true; + var objects = getSerializeObjects(); + console.debug('Apply sending...', $('#filter-form').serializeArray()); + filter_ajax(e, objects); + + + }); + + var currentChackedByOpen = []; //Определение после открытие фильтра чекнутых елементов. + + var checkedAll = []; + var markedCheckbox = document.querySelectorAll('#filter-form input[type="checkbox"]:checked'); + var actibeFilterLog = []; + for (var checkbox of markedCheckbox) { + checkedAll.push($(checkbox).attr('id')); + currentChackedByOpen.push($(checkbox).attr('id')); + actibeFilterLog.push($(checkbox).attr('id')); + } + console.debug('Active filter:', actibeFilterLog.join(', ')); + + + var changeItems = []; + var oldcheckedAll = checkedAll; + + + $(document).on('filter:buttons:toggle', '.filter-buttons', function (e, btn_reset, btn_apply) { + + /*if (Array.isArray(checkboxChacked)) { + if (!checkboxChacked.length) { + checkboxChacked = false; + } + } + + console.debug('TEST', showReset, showApply);*/ + if (showReset) { //checkedAll || + $('#filter-reset').show(); + } else { + $('#filter-reset').hide(); + } + + if (showApply) { //checkedAll || + $('#filter-apply').show(); + } else { + $('#filter-apply').hide(); + } + + if (showReset || showApply) { //if (checkboxChacked) { + $(this).addClass('show'); + $('.sidebar').addClass('submitted'); + console.debug(e.type, 'Show'); + } else { + //showApply = false; + $(this).removeClass('show'); + $('.sidebar').removeClass('submitted'); + console.debug(e.type, 'Hide'); + } + + }); + + + $(document).on('filter:open', '.sidebar', function (e) { + console.debug('Event: ' + e.type, checkedAll); + $(this).addClass('open'); + $('body').addClass('noscroll'); + + if ($('#filter-current ul li').length) { + showReset = true; + showApply = true; //not chika: set false + } + $('.filter-buttons').trigger('filter:buttons:toggle'); + + }); + + $(document).on('filter:close', '.sidebar', function (e) { + console.debug('Event: ' + e.type); + $(this).removeClass('open'); + $('body').removeClass('noscroll'); + + }); + + $(document).on('filter:click:checkbox', '#filter-form input[type="checkbox"],#filter-form input[type="radio"]', function (e, state) { + this.checked = state; + var id = $(this).attr('id'); + // $('.tester').remove(); + + + // $(this).parent().append('
123
'); + // $('#example').popover({ + // container: $(this).parent() + // }) + + console.debug(e.type, id, state); + if (!isMobile) { + + + var hovered = false; + + /* form.on({ + 'mouseenter': function (e) { + hovered = true; + }, + 'mouseleave': function (e) { + hovered = false; + + $('[aria-describedby="' + $(this).attr('id') + '"]').popover('toggle'); + } + }, '.popover').on('hide.bs.popover', '[aria-describedby^="popover"]', function (e) { + setTimeout(function (element) { + $(element).show(); + }, 0, e.target); + + if (hovered) { + e.preventDefault(); + } + });*/ + + + console.debug('Dekstop', width, this); + $(this).trigger('filter:apply'); + + if (newFunction) { + var objects = getSerializeObjects(); + var target = $(this); + filterCallback(e, objects, target); + } + + } else { + console.debug('Mobile', width, this); + + if (state) { + checkedAll.push(id); + } else { + checkedAll = arrayRemove(checkedAll, id); + } + + if (checkedAll.length > currentChackedByOpen.length) { + changeItems = checkedAll.filter(n => currentChackedByOpen.indexOf(n) === -1); + + } else { + changeItems = currentChackedByOpen.filter(n => checkedAll.indexOf(n) === -1); + + } + console.log('> activeItems', changeItems); + //showReset = (checkedAll.length) ? true : false; //not for chika + showReset = true; //for chika + showApply = true; + $('.filter-buttons').trigger('filter:buttons:toggle'); + } + + }); + + + //Active filters mobile + if (isMobile) { + $(document).on('click', '#filter-current ul a', function (e) { + var object = $(this).parent('li'); + var objectList = $(this).closest('ul'); + var checkboxId = $(object.data('target')); + var slideId = $(object.data('slide-price-max')); + var type = object.data('type'); + + if (type == 'slider') { + //remove params by slider + console.debug('check', slideId); + var slider = $("#slider-price"); + var min = slider.slider("option", "min"); + var max = slider.slider("option", "max"); + slider.slider("values", [min, max]); + $('#min_price').val(min); + $('#max_price').val(max); + $('#filter-apply').show(); + + } else { + checkboxId.prop('checked', false); + checkboxId.trigger('filter:click:checkbox', false); + } + + + object.remove(); + if (!objectList.find('li').length) { + objectList.parent('li').remove(); + } else { + //console.debug('ssssssssssssssss'); + } + + + if ($('#filter-current ul li').length) { //checkedAll || + showReset = true; + showApply = true; + } else { + showReset = false; + showApply = true; + } + $(".filter-buttons").trigger("filter:buttons:toggle"); + console.debug($('#filter-current ul li').length); + + return false; + }); + } + + $(document).on('click', '#filter-apply', function (e) { + $('#filter-apply').hide(); + showApply = true; //not chika: set false + $(this).trigger('filter:apply'); + $(this).trigger('filter:close'); + e.preventDefault(); + }); + + $(document).on('change', '#filter-form input[type="checkbox"],#filter-form input[type="radio"]', function (e) { + $(this).trigger('filter:click:checkbox', this.checked); + }); + + + $("#slider-price").on("slidechange", function (e, ui) { + var flag = false; + var objects = getSerializeObjects(); + if (!isMobile) { + filter_ajax(event, objects); + } else { + console.debug(e.type, ui.values); + if (ui.values[0] !== parseInt($('#min_price').data('default'))) { + flag = true; + } + + if (ui.values[1] !== parseInt($('#max_price').data('default'))) { + flag = true; + } + + showApply = flag + $(".filter-buttons").trigger("filter:buttons:toggle"); + + } + }); + + //for price inputs + $(document).on('change', '#filter-form #max_price,#filter-form #min_price', function (e) { + flagDeletePrices = false; + var slider = $("#filters .ui-slider"); + var min = slider.slider("option", "min"); + var max = slider.slider("option", "max"); + + var valueMin; + var valueMax; + + if (parseInt($('#max_price').val()) > max) { + valueMax = max; + $('#max_price').val(valueMax); + } else if (parseInt($('#max_price').val()) < min) { + valueMax = min; + $('#max_price').val(valueMax); + } else { + valueMax = parseInt($('#max_price').val()); + } + + if (parseInt($('#min_price').val()) < min) { + valueMin = min; + $('#min_price').val(valueMin); + } else if (parseInt($('#min_price').val()) > max) { + valueMin = max; + $('#min_price').val(valueMin); + } else { + valueMin = parseInt($('#min_price').val()); + } + + + slider.slider("values", [valueMin, valueMax]); + + filter_ajax(e, getSerializeObjects()); + if (e.cancelable) { + e.preventDefault(); + } + e.preventDefault(); + console.debug('change filter price input'); + }); + + + $(document).on('click', '#sorting-form button2', function (e) { + filter_ajax(e, getSerializeObjects()); + console.debug('#sorting-form button'); + e.preventDefault(); + return false; + }); + + $(document).on('click', '#sorting-form input[type="radio"]', function (e) { + filter_ajax(e, getSerializeObjects()); + console.debug('#sorting-form input[type="radio"]'); + e.preventDefault(); + return false; + }); + + $(document).on('change', '#sorting-form select', function (e) { + filter_ajax(e, getSerializeObjects()); + console.log('#sorting-form select'); + e.preventDefault(); + return false; + }); + + + /* + $('#sorting-form a').click(function (e) { + e.preventDefault(); + $.fn.yiiListView.update('shop-products', {url: $(this).attr('href')}); + history.pushState(null, $('title').text(), $(this).attr('href')); + console.log('click #sorting-form a'); + }); + */ +}); + + +function filterSearchInput(that, listId) { + // Declare variables + var value, ul, li, a, i, txtValue; + + value = $(that).val().toUpperCase(); + ul = document.getElementById(listId); + li = ul.getElementsByTagName('li'); + + // Loop through all list items, and hide those who don't match the search query + for (i = 0; i < li.length; i++) { + a = li[i].getElementsByTagName("label")[0]; + txtValue = a.textContent || a.innerText; + if (txtValue.toUpperCase().indexOf(value) > -1) { + li[i].style.display = ""; + } else { + li[i].style.display = "none"; + } + } +} diff --git a/widgets/filtersnew3/views/attributes.php b/widgets/filtersnew3/views/attributes.php new file mode 100644 index 00000000..5c720277 --- /dev/null +++ b/widgets/filtersnew3/views/attributes.php @@ -0,0 +1,94 @@ + 1 && $attrData['totalCount'] > 1) { + + ?> + +
+ +
+ + context->searchItem > 0 && $attrData['filtersCount'] >= $this->context->searchItem && !in_array($attrData['type'],[\panix\mod\shop\models\Attribute::TYPE_COLOR])) { ?> + + +
+
    + 0) { + $url = Yii::$app->urlManager->addUrlParam('/' . Yii::$app->requestedRoute, [$attrData['key'] => $filter['queryParam']], $attrData['selectMany']); + //} else { + // $url = 'javascript:void(0)'; + // + + $queryData = explode(',', Yii::$app->request->getQueryParam($attrData['key'])); + + echo Html::beginTag('li'); + // Filter link was selected. + + if (in_array($filter['queryParam'], $queryData)) { + $checked = true; + // Create link to clear current filter + $url = Yii::$app->urlManager->removeUrlParam('/' . Yii::$app->requestedRoute, $attrData['key'], $filter['queryParam']); + //echo Html::a($filter['title'], $url, array('class' => 'active')); + } else { + $checked = false; + //echo Html::a($filter['title'], $url); + } + + if ($attrData['type'] == \panix\mod\shop\models\Attribute::TYPE_COLOR) { + $css = $this->context->generateGradientCss($filter['data']); + + $checkedHtml = ($checked) ? '' : ''; + echo Html::label(Html::checkBox('filter[' . $attrData['key'] . '][]', $checked, ['class' => '', 'value' => $filter['queryParam'], 'id' => 'filter_' . $attrData['key'] . '_' . $filter['queryParam']]) . $checkedHtml, 'filter_' . $attrData['key'] . '_' . $filter['queryParam'], ['class' => 'filter-color', 'title' => $filter['title'] . ' (' . strip_tags($this->context->getCount($filter)) . ')', 'style' => $css]); + + + } else { + + + + if($attrData['selectMany']){ + echo '
    '; + echo Html::checkBox('filter[' . $attrData['key'] . '][]', $checked, ['class' => 'custom-control-input', 'value' => $filter['queryParam'], 'id' => 'filter_' . $attrData['key'] . '_' . $filter['queryParam']]); + echo Html::label($filter['title'].$this->context->getCount($filter), 'filter_' . $attrData['key'] . '_' . $filter['queryParam'], ['class' => 'custom-control-label']); + echo '
    '; + }else{ + echo '
    '; + echo Html::label(Html::radio('filter[' . $attrData['key'] . '][]', $checked, ['class' => '', 'value' => $filter['queryParam'], 'id' => 'filter_' . $attrData['key'] . '_' . $filter['queryParam']]).$filter['title'].$this->context->getCount($filter), 'filter_' . $attrData['key'] . '_' . $filter['queryParam'], ['class' => '']); + echo '
    '; + } + + + //var_dump($checked); + + // echo $this->context->getCount($filter); + } + + echo Html::endTag('li'); + } + } + ?> +
+
+
+
+ diff --git a/widgets/filtersnew3/views/brand.php b/widgets/filtersnew3/views/brand.php new file mode 100644 index 00000000..2e7d3d4a --- /dev/null +++ b/widgets/filtersnew3/views/brand.php @@ -0,0 +1,51 @@ + + 1) { ?> +
+ + + +
+ = 20 && $this->context->searchItem > 0) { ?> + + +
+
    + urlManager->addUrlParam('/' . Yii::$app->requestedRoute, [$filter['key'] => $filter['queryParam']], $brands['selectMany']); + $queryData = explode(',', Yii::$app->request->getQueryParam($filter['key'])); + + echo Html::beginTag('li'); + + + // Filter link was selected. + if (in_array($filter['queryParam'], $queryData)) { + // Create link to clear current filter + $checked = true; + $url = Yii::$app->urlManager->removeUrlParam('/' . Yii::$app->requestedRoute, $filter['key'], $filter['queryParam']); + //echo Html::a($filter['title'], $url, array('class' => 'active')); + } else { + $checked = false; + //echo Html::a($filter['title'], $url); + } + echo '
    '; + echo Html::checkBox('filter[' . $filter['key'] . '][]', $checked, ['class' => 'custom-control-input', 'value' => $filter['queryParam'], 'id' => 'filter_' . $filter['key'] . '_' . $filter['queryParam']]); + echo Html::label($filter['title'], 'filter_' . $filter['key'] . '_' . $filter['queryParam'],['class' => 'custom-control-label']); + + + echo $this->context->getCount($filter); + echo '
    '; + echo Html::endTag('li'); + } + ?> +
+
+
+
+ diff --git a/widgets/filtersnew3/views/current.php b/widgets/filtersnew3/views/current.php new file mode 100644 index 00000000..01bfa4cc --- /dev/null +++ b/widgets/filtersnew3/views/current.php @@ -0,0 +1,29 @@ + +
+
+
+
+
+ $active, + 'encodeLabels' => false + ]); + ?> +
+ + + +
diff --git a/widgets/filtersnew3/views/default.php b/widgets/filtersnew3/views/default.php new file mode 100644 index 00000000..8d014909 --- /dev/null +++ b/widgets/filtersnew3/views/default.php @@ -0,0 +1,55 @@ + +
+ 'filter-form','data-category_id'=>(isset($model->id))?$model->id:'']); + ?> +
+
+ + 'ajax_filter_current']); + if (!empty($active)) { + // echo Yii::$app->controller->refreshUrl; + $url = Yii::$app->controller->refreshUrl; + echo $this->render(Yii::$app->getModule('shop')->filterViewCurrent, ['active' => $active, 'dataModel' => $this->context->model, 'url' => $url]); + } + echo Html::endTag('div'); + ?> + + context->priceView) + echo $this->render($this->context->priceView, [ + 'priceMin' => $priceMin, + 'priceMax' => $priceMax, + 'currentPriceMin' => $currentPriceMin, + 'currentPriceMax' => $currentPriceMax, + ]); + + if ($this->context->brandView) + echo $this->render($this->context->brandView, ['brands' => $brands]); + + if ($this->context->attributeView) + echo $this->render($this->context->attributeView, ['attributes' => $attributes]); + + ?> +
+
+
+ 'btn btn-outline-secondary pl-3 pr-3', 'id' => 'filter-reset']) + ?> + ' col22 btn btn-danger pl-3 pr-3', 'id' => 'filter-apply']); ?> + + 'btn d-block btn-outline-secondary pl-3 pr-3', 'id' => 'filter-reset']); ?> +
+ + + +
diff --git a/widgets/filtersnew3/views/price.php b/widgets/filtersnew3/views/price.php new file mode 100644 index 00000000..4b01a0d4 --- /dev/null +++ b/widgets/filtersnew3/views/price.php @@ -0,0 +1,86 @@ +currency; + + +//if (($minPrice && $maxPrice) && ($minPrice !== $maxPrice)) { +$getDefaultMin = floor($priceMin); +$getDefaultMax = ceil($priceMax); + + + +$min = (int)floor($currentPriceMin); //$cm->convert() +$max = (int)ceil($currentPriceMax); +//echo $getDefaultMin; +//echo '
'; +//echo $getDefaultMax; +$valueMax = ($max) ? $max : $getDefaultMax; +$valueMin = ($min) ? $min : $getDefaultMin; +if ($getDefaultMin != $getDefaultMax) { + ?> + +
+ +
+
+ + + 'slider-price', + 'clientOptions' => [ + 'range' => true, + // 'disabled' => $getDefaultMin === $getDefaultMax, + 'min' => $getDefaultMin, //$prices['min'],//$min, + 'max' => $getDefaultMax, //$prices['max'],//$max, + 'values' => [$valueMin, $valueMax], + ], + 'clientEvents' => [ + + 'slide' => 'function(event, ui) { + $("#min_price").val(ui.values[0]); + $("#max_price").val(ui.values[1]); + $("#mn").text(price_format(ui.values[0])); + $("#mx").text(price_format(ui.values[1])); + }', + 'create' => 'function(event, ui){ + $("#min_price").val(' . $valueMin . '); + $("#max_price").val(' . $valueMax . '); + $("#mn").text("' . Yii::$app->currency->number_format($min) . '"); + $("#mx").text("' . Yii::$app->currency->number_format($max) . '"); + }' + ], + ]); + ?> + 'slide_default_price_min']); + //echo Html::hiddenInput('slide[default_price][]', $getDefaultMax, ['id' => 'slide_default_price_max']); + ?> + + от + 'min_price', 'data-default' => $getDefaultMin, 'class' => '']); + ?> + до + 'max_price', 'data-default' => $getDefaultMax, 'class' => '']); + ?> + currency->active['symbol'] ?> + + 'btn btn-sm btn-warning']); + ?> + +
+
+
+