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 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']); }); }
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])); }
/** * 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; }
public static function buildTextTree($id = null, $level = 1, $ban = []) { $return = []; $prefix = str_repeat('--', $level); $level++; if (empty($id)) { $categories = Category::find()->where('parent_id = 0 OR parent_id is null')->orderBy('sort DESC')->asArray()->all(); } else { $categories = Category::find()->where(['parent_id' => $id])->orderBy('sort DESC')->asArray()->all(); } foreach ($categories as $category) { if (!in_array($category['id'], $ban)) { $return[$category['id']] = "{$prefix} {$category['name']}"; $return = $return + self::buildTextTree($category['id'], $level, $ban); } } return $return; }
/** * @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; }
<?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
/** * @param null $id * @return string|\yii\web\Response * @throws NotFoundHttpException * @throws ServerErrorHttpException * @throws \Exception * @throws \yii\base\InvalidRouteException */ public function actionEdit($id = null) { /* * @todo Продумать механизм сохранения изображений для нового продукта. * Сейчас для нового продукта скрывается форма добавления изображений. */ if (null === ($object = Object::getForClass(Product::className()))) { throw new ServerErrorHttpException(); } /** @var null|Product|HasProperties|\devgroup\TagDependencyHelper\ActiveRecordHelper $model */ $model = null; $parent = null; if (null === $id) { $model = new Product(); $model->loadDefaultValues(); $parent_id = Yii::$app->request->get('owner_id', 0); if (0 !== intval($parent_id) && null !== Product::findById($parent_id)) { $model->parent_id = $parent_id; } $model->measure_id = $this->module->defaultMeasureId; } else { $model = Product::findById($id, null); if (null !== $model && $model->parent_id > 0) { $parent = Product::findById($model->parent_id, null); } } if (null === $model) { throw new NotFoundHttpException(); } $model->loadRelatedProductsArray(); $event = new BackendEntityEditEvent($model); $this->trigger(self::EVENT_BACKEND_PRODUCT_EDIT, $event); $post = \Yii::$app->request->post(); if ($event->isValid && $model->load($post)) { $saveStateEvent = new BackendEntityEditEvent($model); $this->trigger(self::EVENT_BACKEND_PRODUCT_EDIT_SAVE, $saveStateEvent); if ($model->validate()) { if (isset($post['GeneratePropertyValue'])) { $generateValues = $post['GeneratePropertyValue']; } else { $generateValues = []; } if (isset($post['PropertyGroup'])) { $model->option_generate = Json::encode(['group' => $post['PropertyGroup']['id'], 'values' => $generateValues]); } else { $model->option_generate = ''; } $save_result = $model->save(); $model->saveProperties($post); $model->saveRelatedProducts(); if (null !== ($view_object = ViewObject::getByModel($model, true))) { if ($view_object->load($post, 'ViewObject')) { if ($view_object->view_id <= 0) { $view_object->delete(); } else { $view_object->save(); } } } if ($save_result) { $modelAfterSaveEvent = new BackendEntityEditEvent($model); $this->trigger(self::EVENT_BACKEND_PRODUCT_AFTER_SAVE, $modelAfterSaveEvent); $categories = isset($post['Product']['categories']) ? $post['Product']['categories'] : []; $model->saveCategoriesBindings($categories); $this->runAction('save-info', ['model_id' => $model->id]); $model->invalidateTags(); $action = Yii::$app->request->post('action', 'save'); if (Yii::$app->request->post(HasProperties::FIELD_ADD_PROPERTY_GROUP) || Yii::$app->request->post(HasProperties::FIELD_REMOVE_PROPERTY_GROUP)) { $action = 'save'; } $returnUrl = Yii::$app->request->get('returnUrl', ['index']); switch ($action) { case 'next': return $this->redirect(['edit', 'returnUrl' => $returnUrl, 'parent_id' => Yii::$app->request->get('parent_id', null)]); case 'back': return $this->redirect($returnUrl); default: return $this->redirect(Url::toRoute(['edit', 'id' => $model->id, 'returnUrl' => $returnUrl, 'parent_id' => $model->main_category_id])); } } else { Yii::$app->session->setFlash('error', Yii::t('app', 'Cannot save data')); } } else { Yii::$app->session->setFlash('error', Yii::t('app', 'Cannot save data')); } } $items = ArrayHelper::map(Category::find()->all(), 'id', 'name'); return $this->render('product-form', ['object' => $object, 'model' => $model, 'items' => $items, 'selected' => $model->getCategoryIds(), 'parent' => $parent]); }
public function actionGenerate() { $ymlConfig = new Yml(); if (!$ymlConfig->loadConfig()) { return false; } static::$noimg = Yii::$app->getModule('image')->noImageSrc; if (1 == $ymlConfig->offer_param) { $this->prepareProperties(); } \Yii::$app->urlManager->setHostInfo($ymlConfig->shop_url); $filePath = \Yii::getAlias('@webroot') . '/' . $ymlConfig->general_yml_filename; $tpl = <<<'TPL' <name>%s</name> <company>%s</company> <url>%s</url> <currencies> <currency id="%s" rate="1" plus="0"/> </currencies> <categories> %s </categories> <store>%s</store> <pickup>%s</pickup> <delivery>%s</delivery> <local_delivery_cost>%s</local_delivery_cost> <adult>%s</adult> TPL; $section_categories = ''; $categories = Category::find()->where(['active' => 1])->asArray(); /** @var Category $row */ foreach ($categories->each(500) as $row) { $section_categories .= '<category id="' . $row['id'] . '" ' . (0 != $row['parent_id'] ? 'parentId="' . $row['parent_id'] . '"' : '') . '>' . htmlspecialchars(trim(strip_tags($row['name']))) . '</category>' . PHP_EOL; } unset($row, $categories); $section_shop = sprintf($tpl, $ymlConfig->shop_name, $ymlConfig->shop_company, $ymlConfig->shop_url, $ymlConfig->currency_id, $section_categories, 1 == $ymlConfig->shop_store ? 'true' : 'false', 1 == $ymlConfig->shop_pickup ? 'true' : 'false', 1 == $ymlConfig->shop_delivery ? 'true' : 'false', $ymlConfig->shop_local_delivery_cost, 1 == $ymlConfig->shop_adult ? 'true' : 'false'); $section_offers = ''; // $offer_type = ('simplified' === $ymlConfig->general_yml_type) ? '' : 'type="'.$ymlConfig->general_yml_type.'"'; $offer_type = ''; // временно, пока не будет окончательно дописан механизм для разных типов $products = Product::find()->where(['active' => 1]); /** @var Product $row */ foreach ($products->each(100) as $row) { $price = $this->getByYmlParam($ymlConfig, 'offer_price', $row, 0); $price = intval($price); if ($price <= 0 || $price >= 1000000000) { continue; } $offer = '<offer id="' . $row->id . '" ' . $offer_type . ' available="true">' . PHP_EOL; /** @var Category $category */ $category = $row->category; $category = empty($category) ? 1 : $category->category_group_id; $offer .= '<url>' . Url::to(['/shop/product/show', 'model' => $row, 'category_group_id' => $category], true) . '</url>' . PHP_EOL; $offer .= $this->wrapByYmlParam($ymlConfig, 'offer_price', $row, '<price>%s</price>' . PHP_EOL); $offer .= '<currencyId>' . $ymlConfig->currency_id . '</currencyId>' . PHP_EOL; $offer .= $this->wrapByYmlParam($ymlConfig, 'offer_category', $row, '<categoryId>%s</categoryId>' . PHP_EOL); $offer .= $this->wrapByYmlParam($ymlConfig, 'offer_picture', $row, function ($value) use($ymlConfig) { if (empty($value)) { return $value; } $value = '<picture>' . rtrim($ymlConfig->shop_url, '/') . $value . '</picture>' . PHP_EOL; return $value; }); $offer .= $this->wrapByYmlParam($ymlConfig, 'offer_name', $row, function ($value) use($ymlConfig) { if (mb_strlen($value) > 120) { $value = mb_substr($value, 0, 120); $value = mb_substr($value, 0, mb_strrpos($value, ' ')); } $value = '<name>' . htmlspecialchars(trim(strip_tags($value))) . '</name>' . PHP_EOL; return $value; }); $offer .= $this->wrapByYmlParam($ymlConfig, 'offer_description', $row, function ($value) use($ymlConfig) { if (mb_strlen($value) > 175) { $value = mb_substr($value, 0, 175); $value = mb_substr($value, 0, mb_strrpos($value, ' ')); } $value = '<description>' . htmlspecialchars(trim(strip_tags($value))) . '</description>' . PHP_EOL; return $value; }); if (1 == $ymlConfig->offer_param) { $offer .= $this->getValues($row); } $offer .= '</offer>'; $section_offers .= $offer . PHP_EOL; } unset($row, $products); $ymlFileTpl = <<<'TPL' <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE yml_catalog SYSTEM "shops.dtd"> <yml_catalog date="%s"> <shop> %s <offers> %s </offers> </shop> </yml_catalog> TPL; $fileString = sprintf($ymlFileTpl, date('Y-m-d H:i'), $section_shop, $section_offers); if (1 == $ymlConfig->use_gzip) { file_put_contents($filePath . '.gz', gzencode($fileString, 5)); } file_put_contents($filePath, $fileString); }
/** * @param YmlModel $config * @return array */ private function generateSectionShop(YmlModel $config) { return ['name' => $config->shop_name, 'company' => $config->shop_company, 'url' => $config->shop_url, 'currency' => $this->currency->iso_code, 'categories' => Category::find()->where(['active' => 1])->asArray(), 'store' => static::USE_STORE == $config->shop_store ? 'true' : 'false', 'pickup' => static::USE_PICKUP == $config->shop_pickup ? 'true' : 'false', 'delivery' => static::USE_DELIVERY == $config->shop_delivery ? 'true' : 'false', 'local_delivery_cost' => $config->shop_local_delivery_cost, 'adult' => static::USE_ADULT == $config->shop_adult ? 'true' : 'false']; }
public function getData() { $this->data = ArrayHelper::map(Category::find()->asArray()->all(), 'id', 'name'); return parent::getData(); }