/** * Get or create new instance of category * * @return \Magento\Catalog\Model\Product */ private function _getCategory() { if (!$this->hasData('category')) { $this->setCategory($this->_categoryFactory->create()); } return $this->getCategory(); }
/** * Get parent category options * * @return array */ protected function _getParentCategoryOptions() { $items = $this->_categoryFactory->create()->getCollection()->addAttributeToSelect('name')->addAttributeToSort('entity_id', 'ASC')->setPageSize(3)->load()->getItems(); $result = array(); if (count($items) === 2) { $item = array_pop($items); $result = array($item->getEntityId() => $item->getName()); } return $result; }
/** * @param int $id * @return CategoryModel * @throws \Magento\Framework\Exception\NoSuchEntityException */ private function getCategory($id) { /** @var CategoryModel $category */ $category = $this->categoryFactory->create(); $category->load($id); if (!$category->getId()) { throw NoSuchEntityException::singleField(Category::ID, $id); } return $category; }
/** * @param int $categoryId * @return Category * @throws \Magento\Framework\Exception\NoSuchEntityException */ public function load($categoryId) { /** @var Category $category */ $category = $this->categoryFactory->create(); $category->load($categoryId); if (!$category->getId()) { throw new NoSuchEntityException('There is no category with provided ID'); } return $category; }
/** * {@inheritdoc} */ public function tree($rootCategoryId = null, $depth = null) { $category = null; if (!is_null($rootCategoryId)) { /** @var \Magento\Catalog\Model\Category $category */ $category = $this->categoryFactory->create()->load($rootCategoryId); if (!$category->getId()) { throw new \Magento\Framework\Exception\NoSuchEntityException('Root Category does not exist'); } } $result = $this->categoryTree->getTree($this->categoryTree->getRootNode($category), $depth); return $result; }
/** * Get all categories * * @param bool $sorted * @param bool $asCollection * @param bool $toLoad * * @return array|\Magento\Catalog\Model\ResourceModel\Category\Collection|\Magento\Framework\Data\Tree\Node\Collection */ public function getCategories($sorted = false, $asCollection = false, $toLoad = true) { $cacheKey = sprintf('%d-%d-%d-%d', $this->getSelectedRootCategory(), $sorted, $asCollection, $toLoad); if (isset($this->_storeCategories[$cacheKey])) { return $this->_storeCategories[$cacheKey]; } /** * Check if parent node of the store still exists */ $category = $this->_categoryFactory->create(); $storeCategories = $category->getCategories($this->getSelectedRootCategory(), $recursionLevel = 1, $sorted, $asCollection, $toLoad); $this->_storeCategories[$cacheKey] = $storeCategories; return $storeCategories; }
/** * Creates a category. * * @param string $name * @param int $parentId * * @return int */ protected function createCategory($name, $parentId) { /** @var \Magento\Catalog\Model\Category $category */ $category = $this->categoryFactory->create(); $parentCategory = $this->categoryFactory->create()->load($parentId); $category->setPath($parentCategory->getPath()); $category->setParentId($parentId); $category->setName($name); $category->setIsActive(true); $category->setIncludeInMenu(true); $category->setAttributeSetId($category->getDefaultAttributeSetId()); $category->save(); return $category->getId(); }
/** * Set current attribute to entry (for specified product) * * @param \Magento\Catalog\Model\Product $product * @param \Magento\Framework\Gdata\Gshopping\Entry $entry * @return \Magento\Framework\Gdata\Gshopping\Entry */ public function convertAttribute($product, $entry) { $productCategories = $product->getCategoryIds(); // TODO: set Default value for product_type attribute if product isn't assigned for any category $value = 'Shop'; if (!empty($productCategories)) { $category = $this->_categoryFactory->create()->load(array_shift($productCategories)); $breadcrumbs = array(); foreach ($category->getParentCategories() as $cat) { $breadcrumbs[] = $cat->getName(); } $value = implode(' > ', $breadcrumbs); } $this->_setAttribute($entry, 'product_type', self::ATTRIBUTE_TYPE_TEXT, $value); return $entry; }
/** * Retrieve loaded category collection * * @return AbstractCollection */ protected function _getProductCollection() { if (is_null($this->_productCollection)) { $layer = $this->getLayer(); /* @var $layer \Magento\Catalog\Model\Layer */ if ($this->getShowRootCategory()) { $this->setCategoryId($this->_storeManager->getStore()->getRootCategoryId()); } // if this is a product view page if ($this->_coreRegistry->registry('product')) { // get collection of categories this product is associated with $categories = $this->_coreRegistry->registry('product')->getCategoryCollection()->setPage(1, 1)->load(); // if the product is associated with any category if ($categories->count()) { // show products from this category $this->setCategoryId(current($categories->getIterator())); } } $origCategory = null; if ($this->getCategoryId()) { /** @var \Magento\Catalog\Model\Category $category */ $category = $this->_categoryFactory->create()->load($this->getCategoryId()); if ($category->getId()) { $origCategory = $layer->getCurrentCategory(); $layer->setCurrentCategory($category); } } $this->_productCollection = $layer->getProductCollection(); $this->prepareSortableFieldsByCategory($layer->getCurrentCategory()); if ($origCategory) { $layer->setCurrentCategory($origCategory); } } return $this->_productCollection; }
/** * Retrieve category url * * @param ModelCategory $category * @return string */ public function getCategoryUrl($category) { if ($category instanceof ModelCategory) { return $category->getUrl(); } return $this->_categoryFactory->create()->setData($category->getData())->getUrl(); }
/** * @return \Magento\Catalog\Model\Category */ protected function getTreeRootCategory() { if (!$this->treeRootCategory) { $this->treeRootCategory = $this->categoryFactory->create()->load(Category::TREE_ROOT_ID); } return $this->treeRootCategory; }
/** * Load current category using the request params. * * @return CategoryInterface */ private function loadCategory() { $category = $this->categoryFactory->create(); $storeId = $this->getRequest()->getParam('store'); $categoryId = $this->getRequest()->getParam('entity_id'); $category->setStoreId($storeId)->load($categoryId); return $category; }
/** * Get categories collection * * @return \Magento\Catalog\Model\ResourceModel\Category\Collection */ public function getCategoryCollection() { $collection = $this->_getData('category_collection'); if ($collection === null) { $collection = $this->_categoryFactory->create()->getCollection()->addAttributeToSelect(['name', 'is_active'])->setLoadProductCount(true); $this->setData('category_collection', $collection); } return $collection; }
/** * Load category * * @param int $id * @throws \Magento\Framework\Exception\NoSuchEntityException * @return \Magento\Catalog\Model\Category */ protected function loadCategory($id) { $model = $this->categoryFactory->create(); $model->load($id); if (!$model->getId()) { throw NoSuchEntityException::singleField(CategoryDataObject::ID, $id); } return $model; }
/** * Get last purchased category. * * @return string */ public function getLastCategoryPur() { $categoryId = $this->customer->getLastCategoryId(); //customer last category id if ($categoryId) { return $this->categoryFactory->create()->setStoreId($this->customer->getStoreId())->load($categoryId)->getName(); } return ''; }
/** * Return array of options as value-label pairs * * @return array Format: array(array('value' => '<value>', 'label' => '<label>'), ...) */ public function toOptionArray() { $cacheKey = sprintf('%d-%d-%d-%d', 1, false, false, true); if (isset($this->_storeCategories[$cacheKey])) { return $this->_storeCategories[$cacheKey]; } /** * Check if parent node of the store still exists */ $category = $this->_categoryFactory->create(); $storeCategories = $category->getCategories(1, $recursionLevel = 1, false, false, true); $this->_storeCategories[$cacheKey] = $storeCategories; $resultArray = []; foreach ($storeCategories as $category) { $resultArray[$category->getId()] = $category->getName(); } return $resultArray; }
/** * Load the root category used for a virtual category. * * @param CategoryInterface $category Virtual category. * * @return CategoryInterface */ private function getVirtualRootCategory(CategoryInterface $category) { $storeId = $this->getStoreId(); $rootCategory = $this->categoryFactory->create()->setStoreId($storeId); if ($category->getVirtualCategoryRoot() !== null && !empty($category->getVirtualCategoryRoot())) { $rootCategoryId = $category->getVirtualCategoryRoot(); $rootCategory->load($rootCategoryId); } return $rootCategory; }
/** * Get selected category object * * @return \Magento\Catalog\Model\Category */ public function getCategory() { if (!is_null($this->_categoryId)) { /** @var \Magento\Catalog\Model\Category $category */ $category = $this->_categoryFactory->create()->load($this->_categoryId); if ($category->getId()) { return $category; } } return $this->getLayer()->getCurrentCategory(); }
/** * @param int $rootCategoryId * @param int $storeId * @return array */ protected function generateCategoryUrls($rootCategoryId, $storeId) { $urls = []; $categories = $this->categoryFactory->create()->getCategories($rootCategoryId, 1, false, true); foreach ($categories as $category) { /** @var \Magento\Catalog\Model\Category $category */ $category->setStoreId($storeId); $urls = array_merge($urls, $this->categoryUrlRewriteGenerator->generate($category)); } return $urls; }
/** * @return \Magento\Framework\Model\Resource\Db\Collection\AbstractCollection */ public function getCategoryCollection() { $storeId = $this->getRequest()->getParam('store', $this->_getDefaultStoreId()); $collection = $this->getData('category_collection'); if (is_null($collection)) { $collection = $this->_categoryFactory->create()->getCollection(); $collection->addAttributeToSelect('name')->addAttributeToSelect('is_active')->setProductStoreId($storeId)->setLoadProductCount($this->_withProductCount)->setStoreId($storeId); $this->setData('category_collection', $collection); } return $collection; }
/** * @param array $row * @return void */ protected function createCategory($row) { $category = $this->getCategoryByPath($row['path'] . '/' . $row['name']); if (!$category) { $parentCategory = $this->getCategoryByPath($row['path']); $data = ['parent_id' => $parentCategory->getId(), 'name' => $row['name'], 'is_active' => $row['active'], 'is_anchor' => $row['is_anchor'], 'include_in_menu' => $row['include_in_menu'], 'url_key' => $row['url_key']]; $category = $this->categoryFactory->create(); $category->setData($data)->setPath($parentCategory->getData('path'))->setAttributeSetId($category->getDefaultAttributeSetId()); $this->setAdditionalData($row, $category); $category->save(); } }
/** * Get product collection. * * @return array */ public function getLoadedProductCollection() { $productsToDisplay = []; $mode = $this->getRequest()->getActionName(); $limit = $this->recommnededHelper->getDisplayLimitByMode($mode); $from = $this->recommnededHelper->getTimeFromConfig($mode); $to = $this->_localeDate->date()->format(\Zend_Date::ISO_8601); $reportProductCollection = $this->reportProductCollection->create()->addViewsCount($from, $to)->setPageSize($limit); //filter collection by category by category_id if ($catId = $this->getRequest()->getParam('category_id')) { $category = $this->categoryFactory->create()->load($catId); if ($category->getId()) { $reportProductCollection->getSelect()->joinLeft(['ccpi' => $this->coreResource->getTableName('catalog_category_product_index')], 'e.entity_id = ccpi.product_id', ['category_id'])->where('ccpi.category_id =?', $catId); } else { $this->helper->log('Most viewed. Category id ' . $catId . ' is invalid. It does not exist.'); } } //filter collection by category by category_name if ($catName = $this->getRequest()->getParam('category_name')) { $category = $this->categoryFactory->create()->loadByAttribute('name', $catName); if ($category) { $reportProductCollection->getSelect()->joinLeft(['ccpi' => $this->coreResource->getTableName('catalog_category_product_index')], 'e.entity_id = ccpi.product_id', ['category_id'])->where('ccpi.category_id =?', $category->getId()); } else { $this->helper->log('Most viewed. Category name ' . $catName . ' is invalid. It does not exist.'); } } //product ids from the report product collection $productIds = $reportProductCollection->getColumnValues('entity_id'); $productCollectionFactory = $this->productCollectionFactory->create(); $productCollectionFactory->addIdFilter($productIds)->addAttributeToSelect(['product_url', 'name', 'store_id', 'small_image', 'price']); //product collection foreach ($productCollectionFactory as $_product) { //add only saleable products if ($_product->isSalable()) { $productsToDisplay[] = $_product; } } return $productsToDisplay; }
/** * @param CategoryDataObject $category * @param \Magento\Catalog\Model\Category $categoryModel * @return \Magento\Catalog\Model\Category * @throws \RuntimeException */ public function toModel(CategoryDataObject $category, \Magento\Catalog\Model\Category $categoryModel = null) { $categoryModel = $categoryModel ?: $this->categoryFactory->create(); $data = EavDataObjectConverter::toFlatArray($category); /** @see /app/code/Magento/Catalog/Controller/Adminhtml/Category.php method "_filterCategoryPostData" */ if (isset($data['image']) && is_array($data['image'])) { $data['image_additional_data'] = $data['image']; unset($data['image']); } // this fields should not be changed $data[CategoryDataObject::ID] = $categoryModel->getId(); $data[CategoryDataObject::PARENT_ID] = $categoryModel->getParentId(); $data[CategoryDataObject::PATH] = $categoryModel->getPath(); /** fill required fields */ $data['is_active'] = $category->isActive(); $data['include_in_menu'] = isset($data['include_in_menu']) ? (bool) $data['include_in_menu'] : false; $categoryModel->addData($data); if (!is_numeric($categoryModel->getAttributeSetId())) { $categoryModel->setAttributeSetId($categoryModel->getDefaultAttributeSetId()); } return $categoryModel; }
/** * List of parent categories * * @param int $categoryId * @return \Magento\Catalog\Model\Category[] */ public function getFullPath($categoryId) { $store = $this->storeManager->getStore(); $rootId = $store->getRootCategoryId(); $result = []; $id = $categoryId; do { $parent = $this->categoryFactory->create()->load($id)->getParentCategory(); $id = $parent->getId(); if (!$parent->getId()) { break; } if (!$parent->getIsActive() && $parent->getId() != $rootId) { break; //return false; } if ($parent->getId() != $rootId) { $result[] = $parent; } } while ($parent->getId() != $rootId); $result = array_reverse($result); return $result; }
/** * Returns a random product category * * @return \Magento\Framework\DataObject * @throws \Exception * @throws \Magento\Framework\Exception\LocalizedException */ protected function getProductCategory() { if (NULL == $this->availableCategories) { /** @var \Magento\Catalog\Model\ResourceModel\Category\Collection $categoriesCollection */ $categoriesCollection = $this->categoryFactory->create()->getCollection(); $categoriesCollection->addAttributeToFilter('entity_id', ['gt' => '0'])->addIsActiveFilter(); $this->availableCategories = $categoriesCollection->getItems(); } if (count($this->availableCategories) > 0) { return $this->availableCategories[array_rand($this->availableCategories)]; } else { throw new \Exception("There are no categories available in the store"); } }
/** * Refresh entities index * * @param int[] $entityIds * @param bool $useTempTable * @return Rows */ public function reindex(array $entityIds = array(), $useTempTable = false) { $stores = $this->storeManager->getStores(); /* @var $category \Magento\Catalog\Model\Category */ $category = $this->categoryFactory->create(); /* @var $store \Magento\Store\Model\Store */ foreach ($stores as $store) { $tableName = $this->getTableNameByStore($store, $useTempTable); if (!$this->getWriteAdapter()->isTableExists($tableName)) { continue; } /** @TODO Do something with chunks */ $categoriesIdsChunks = array_chunk($entityIds, 500); foreach ($categoriesIdsChunks as $categoriesIdsChunk) { $categoriesIdsChunk = $this->filterIdsByStore($categoriesIdsChunk, $store); $attributesData = $this->getAttributeValues($categoriesIdsChunk, $store->getId()); $data = array(); foreach ($categoriesIdsChunk as $categoryId) { if (!isset($attributesData[$categoryId])) { continue; } if ($category->load($categoryId)->getId()) { $data[] = $this->prepareValuesToInsert(array_merge($category->getData(), $attributesData[$categoryId], array('store_id' => $store->getId()))); } } foreach ($data as $row) { $updateFields = array(); foreach (array_keys($row) as $key) { $updateFields[$key] = $key; } $this->getWriteAdapter()->insertOnDuplicate($tableName, $row, $updateFields); } } $this->deleteNonStoreCategories($store, $useTempTable); } return $this; }
/** * Return parent categories of category * * @param \Magento\Catalog\Model\Category $category * @param bool $isActive * @return \Magento\Catalog\Model\Category[] */ public function getParentCategories($category, $isActive = true) { $categories = []; $read = $this->_getReadAdapter(); $select = $read->select()->from(['main_table' => $this->getMainStoreTable($category->getStoreId())], ['main_table.entity_id', 'main_table.name'])->joinLeft(['url_rewrite' => $this->getTable('url_rewrite')], 'url_rewrite.entity_id = main_table.entity_id AND url_rewrite.is_autogenerated = 1' . $read->quoteInto(' AND url_rewrite.store_id = ?', $category->getStoreId()) . $read->quoteInto(' AND url_rewrite.entity_type = ?', CategoryUrlRewriteGenerator::ENTITY_TYPE), ['request_path' => 'url_rewrite.request_path'])->where('main_table.entity_id IN (?)', array_reverse(explode(',', $category->getPathInStore()))); if ($isActive) { $select->where('main_table.is_active = ?', '1'); } $select->order('main_table.path ASC'); $result = $this->_getReadAdapter()->fetchAll($select); foreach ($result as $row) { $row['id'] = $row['entity_id']; $categories[$row['entity_id']] = $this->_categoryFactory->create()->setData($row); } return $categories; }
/** * Change current category object * * @param mixed $category * @return \Magento\Catalog\Model\Layer * @throws \Magento\Framework\Model\Exception */ public function setCurrentCategory($category) { if (is_numeric($category)) { $category = $this->_categoryFactory->create()->load($category); } if (!$category instanceof \Magento\Catalog\Model\Category) { throw new \Magento\Framework\Model\Exception(__('The category must be an instance of \\Magento\\Catalog\\Model\\Category.')); } if (!$category->getId()) { throw new \Magento\Framework\Model\Exception(__('Please correct the category.')); } if ($category->getId() != $this->getCurrentCategory()->getId()) { $this->setData('current_category', $category); } return $this; }
/** * {@inheritdoc} */ public function get($categoryId, $storeId = null) { if (!isset($this->instances[$categoryId])) { /** @var Category $category */ $category = $this->categoryFactory->create(); if (null !== $storeId) { $category->setStoreId($storeId); } $category->load($categoryId); if (!$category->getId()) { throw NoSuchEntityException::singleField('id', $categoryId); } $this->instances[$categoryId] = $category; } return $this->instances[$categoryId]; }
/** * Get selected category object * * @return CategoryModel */ public function getCategory() { if ($this->category === null) { /** @var CategoryModel|null $category */ $category = null; if ($this->categoryId !== null) { $category = $this->categoryFactory->create()->setStoreId($this->getLayer()->getCurrentStore()->getId())->load($this->categoryId); } if ($category === null || !$category->getId()) { $category = $this->getLayer()->getCurrentCategory(); } $this->coreRegistry->register('current_category_filter', $category, true); $this->category = $category; } return $this->category; }