Set product in shared Catalog
Domanda
For product import,
I have checked from admin (admin -> catalog -> shared catalog ) that my id for shared catalog (Default (General)) is 1.
Then I done code as below. but not works. please guide me what I have missed
public function __construct(
\Magento\Store\Model\StoreManagerInterface $storeManager,
\Magento\Catalog\Model\ResourceModel\Category\CollectionFactory $categoryCollection,
\Magento\Catalog\Api\ProductRepositoryInterface $productRepository,
\Magento\Catalog\Model\Product $productModel,
\Magento\Catalog\Model\ProductFactory $productFactory,
\Magento\CatalogInventory\Api\StockStateInterface $stockStateInterface,
\Magento\CatalogInventory\Api\StockRegistryInterface $stockRegistry,
\Magento\Framework\Api\SearchCriteriaBuilder $searchCriteriaBuilder,
\Magento\Eav\Api\AttributeRepositoryInterface $attributeRepository,
\Magento\SharedCatalog\Model\ProductManagement $sharedCatalog
)
{
$this->_storeManager = $storeManager;
$this->_categoryCollection = $categoryCollection;
$this->_productRepository = $productRepository;
$this->_productModel = $productModel;
$this->_productFactory = $productFactory;
$this->_stockStateInterface = $stockStateInterface;
$this->_stockRegistry = $stockRegistry;
$this->_categoryData = $this->getCategories();
$this->attributeRepository = $attributeRepository;
$this->searchCriteriaBuilder = $searchCriteriaBuilder;
$this->_attributeData = $this->getAttributes();
$this->_sharedCatalog = $sharedCatalog;
}
private function saveProduct($productData = array())
{
$sku = $productData['custom_material'];
$productObj = $this->_productFactory->create();
$productObj->setName($productData['custom_material_description']);
other attributes ....
$productObj->save();
$this->_sharedCatalog->assignProducts(1, array($sku) );
}
Soluzione
- Find the ID of the shared catalog you need to assign to the products. If you know the shared catalog name, you can use a custom resource model that extends the
Magento\SharedCatalog\Model\ResourceModel\SharedCatalog
resource model, then add the following method:
public function getSharedCatalogIdBySharedCatalogName(string $catalogName): int
{
$stmt = $this->getConnection()
->select()
->from($this->getMainTable(), 'entity_id')
->where('name = ?', $catalogName);
return $this->getConnection()->fetchOne($stmt);
}
- In your custom code where you created the product(s), use the
vendor/magento/module-shared-catalog/Model/ProductManagement.php
'sassignProducts()
method to assign the product(s) by using as arguments the shared catalog ID retrieved at step 1. + the array of products which you want to assign (see how this is used inside/vendor/magento/module-shared-catalog/Observer/Controller/SaveProduct.php
).
Good Luck!
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a magento.stackexchange