public function actionIndex($category_id = null) { $searchModel = new Category(); $searchModel->active = 1; $params = Yii::$app->request->get(); $dataProvider = $searchModel->search($params); $selectedCategory = null; if ($category_id !== null) { $selectedCategory = Category::findById($category_id); } if ($selectedCategory !== null) { if (Yii::$app->request->isPost === true) { $newProperty = isset($_GET['add_property_id']) ? Property::findById($_GET['add_property_id']) : null; if ($newProperty !== null) { $filterSet = new FilterSets(); $filterSet->category_id = $selectedCategory->id; $filterSet->property_id = $newProperty->id; $filterSet->sort_order = 65535; $filterSet->save(); } } } $groups = PropertyGroup::getForObjectId(Object::getForClass(Product::className())->id, false); $propertiesDropdownItems = []; foreach ($groups as $group) { $item = ['label' => $group->name, 'url' => '#', 'items' => []]; $properties = Property::getForGroupId($group->id); foreach ($properties as $prop) { $item['items'][] = ['label' => $prop->name, 'url' => '?category_id=' . $category_id . '&add_property_id=' . $prop->id, 'linkOptions' => ['class' => 'add-property-to-filter-set', 'data-property-id' => $prop->id, 'data-action' => 'post']]; } $propertiesDropdownItems[] = $item; } return $this->render('index', ['dataProvider' => $dataProvider, 'searchModel' => $searchModel, 'selectedCategory' => $selectedCategory, 'propertiesDropdownItems' => $propertiesDropdownItems]); }
private function createCategory($name, $parent_id) { $model = new Category(); $model->loadDefaultValues(); $model->name = $name; $model->parent_id = $parent_id; $model->slug = Helper::createSlug($model->name); $model->save(); return $model; }
/** * @inheritdoc */ public function appendPart($route, $parameters = [], &$used_params = [], &$cacheTags = []) { /* В parameters должен храниться last_category_id Если его нет - используем parameters.category_id */ $category_id = null; if (isset($parameters['last_category_id'])) { $category_id = $parameters['last_category_id']; } elseif (isset($parameters['category_id'])) { $category_id = $parameters['category_id']; } $used_params[] = 'last_category_id'; $used_params[] = 'category_id'; if ($category_id === null) { return false; } $category = Category::findById($category_id); if (is_object($category) === true) { $parentIds = $category->getParentIds(); foreach ($parentIds as $id) { $cacheTags[] = ActiveRecordHelper::getObjectTag(Category::className(), $id); } $cacheTags[] = ActiveRecordHelper::getObjectTag(Category::className(), $category_id); return $category->getUrlPath($this->include_root_category); } else { return false; } }
/** * @return ActiveRecord */ public function getParent() { $cacheKey = 'TreeParent:' . $this->owner->className() . ':' . $this->owner->getAttribute($this->idAttribute); /** @var $parent ActiveRecord */ $parent = Yii::$app->cache->get($cacheKey); if ($parent === false) { $className = $this->owner->className(); $parent = new $className(); $parent_id = $this->owner->getAttribute($this->parentIdAttribute); if ($parent_id < 1) { return null; } /* findById does not have a calling standard and uses different parameters. For example isActive = 1. * But we must get a parent model by primary id only. * Uncomment this code if you unify findById method. */ // if ($parent->hasMethod('findById')) { // $parent = $parent->findById($parent_id); // } else { if ($parent instanceof Category) { $parent = Category::findById($parent_id, null); } else { $parent = $parent->findOne($parent_id); } Yii::$app->cache->set($cacheKey, $parent, 86400, new TagDependency(['tags' => [\devgroup\TagDependencyHelper\ActiveRecordHelper::getCommonTag($className)]])); } return $parent; }
public function run() { $query = Category::find(); $query->andWhere([Category::tableName() . '.active' => 1]); if ($this->root_category_id !== null) { $query->andWhere([Category::tableName() . '.parent_id' => $this->root_category_id]); } if ($this->category_group_id !== null) { $query->andWhere([Category::tableName() . '.category_group_id' => $this->category_group_id]); } $query->groupBy(Category::tableName() . ".id"); $query->orderBy($this->sort); if ($this->limit !== null) { $query->limit($this->limit); } $object = Object::getForClass(Category::className()); \app\properties\PropertiesHelper::appendPropertiesFilters($object, $query, $this->values_by_property_id, []); $sql = $query->createCommand()->getRawSql(); $cacheKey = "FilteredCategoriesWidget:" . md5($sql); $result = Yii::$app->cache->get($cacheKey); if ($result === false) { $categories = Category::findBySql($sql)->all(); $result = $this->render($this->viewFile, ['categories' => $categories]); Yii::$app->cache->set($cacheKey, $result, 86400, new \yii\caching\TagDependency(['tags' => ActiveRecordHelper::getCommonTag(Category::tableName())])); } return $result; }
protected function getLinks() { if (!is_null($this->frontendLink) || !is_null($this->backendLink)) { return true; } /** @var Image $image */ $image = Image::findById($this->img_id); if (is_null($image) || is_null($object = Object::findById($image->object_id))) { return false; } /** @var \app\models\Object $object */ switch ($object->object_class) { case Page::className(): $this->getPageLinks($image->object_model_id); break; case Category::className(): $this->getCategoryLinks($image->object_model_id); break; case Product::className(): $this->getProductLinks($image->object_model_id); break; default: return false; } return true; }
public function up() { $this->addColumn(Page::tableName(), 'mate_keywords', $this->string()->defaultValue(null)); $this->addColumn(Product::tableName(), 'mate_keywords', $this->string()->defaultValue(null)); $this->addColumn(Category::tableName(), 'mate_keywords', $this->string()->defaultValue(null)); $this->addColumn(PrefilteredPages::tableName(), 'mate_keywords', $this->string()->defaultValue(null)); }
public function down() { $this->dropColumn(Category::tableName(), 'date_added'); $this->dropColumn(Category::tableName(), 'date_modified'); $this->dropColumn(Product::tableName(), 'date_added'); $this->dropColumn(Product::tableName(), 'date_modified'); }
/** * @return string */ public function run() { parent::run(); if (null === $this->rootCategory) { return ''; } $cacheKey = $this->className() . ':' . implode('_', [$this->viewFile, $this->rootCategory, null === $this->depth ? 'null' : intval($this->depth), intval($this->includeRoot), intval($this->fetchModels), intval($this->onlyNonEmpty), implode(',', $this->excludedCategories), \Yii::$app->request->url]) . ':' . json_encode($this->additional); if (false !== ($cache = \Yii::$app->cache->get($cacheKey))) { return $cache; } /** @var array|Category[] $tree */ $tree = Category::getMenuItems(intval($this->rootCategory), $this->depth, boolval($this->fetchModels)); if (true === $this->includeRoot) { if (null !== ($_root = Category::findById(intval($this->rootCategory)))) { $tree = [['label' => $_root->name, 'url' => Url::toRoute(['@category', 'category_group_id' => $_root->category_group_id, 'last_category_id' => $_root->id]), 'id' => $_root->id, 'model' => $this->fetchModels ? $_root : null, 'items' => $tree]]; } } if (true === $this->onlyNonEmpty) { $_sq1 = (new Query())->select('main_category_id')->distinct()->from(Product::tableName()); $_sq2 = (new Query())->select('category_id')->distinct()->from('{{%product_category}}'); $_query = (new Query())->select('id')->from(Category::tableName())->andWhere(['not in', 'id', $_sq1])->andWhere(['not in', 'id', $_sq2])->all(); $this->excludedCategories = array_merge($this->excludedCategories, array_column($_query, 'id')); } $tree = $this->filterTree($tree); $cache = $this->render($this->viewFile, ['tree' => $tree, 'fetchModels' => $this->fetchModels, 'additional' => $this->additional, 'activeClass' => $this->activeClass, 'activateParents' => $this->activateParents]); \Yii::$app->cache->set($cacheKey, $cache, 0, new TagDependency(['tags' => [ActiveRecordHelper::getCommonTag(Category::className()), ActiveRecordHelper::getCommonTag(Product::className())]])); return $cache; }
private function recursiveGetTree($model, $allowed_category_ids) { $params = [$this->route]; $params += $this->current_selections; $params['category_group_id'] = $this->category_group_id; $params['last_category_id'] = $model->id; if (!isset($params['categories'])) { $params['categories'] = []; } $active = false; if (isset($this->current_selections['last_category_id'])) { $active = $this->current_selections['last_category_id'] == $model->id; } $result = ['label' => $model->name, 'url' => Url::to($params), 'items' => [], 'active' => in_array($model->id, $params['categories']) || $active, '_model' => &$model]; if ($this->recursive === true) { $children = Category::getByParentId($model->id); foreach ($children as $child) { if ($this->onlyAvailableProducts === true && !in_array($child->id, $allowed_category_ids)) { continue; } $result['items'][] = $this->recursiveGetTree($child, $allowed_category_ids); } } return $result; }
public function run() { $id = $this->getId(); $this->plugins = ArrayHelper::merge($this->plugins, ['checkbox']); $items = []; if (empty($this->selectedItems)) { $parent = Category::findById(Yii::$app->request->get('parent_id')); while ($parent instanceof Category) { $this->selectedItems[] = $parent->id; $parent = $parent->parent; } } $this->routes['getTree'] = ArrayHelper::merge($this->routes['getTree'], ['selectedItems' => implode(',', $this->selectedItems)]); if (isset($this->routes['edit'])) { $items['edit'] = ['label' => Yii::t('app', 'Edit'), 'icon' => 'fa fa-pencil', 'action' => new JsExpression("function (a) {\n var \$object = \$(a.reference[0]);\n document.location = " . Json::encode(Url::to($this->routes['edit'])) . "\n + '?id=' + \$object.attr('data-id') + '&parent_id=' +\n \$object.attr('data-parent-id');\n }")]; } if (isset($this->routes['open'])) { $items['open'] = ['label' => Yii::t('app', 'Open'), 'icon' => 'fa fa-folder-open', 'action' => new JsExpression("function (a) {\n var \$object = \$(a.reference[0]);\n document.location = " . Json::encode(Url::to($this->routes['open'])) . "\n + '?parent_id=' + \$object.attr('data-id');\n }")]; } if (isset($this->routes['create'])) { $items['create'] = ['label' => Yii::t('app', 'Create'), 'icon' => 'fa fa-plus-circle', 'action' => new JsExpression("function (a) {\n var \$object = \$(a.reference[0]);\n document.location = " . Json::encode(Url::to($this->routes['create'])) . "\n + '?parent_id=' + \$object.attr('data-id');\n }")]; } if (isset($this->routes['delete'])) { $items['delete'] = ['label' => Yii::t('app', 'Delete'), 'icon' => 'fa fa-trash-o', 'action' => new JsExpression("function (a) {\n var \$object = \$(a.reference[0]);\n document.location = " . Json::encode(Url::to($this->routes['delete'])) . "\n + '?id=' + \$object.attr('data-id');\n }")]; } $options = ['state' => ['key' => $this->stateKey], 'plugins' => $this->plugins, 'core' => ['check_callback' => true, 'data' => ['url' => new JsExpression("function (node) {\n return " . Json::encode(Url::to($this->routes['getTree'])) . ";\n }"), 'data' => new JsExpression("function (node) {\n return { 'id' : node.id };\n }")], 'multiple' => $this->multiple], 'checkbox' => ['three_state' => false], 'contextmenu' => ['items' => $items], 'dnd' => ['is_draggable' => false]]; if (count($this->types) > 0) { $options['types'] = $this->types; } $this->selectOptions['id'] = $id . '-select'; return $this->render('JSSelectableTree', ['id' => $id, 'flagFieldName' => $this->flagFieldName, 'fieldName' => $this->fieldName, 'model' => $this->model, 'multiple' => $this->multiple, 'options' => Json::encode($options), 'routes' => $this->routes, 'selectedItems' => $this->selectedItems, 'selectLabel' => $this->selectLabel, 'selectLabelOptions' => $this->selectLabelOptions, 'selectOptions' => $this->selectOptions, 'selectParents' => $this->selectParents]); }
protected function categoriesSitemap($parentId = 0, $prefix = '') { $categories = Category::find()->select(['id', 'category_group_id', 'slug'])->where(['parent_id' => $parentId, 'active' => 1])->asArray(true)->all(); array_reduce($categories, function ($carry, $item) use($prefix) { $this->sitemap->addUrl($prefix . '/' . $item['slug']); $this->categoriesSitemap($item['id'], $prefix . '/' . $item['slug']); $this->productsSitemap($item['id'], $prefix . '/' . $item['slug']); }); }
/** * @inheritdoc * @return string */ public function run() { $cacheKey = "PlainCategoriesWidget:" . $this->root_category_id . ":" . $this->viewFile; $result = Yii::$app->cache->get($cacheKey); if ($result === false) { $categories = Category::getByParentId($this->root_category_id); $result = $this->render($this->viewFile, ['categories' => $categories]); Yii::$app->cache->set($cacheKey, $result, 86400, new \yii\caching\TagDependency(['tags' => ActiveRecordHelper::getCommonTag(Category::className())])); } return $result; }
/** * @param $categoryId * @return FilterSets[] */ public static function getForCategoryId($categoryId) { Yii::beginProfile('FilterSets.GetForCategory ' . $categoryId); $category = Category::findById($categoryId); if ($category === null) { return []; } $categoryIds = $category->getParentIds(); $filter_sets = FilterSets::find()->where(['in', 'category_id', $categoryIds])->andWhere(['delegate_to_children' => 1])->orWhere(['category_id' => $category->id])->orderBy(['sort_order' => SORT_ASC])->all(); Yii::endProfile('FilterSets.GetForCategory ' . $categoryId); return $filter_sets; }
protected static function getProductType(Product $model) { if (!isset(self::$breadcrumbsData[$model->main_category_id])) { $parentIds = $model->getMainCategory()->getParentIds(); $breadcrumbs = []; foreach ($parentIds as $id) { $breadcrumbs[] = Category::find()->select(['name'])->where(['id' => $id])->asArray()->scalar(); } $breadcrumbs[] = $model->getMainCategory()->name; self::$breadcrumbsData[$model->main_category_id] = $breadcrumbs; } return htmlspecialchars(implode(' > ', self::$breadcrumbsData[$model->main_category_id])); }
/** * @param $categoryId * @return FilterSets[] */ public static function getForCategoryId($categoryId) { Yii::beginProfile('FilterSets.GetForCategory ' . $categoryId); $category = Category::findById($categoryId); if ($category === null) { return []; } $categoryIds = $category->getParentIds(); $filter_sets = Yii::$app->db->cache(function ($db) use($categoryIds, $category) { return FilterSets::find()->where(['in', 'category_id', $categoryIds])->andWhere(['delegate_to_children' => 1])->orWhere(['category_id' => $category->id])->orderBy(['sort_order' => SORT_ASC])->all(); }, 86400, new TagDependency(['tags' => [ActiveRecordHelper::getCommonTag(static::className())]])); Yii::endProfile('FilterSets.GetForCategory ' . $categoryId); return $filter_sets; }
public function run() { app\backend\assets\FrontendEditingAsset::register($this->view); $items = [['label' => Icon::show('dashboard') . ' ' . Yii::t('app', 'Backend'), 'url' => ['/backend/']]]; switch (Yii::$app->requestedRoute) { case 'shop/product/list': if (isset($_GET['properties'])) { $apply_if_params = []; foreach ($_GET['properties'] as $property_id => $values) { if (isset($values[0])) { $apply_if_params[$property_id] = $values[0]; } } if (Yii::$app->response->dynamic_content_trait === true) { $items[] = ['label' => Icon::show('puzzle') . ' ' . Yii::t('app', 'Edit Dynamic Content'), 'url' => ['/backend/dynamic-content/edit', 'id' => Yii::$app->response->matched_dynamic_content_trait_model->id]]; } else { if (isset($_GET['properties'], $_GET['last_category_id'])) { $items[] = ['label' => Icon::show('puzzle') . ' ' . Yii::t('app', 'Add Dynamic Content'), 'url' => ['/backend/dynamic-content/edit', 'DynamicContent' => ['apply_if_params' => Json::encode($apply_if_params), 'apply_if_last_category_id' => $_GET['last_category_id'], 'object_id' => Object::getForClass(app\modules\shop\models\Product::className())->id, 'route' => 'shop/product/list']]]; } } } else { // no properties selected - go to category edit page if (isset($_GET['last_category_id'])) { $reviewsLink = $this->getReviewEditParams("Category", intval($_GET['last_category_id'])); $cat = app\modules\shop\models\Category::findById($_GET['last_category_id']); $items[] = ['label' => Icon::show('pencil') . ' ' . Yii::t('app', 'Edit category'), 'url' => ['/shop/backend-category/edit', 'id' => $cat->id, 'parent_id' => $cat->parent_id]]; } } break; case 'shop/product/show': if (isset($_GET['model_id'])) { $reviewsLink = $this->getReviewEditParams("Product", intval($_GET['model_id'])); $items[] = ['label' => Icon::show('pencil') . ' ' . Yii::t('app', 'Edit product'), 'url' => ['/shop/backend-product/edit', 'id' => intval($_GET['model_id'])]]; } break; case '/page/page/show': case '/page/page/list': if (isset($_GET['id'])) { $page = app\modules\page\models\Page::findById($_GET['id']); $reviewsLink = $this->getReviewEditParams("Page", $_GET['id']); $items[] = ['label' => Icon::show('pencil') . ' ' . Yii::t('app', 'Edit page'), 'url' => ['/page/backend/edit', 'id' => $page->id, 'parent_id' => $page->parent_id]]; } break; } if (!empty($reviewsLink)) { $items[] = $reviewsLink; } return $this->render('floating-panel', ['items' => $items, 'bottom' => $this->bottom]); }
/** * Creates data provider instance with search query applied * * @param array $params * * @return ActiveDataProvider */ public function search($params) { $query = Category::find(); $dataProvider = new ActiveDataProvider(['query' => $query, 'pagination' => false, 'sort' => new \yii\data\Sort(['attributes' => ['name']])]); $this->load($params); if (!$this->validate()) { // uncomment the following line if you do not want to return any records when validation fails // $query->where('0=1'); return $dataProvider; } $query->andFilterWhere(['id' => $this->id, 'parent_id' => $this->parent_id]); $query->andFilterWhere(['like', 'name', $this->name]); $query->andFilterWhere(['like', 'text', $this->text]); return $dataProvider; }
/** * @inheritdoc */ public function getNextPart($full_url, $next_part, &$previous_parts) { if (mb_strpos($next_part, $this->static_part) === 0) { if (count($this->parameters) === 0) { $this->parameters = ['static_part' => $this->static_part]; } $cacheTags = []; if (isset($this->parameters['last_category_id']) && $this->parameters['last_category_id'] !== null) { $cacheTags[] = ActiveRecordHelper::getObjectTag(Category::className(), $this->parameters['last_category_id']); } $part = new self(['gathered_part' => $this->static_part, 'rest_part' => mb_substr($next_part, mb_strlen($this->static_part)), 'parameters' => $this->parameters, 'cacheTags' => $cacheTags]); return $part; } else { return false; } }
/** * @throws NotFoundHttpException * @throws ServerErrorHttpException */ public function init() { if (false === Yii::$app->request->isAjax) { throw new NotFoundHttpException('Page not found'); } $catId = Yii::$app->request->post('cat-id'); if (null !== Category::findOne(['id' => $catId])) { $this->categoryId = $catId; } else { throw new ServerErrorHttpException("Can't find Category with id {$catId}"); } if (true === empty(static::$object)) { static::$object = Object::getForClass(Product::className()); } $this->action = Yii::$app->request->post('action', ''); $this->items = Yii::$app->request->post('mc-items', []); parent::init(); }
public function up() { $this->addColumn('{{%theme_active_widgets}}', 'configuration_json', Schema::TYPE_TEXT); $this->insert('{{%theme_widgets}}', ['name' => Yii::t('app', 'Categories list'), 'widget' => 'app\\extensions\\DefaultTheme\\widgets\\CategoriesList\\Widget', 'configuration_model' => 'app\\extensions\\DefaultTheme\\widgets\\CategoriesList\\ConfigurationModel', 'configuration_view' => '@app/extensions/DefaultTheme/widgets/CategoriesList/views/_config.php', 'configuration_json' => '{}', 'is_cacheable' => 0, 'cache_tags' => \app\modules\shop\models\Category::className()]); $categoriesListWidgetId = $this->db->lastInsertID; $this->insert('{{%theme_widgets}}', ['name' => Yii::t('app', 'Filter widget'), 'widget' => 'app\\extensions\\DefaultTheme\\widgets\\FilterSets\\Widget', 'configuration_model' => 'app\\extensions\\DefaultTheme\\widgets\\FilterSets\\ConfigurationModel', 'configuration_view' => '@app/extensions/DefaultTheme/widgets/FilterSets/views/_config.php', 'configuration_json' => '{}', 'is_cacheable' => 0, 'cache_tags' => '']); $filterSetsWidget = $this->db->lastInsertID; $this->insert('{{%theme_widgets}}', ['name' => Yii::t('app', 'Pages list'), 'widget' => 'app\\extensions\\DefaultTheme\\widgets\\PagesList\\Widget', 'configuration_model' => 'app\\extensions\\DefaultTheme\\widgets\\PagesList\\ConfigurationModel', 'configuration_view' => '@app/extensions/DefaultTheme/widgets/PagesList/views/_config.php', 'configuration_json' => '{}', 'is_cacheable' => 1, 'cache_lifetime' => 86400, 'cache_tags' => \app\modules\page\models\Page::className()]); $pagesList = $this->db->lastInsertID; $this->insert('{{%theme_widgets}}', ['name' => Yii::t('app', 'Content block'), 'widget' => 'app\\extensions\\DefaultTheme\\widgets\\ContentBlock\\Widget', 'configuration_model' => 'app\\extensions\\DefaultTheme\\widgets\\ContentBlock\\ConfigurationModel', 'configuration_view' => '@app/extensions/DefaultTheme/widgets/ContentBlock/views/_config.php', 'configuration_json' => '{}', 'is_cacheable' => 1, 'cache_lifetime' => 86400, 'cache_tags' => \app\modules\page\models\Page::className()]); $contentBlock = $this->db->lastInsertID; $allBlocks = [$categoriesListWidgetId, $filterSetsWidget, $pagesList, $contentBlock]; foreach ($allBlocks as $widget_id) { // left sidebar $this->insert('{{%theme_widget_applying}}', ['widget_id' => $widget_id, 'part_id' => 5]); // right sidebar $this->insert('{{%theme_widget_applying}}', ['widget_id' => $widget_id, 'part_id' => 8]); } }
public function appendPart($route, $parameters = [], &$used_params = [], &$cacheTags = []) { $used_params[] = 'categories'; $used_params[] = 'category_group_id'; $used_params[] = $this->model_category_attribute; $attribute_name = $this->model_category_attribute; $category_id = $this->model->{$attribute_name}; /** @var Category $category */ $category = Category::findById($category_id); if (is_object($category) === true) { $parentIds = $category->getParentIds(); foreach ($parentIds as $id) { $cacheTags[] = ActiveRecordHelper::getObjectTag(Category::className(), $id); } $cacheTags[] = ActiveRecordHelper::getObjectTag(Category::className(), $category_id); return $category->getUrlPath($this->include_root_category); } else { return false; } }
/** * @inheritdoc */ public function init() { if (!isset($this->url, $this->gridSelector)) { throw new InvalidParamException('Attribute \'url\' or \'gridSelector\' is not set'); } if (true === empty($this->moveText)) { $this->moveText = Yii::t('app', 'Are you sure you want to move all selected products into'); } if (true === empty($this->addText)) { $this->addText = Yii::t('app', 'Are you sure you want to add all selected products into'); } if (!isset($this->htmlOptions['id'])) { $this->htmlOptions['id'] = ''; } if (true === empty(static::$categories)) { $cc = Category::find()->select('id, name')->where(['active' => 1])->asArray(true)->all(); foreach ($cc as $k => $cat) { static::$categories[$cat['id']] = $cat['name']; } } }
/** * @deprecated * @param $category_group_id * @param int $level * @param int $is_active * @return Category[] */ public static function getByLevel($category_group_id, $level = 0, $is_active = 1) { $cacheKey = "CategoriesByLevel:{$category_group_id}:{$level}"; if (false === ($models = Yii::$app->cache->get($cacheKey))) { $models = Category::find()->where(['category_group_id' => $category_group_id, 'parent_id' => $level, 'active' => $is_active])->orderBy('sort_order')->with('images')->all(); if (null !== $models) { $cache_tags = []; foreach ($models as $model) { $cache_tags[] = ActiveRecordHelper::getObjectTag($model, $model->id); } $cache_tags[] = ActiveRecordHelper::getObjectTag(static::className(), $level); Yii::$app->cache->set($cacheKey, $models, 86400, new TagDependency(['tags' => $cache_tags])); } } foreach ($models as $model) { static::$identity_map[$model->id] = $model; } return $models; }
/** * This function build array for widget "Breadcrumbs" * @param Category $selCat - model of current category * @param Product|null $product - model of product, if current page is a page of product * @param array $properties - array of properties and static values * Return an array for widget or empty array */ private function buildBreadcrumbsArray($selCat, $product = null, $properties = []) { if ($selCat === null) { return []; } // init $breadcrumbs = []; if ($product !== null) { $crumbs[$product->slug] = !empty($product->breadcrumbs_label) ? $product->breadcrumbs_label : ''; } $crumbs[$selCat->slug] = $selCat->breadcrumbs_label; // get basic data $parent = $selCat->parent_id > 0 ? Category::findById($selCat->parent_id) : null; while ($parent !== null) { $crumbs[$parent->slug] = $parent->breadcrumbs_label; $parent = $parent->parent; } // build array for widget $url = ''; $crumbs = array_reverse($crumbs, true); foreach ($crumbs as $slug => $label) { $url .= '/' . $slug; $breadcrumbs[] = ['label' => $label, 'url' => $url]; } if (is_null($product) && $this->module->showFiltersInBreadcrumbs && !empty($properties)) { $route = ['@category', 'last_category_id' => $selCat->id, 'category_group_id' => $selCat->category_group_id]; $params = []; foreach ($properties as $propertyId => $propertyStaticValues) { $localParams = $params; foreach ($propertyStaticValues as $propertyStaticValue) { $psv = PropertyStaticValues::findById($propertyStaticValue); if (is_null($psv)) { continue; } $localParams[$propertyId][] = $propertyStaticValue; $breadcrumbs[] = ['label' => $psv['name'], 'url' => array_merge($route, ['properties' => $localParams])]; } $params[$propertyId] = $propertyStaticValues; } } unset($breadcrumbs[count($breadcrumbs) - 1]['url']); // last item is not a link if (isset(Yii::$app->response->blocks['breadcrumbs_label'])) { // last item label rewrited through prefiltered page or something similar $breadcrumbs[count($breadcrumbs) - 1]['label'] = Yii::$app->response->blocks['breadcrumbs_label']; } return $breadcrumbs; }
/** * @return array */ public function actionAjaxSearch() { Yii::$app->response->format = Response::FORMAT_JSON; $search = \Yii::$app->request->get('search', []); $object = !empty($search['object']) ? intval($search['object']) : 0; $term = !empty($search['term']) ? $search['term'] : ''; $result = ['more' => false, 'results' => []]; if (null === ($object = Object::findById($object))) { return $result; } /** @var ActiveRecord $class */ $class = $object->object_class; $list = [Product::className(), Category::className(), Page::className()]; if (!in_array($class, $list)) { return $result; } $query = $class::find()->select('id, name, "#" `url`')->andWhere(['like', 'name', $term])->asArray(true); $result['results'] = array_values($query->all()); array_walk($result['results'], function (&$val) use($class) { if (null !== ($model = $class::findOne(['id' => $val['id']]))) { if (Product::className() === $model->className()) { $val['url'] = Url::toRoute(['@product', 'model' => $model, 'category_group_id' => $model->category->category_group_id]); } elseif (Category::className() === $model->className()) { $val['url'] = Url::toRoute(['@category', 'last_category_id' => $model->id, 'category_group_id' => $model->category_group_id]); } else { if (Page::className() === $model->className()) { $val['url'] = Url::toRoute(['@article', 'id' => $model->id]); } } } }); return $result; }
public static function renderEcommerceCounters(Event $event) { $order = Order::findOne(['id' => $event->data['orderId']]); $config = Config::getModelByKey('ecommerceCounters'); if (empty($event->data['orderId']) || empty($config) || empty($order)) { return; } $orderItems = OrderItem::findAll(['order_id' => $event->data['orderId']]); if (!empty($orderItems)) { $products = []; foreach ($orderItems as $item) { $product = Product::findById($item->product_id, null, null); if (empty($product)) { continue; } $category = Category::findById($product->main_category_id); $category = empty($category) ? 'Магазин' : str_replace('\'', '', $category->name); $products[] = ['id' => $product->id, 'name' => str_replace('\'', '', $product->name), 'price' => number_format($product->price, 2, '.', ''), 'category' => $category, 'qnt' => $item->quantity]; } $order = ['id' => $order->id, 'total' => number_format($order->total_price, 2, '.', '')]; echo Yii::$app->view->renderFile(Yii::getAlias('@app/modules/seo/views/manage/_ecommerceCounters.php'), ['order' => $order, 'products' => $products, 'config' => Json::decode($config->value)]); } }
?> </article> </div> </section> <input type="hidden" name="DynamicContent[apply_if_params]" id="apply_if_params"> <?php BackendWidget::begin(['title' => Yii::t('app', 'Match settings'), 'icon' => 'cogs', 'footer' => $this->blocks['submit']]); ?> <div id="properties"> <?php $url = Url::to(['/shop/backend-category/autocomplete']); $category = $model->apply_if_last_category_id > 0 ? \app\modules\shop\models\Category::findById($model->apply_if_last_category_id) : null; ?> <?php echo $form->field($model, 'apply_if_last_category_id')->widget(Select2::classname(), ['options' => ['placeholder' => 'Search for a category ...'], 'pluginOptions' => ['allowClear' => true, 'ajax' => ['url' => $url, 'dataType' => 'json', 'data' => new JsExpression('function(term,page) { return {search:term}; }'), 'results' => new JsExpression('function(data,page) { return {results:data.results}; }')]], 'initValueText' => !is_null($category) ? $category->name : '']); ?> <div class="row"> <div class="col-md-10 col-md-offset-2"> <a href="#" class="btn btn-md btn-primary add-property"> <?php echo Icon::show('plus'); ?> <?php echo Yii::t('app', 'Add property'); ?> </a> <br>
<?php echo $form->field($model, 'content')->widget(Yii::$app->getModule('core')->wysiwyg_class_name(), Yii::$app->getModule('core')->wysiwyg_params()); ?> <?php echo $form->field($model, 'sort_order'); ?> <?php echo $form->field($model, 'date_added')->widget(DateTimePicker::classname(), ['pluginOptions' => ['autoclose' => true, 'format' => 'yyyy-mm-dd hh:ii', 'todayHighlight' => true, 'todayBtn' => true]]); ?> <?php if ($model->isNewRecord === false) { echo $form->field($model, 'parent_id')->dropDownList(ArrayHelper::merge([0 => Yii::t('app', 'Root')], ArrayHelper::map(\app\modules\shop\models\Category::find()->where('id != :id', ['id' => $model->id])->all(), 'id', 'name'))); } ?> <?php BackendWidget::end(); ?> <?php BackendWidget::begin(['title' => Yii::t('app', 'Images'), 'icon' => 'image', 'footer' => $this->blocks['submit']]); ?> <div id="actions"> <?php echo \yii\helpers\Html::tag('span', Icon::show('plus') . Yii::t('app', 'Add files..'), ['class' => 'btn btn-success fileinput-button']); ?> <?php
use kartik\icons\Icon; use app\backend\widgets\BackendWidget; use yii\helpers\ArrayHelper; $this->title = Yii::t('app', 'Settings'); $this->params['breadcrumbs'][] = 'Google Feed'; \app\backend\assets\YmlAsset::register($this); $formName = 'YmlSettings'; $currencies = ArrayHelper::map(\app\modules\shop\models\Currency::find()->select('iso_code')->orderBy(['is_main' => SORT_DESC, 'sort_order' => SORT_ASC, 'iso_code' => SORT_ASC])->asArray()->all(), 'iso_code', 'iso_code'); ?> <?php echo app\widgets\Alert::widget(['id' => 'alert']); ?> <?php $feed_relations = ['getImage' => \app\modules\image\models\Image::className(), 'getMainCategory' => \app\modules\shop\models\Category::className()]; $feed_settings = []; $feed_settings['product_fields'] = (new \app\modules\shop\models\Product())->attributeLabels(); $feed_settings['relations_keys'] = array_combine(array_keys($feed_relations), array_keys($feed_relations)); $feed_settings['relations_map'] = []; foreach ($feed_relations as $key => $value) { $_fields = (new $value())->attributeLabels(); $feed_settings['relations_map'][$key] = ['fields' => $_fields, 'html' => array_reduce($_fields, function ($result, $i) { $result .= '<option value="' . addslashes(htmlspecialchars($i)) . '">' . addslashes(htmlspecialchars($i)) . '</option>'; return $result; }, '')]; } if (true === isset($feed_settings['relations_map']['getImage'])) { $feed_settings['relations_map']['getImage']['fields']['file'] = Yii::t('app', 'File'); $feed_settings['relations_map']['getImage']['html'] .= '<option value="file">' . Yii::t('app', 'File') . '</option>'; }