Assign products to category programatically in magento2 Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern) Announcing the arrival of Valued Associate #679: Cesar Manara Unicorn Meta Zoo #1: Why another podcast?Adding Product to Category on selecting yes/no attribute in Magento 2Assign product to category programmatically Magento2 receive an errorHow to assign category on multiple products?Assign products to a category that are not assigned to any categoryProgrammatically assign a product's categories _AND_ sort order/positionFind all Simple Products without category. Assign Cat to simple Product who is child of configurableHow to assign category to all subcategory products?How to assign categories to a new product automatically?Add collection of products to a categoryProducts not getting displayed on category page in magento 2Assign Products created in last 45 days to specific categoryMagento2: Assign products to category programatically
What is the role of the transistor and diode in a soft start circuit?
What to do with chalk when deepwater soloing?
Dating a Former Employee
Fundamental Solution of the Pell Equation
What LEGO pieces have "real-world" functionality?
Can a non-EU citizen traveling with me come with me through the EU passport line?
3 doors, three guards, one stone
Why am I getting the error "non-boolean type specified in a context where a condition is expected" for this request?
How to tell that you are a giant?
Check which numbers satisfy the condition [A*B*C = A! + B! + C!]
How do I keep my slimes from escaping their pens?
Withdrew £2800, but only £2000 shows as withdrawn on online banking; what are my obligations?
51k Euros annually for a family of 4 in Berlin: Is it enough?
Identifying polygons that intersect with another layer using QGIS?
Echoing a tail command produces unexpected output?
Why did the IBM 650 use bi-quinary?
What does the "x" in "x86" represent?
Why did the Falcon Heavy center core fall off the ASDS OCISLY barge?
Apollo command module space walk?
Why aren't air breathing engines used as small first stages
Error "illegal generic type for instanceof" when using local classes
Denied boarding although I have proper visa and documentation. To whom should I make a complaint?
What does "fit" mean in this sentence?
If a contract sometimes uses the wrong name, is it still valid?
Assign products to category programatically in magento2
Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern)
Announcing the arrival of Valued Associate #679: Cesar Manara
Unicorn Meta Zoo #1: Why another podcast?Adding Product to Category on selecting yes/no attribute in Magento 2Assign product to category programmatically Magento2 receive an errorHow to assign category on multiple products?Assign products to a category that are not assigned to any categoryProgrammatically assign a product's categories _AND_ sort order/positionFind all Simple Products without category. Assign Cat to simple Product who is child of configurableHow to assign category to all subcategory products?How to assign categories to a new product automatically?Add collection of products to a categoryProducts not getting displayed on category page in magento 2Assign Products created in last 45 days to specific categoryMagento2: Assign products to category programatically
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;
How can I assign 'New products' to 'NEW PRODUCTS category' programatically in magento 2.
magento2 product category
add a comment |
How can I assign 'New products' to 'NEW PRODUCTS category' programatically in magento 2.
magento2 product category
add a comment |
How can I assign 'New products' to 'NEW PRODUCTS category' programatically in magento 2.
magento2 product category
How can I assign 'New products' to 'NEW PRODUCTS category' programatically in magento 2.
magento2 product category
magento2 product category
edited Jul 2 '18 at 10:32
Teja Bhagavan Kollepara
2,99341949
2,99341949
asked Oct 14 '16 at 10:03
chinchuchinchu
6527
6527
add a comment |
add a comment |
4 Answers
4
active
oldest
votes
You need to get category Ids and product Id to set data:
impliment this :
$this->getCategoryLinkManagement()->assignProductToCategories(
$product->getSku(),
$product->getCategoryIds()
);
also impliment this function :
private function getCategoryLinkManagement()
if (null === $this->categoryLinkManagement)
$this->categoryLinkManagement = MagentoFrameworkAppObjectManager::getInstance()
->get('MagentoCatalogApiCategoryLinkManagementInterface');
return $this->categoryLinkManagement;
rest dependency you should manage for : MagentoCatalogApiCategoryLinkManagementInterface
intialize :
protected $categoryLinkManagement;
Direct use of MagentoFrameworkAppObjectManager::getInstance() is not valid as per magento so you can inject it in Constructor
I used this code in a block and tried to render that block in template file. When I tried this method I got "Uncaught Error: Call to a member function assignProductToCategories()" in the template file. Could you please help me to sort out this?
– chinchu
Oct 17 '16 at 9:58
Have you give dependency for "MagentoCatalogApiCategoryLinkManagementInterface" ?
– Ronak Chauhan
Oct 17 '16 at 12:40
Yes, I have added. I worked fine.
– chinchu
Oct 18 '16 at 8:48
Hi @RonakChauhan I tried your code but it doesnt seem like working . My products are not getting assigned to category..
– Daniel_12
Oct 30 '18 at 15:18
@Daniel_12 are you getting any error?
– Ronak Chauhan
Oct 30 '18 at 17:24
|
show 1 more comment
I think, this needs an updated answer which does not make use of the object manager. Also, there are some kinks involved which are not mentioned anywhere.
In your constructor, inject the CategoryLinkManagementInterface:
protected $categoryLinkManagement;
public function __construct(
...
MagentoCatalogApiCategoryLinkManagementInterface $categoryLinkManagementInterface,
...
)
$this->categoryLinkManagement = $categoryLinkManagementInterface;
...
Later in your code, assign categories the following way:
$product = $this->productRepository->getById(1337); // or any other way to get a product model/interface
$categoryIds = [
42,
606
];
$this->categoryLinkManagement->assignProductToCategories(
$product->getSku(),
$categoryIds
);
This will replace all previous category assignments. If you want to keep the existing category assignments, use something like this:
$categoryIds = array_unique(
array_merge(
$product->getCategoryIds(),
$categoryIds
)
);
Be aware: The link management defers the category assignment (for the product attribute) to the scheduled indexer. This means that if you make other changes to the product and save it after assignProductToCategories()
$product = $this->productRepository->save($product);
the category assignments will be gone as $product contains either null (if it was a newly created product) or only the previously assigned categories for its attribute. Also,
$product = $this->productRepository->getById($product->getId());
right after assignProductToCategories() will not help for the same reason mentioned above. Either assign categories at the latest possible point in time (when you do not save the product afterwards) or assign the attribute manually before saving again
$product->setCategoryIds($categoryIds);
If you opt to use the latter, you could probably fall back to only using setCategoryIds(). I have not tested either case (assignProductToCategories + setCategoryIds + save or setCategoryIds only + save) for performance impact, so I can not comment on that, but I think the whole circumstance was important to mention.
hi, @Drelling, Could not save product "41859" with position 0 to category 8 getting above error,
– jafar pinjar
Nov 26 '18 at 11:59
Hi @jafarpinjar, is that all you got in terms of error messages? I could think of a few reasons, why this occured: 1. You accidentally used $product->getId() instead of $product->getSku() 2. The product's URL key is not unique (although I think that the error message would be specific) 3. The product is already assigned to category with id 8
– T. Dreiling
Nov 27 '18 at 12:07
1. can we not use $product->getId()? 3. The product is already assigned to category with id 8 – T. if assigned can we not remove it?
– jafar pinjar
Nov 27 '18 at 12:18
1. No, assignProductToCategories() explicitly needs the SKU, not the ID! If that was your error, try again with SKU instead. 3. Ah, I was somewhat wrong here. The error I was thinking of occurs when $categoryIds would contain the same category more than once. You actually need to include category id 8 to keep it in that category. If you don't, it will be removed. So that's how you can remove a product from a category.
– T. Dreiling
Nov 27 '18 at 12:53
The error I was thinking of occurs when $categoryIds would contain the same category more than once. Its not possible is it? because category id is unique, I am passing sku only to this method assignProductToCategories not the id
– jafar pinjar
Nov 27 '18 at 13:22
|
show 1 more comment
Assign Products To Category
<?php
$new_category_id = array('100','101');
$sku = 'sku of product';
$objectManager = MagentoFrameworkAppObjectManager::getInstance();
$CategoryLinkRepository = $objectManager->get('MagentoCatalogApiCategoryLinkManagementInterface');
$CategoryLinkRepository->assignProductToCategories($sku, $new_category_id);
Remove Products From Category
<?php
$category_id = 101;
$sku = 'sku of product';
$objectManager = MagentoFrameworkAppObjectManager::getInstance();
$CategoryLinkRepository = $objectManager->get('MagentoCatalogModelCategoryLinkRepository');
$CategoryLinkRepository->deleteByIds($category_id ,$sku);
getting this error, Could not save product with position 0 to category 8
– jafar pinjar
Nov 24 '18 at 10:49
@jafarpinjar this error is related to other customization. If you check this code snippet with fresh Magento install, it will work well. Please check if any third party customization preventing this code from execution
– chirag dodia
Nov 26 '18 at 3:57
hi @chirag dodia, no, I have used this code in custom file and running it by moving to root folder, no customization is used
– jafar pinjar
Nov 26 '18 at 6:00
@jafarpinjar try with fresh product and check is this something related to a particular product?
– chirag dodia
Nov 26 '18 at 11:52
hi @chirag, i got this error, Could not save product "41859" with position 0 to category 8
– jafar pinjar
Nov 26 '18 at 11:55
add a comment |
$objectManager = ObjectManager::getInstance();
$catalogProduct = $objectManager->create('MagentoCatalogModelProduct');
$catalogProduct->setSku('sku-1');
$catalogProduct->setName('name');
$catalogProduct->setAttributeSetId(4);
$catalogProduct->setStatus(1); // Status on product enabled/ disabled 1/0
$catalogProduct->setVisibility(4);
$catalogProduct->setTypeId('simple'); // type of product (simple/virtual/downloadable/configurable)
$catalogProduct->setPrice(100);
$catalogProduct->setCategoryIds(['id']); // here you are
$catalogProduct->setStockData([
'is_in_stock' => true,
'qty' => 10
]);
$catalogProduct->setStoreId(1); // $this->storeManagerInterface->getStore()->getId()
$catalogProduct->setWebsiteIds([1]); // $this->storeManagerInterface->getStore()->getWebsiteId()
$catalogProduct->save();
This is a very heavy request and executes very slowly as oppose to Link Manager
– Timik
Aug 16 '18 at 18:53
add a comment |
Your Answer
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "479"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f140875%2fassign-products-to-category-programatically-in-magento2%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
4 Answers
4
active
oldest
votes
4 Answers
4
active
oldest
votes
active
oldest
votes
active
oldest
votes
You need to get category Ids and product Id to set data:
impliment this :
$this->getCategoryLinkManagement()->assignProductToCategories(
$product->getSku(),
$product->getCategoryIds()
);
also impliment this function :
private function getCategoryLinkManagement()
if (null === $this->categoryLinkManagement)
$this->categoryLinkManagement = MagentoFrameworkAppObjectManager::getInstance()
->get('MagentoCatalogApiCategoryLinkManagementInterface');
return $this->categoryLinkManagement;
rest dependency you should manage for : MagentoCatalogApiCategoryLinkManagementInterface
intialize :
protected $categoryLinkManagement;
Direct use of MagentoFrameworkAppObjectManager::getInstance() is not valid as per magento so you can inject it in Constructor
I used this code in a block and tried to render that block in template file. When I tried this method I got "Uncaught Error: Call to a member function assignProductToCategories()" in the template file. Could you please help me to sort out this?
– chinchu
Oct 17 '16 at 9:58
Have you give dependency for "MagentoCatalogApiCategoryLinkManagementInterface" ?
– Ronak Chauhan
Oct 17 '16 at 12:40
Yes, I have added. I worked fine.
– chinchu
Oct 18 '16 at 8:48
Hi @RonakChauhan I tried your code but it doesnt seem like working . My products are not getting assigned to category..
– Daniel_12
Oct 30 '18 at 15:18
@Daniel_12 are you getting any error?
– Ronak Chauhan
Oct 30 '18 at 17:24
|
show 1 more comment
You need to get category Ids and product Id to set data:
impliment this :
$this->getCategoryLinkManagement()->assignProductToCategories(
$product->getSku(),
$product->getCategoryIds()
);
also impliment this function :
private function getCategoryLinkManagement()
if (null === $this->categoryLinkManagement)
$this->categoryLinkManagement = MagentoFrameworkAppObjectManager::getInstance()
->get('MagentoCatalogApiCategoryLinkManagementInterface');
return $this->categoryLinkManagement;
rest dependency you should manage for : MagentoCatalogApiCategoryLinkManagementInterface
intialize :
protected $categoryLinkManagement;
Direct use of MagentoFrameworkAppObjectManager::getInstance() is not valid as per magento so you can inject it in Constructor
I used this code in a block and tried to render that block in template file. When I tried this method I got "Uncaught Error: Call to a member function assignProductToCategories()" in the template file. Could you please help me to sort out this?
– chinchu
Oct 17 '16 at 9:58
Have you give dependency for "MagentoCatalogApiCategoryLinkManagementInterface" ?
– Ronak Chauhan
Oct 17 '16 at 12:40
Yes, I have added. I worked fine.
– chinchu
Oct 18 '16 at 8:48
Hi @RonakChauhan I tried your code but it doesnt seem like working . My products are not getting assigned to category..
– Daniel_12
Oct 30 '18 at 15:18
@Daniel_12 are you getting any error?
– Ronak Chauhan
Oct 30 '18 at 17:24
|
show 1 more comment
You need to get category Ids and product Id to set data:
impliment this :
$this->getCategoryLinkManagement()->assignProductToCategories(
$product->getSku(),
$product->getCategoryIds()
);
also impliment this function :
private function getCategoryLinkManagement()
if (null === $this->categoryLinkManagement)
$this->categoryLinkManagement = MagentoFrameworkAppObjectManager::getInstance()
->get('MagentoCatalogApiCategoryLinkManagementInterface');
return $this->categoryLinkManagement;
rest dependency you should manage for : MagentoCatalogApiCategoryLinkManagementInterface
intialize :
protected $categoryLinkManagement;
Direct use of MagentoFrameworkAppObjectManager::getInstance() is not valid as per magento so you can inject it in Constructor
You need to get category Ids and product Id to set data:
impliment this :
$this->getCategoryLinkManagement()->assignProductToCategories(
$product->getSku(),
$product->getCategoryIds()
);
also impliment this function :
private function getCategoryLinkManagement()
if (null === $this->categoryLinkManagement)
$this->categoryLinkManagement = MagentoFrameworkAppObjectManager::getInstance()
->get('MagentoCatalogApiCategoryLinkManagementInterface');
return $this->categoryLinkManagement;
rest dependency you should manage for : MagentoCatalogApiCategoryLinkManagementInterface
intialize :
protected $categoryLinkManagement;
Direct use of MagentoFrameworkAppObjectManager::getInstance() is not valid as per magento so you can inject it in Constructor
edited May 26 '17 at 6:18
answered Oct 14 '16 at 10:21
Ronak ChauhanRonak Chauhan
4,27411550
4,27411550
I used this code in a block and tried to render that block in template file. When I tried this method I got "Uncaught Error: Call to a member function assignProductToCategories()" in the template file. Could you please help me to sort out this?
– chinchu
Oct 17 '16 at 9:58
Have you give dependency for "MagentoCatalogApiCategoryLinkManagementInterface" ?
– Ronak Chauhan
Oct 17 '16 at 12:40
Yes, I have added. I worked fine.
– chinchu
Oct 18 '16 at 8:48
Hi @RonakChauhan I tried your code but it doesnt seem like working . My products are not getting assigned to category..
– Daniel_12
Oct 30 '18 at 15:18
@Daniel_12 are you getting any error?
– Ronak Chauhan
Oct 30 '18 at 17:24
|
show 1 more comment
I used this code in a block and tried to render that block in template file. When I tried this method I got "Uncaught Error: Call to a member function assignProductToCategories()" in the template file. Could you please help me to sort out this?
– chinchu
Oct 17 '16 at 9:58
Have you give dependency for "MagentoCatalogApiCategoryLinkManagementInterface" ?
– Ronak Chauhan
Oct 17 '16 at 12:40
Yes, I have added. I worked fine.
– chinchu
Oct 18 '16 at 8:48
Hi @RonakChauhan I tried your code but it doesnt seem like working . My products are not getting assigned to category..
– Daniel_12
Oct 30 '18 at 15:18
@Daniel_12 are you getting any error?
– Ronak Chauhan
Oct 30 '18 at 17:24
I used this code in a block and tried to render that block in template file. When I tried this method I got "Uncaught Error: Call to a member function assignProductToCategories()" in the template file. Could you please help me to sort out this?
– chinchu
Oct 17 '16 at 9:58
I used this code in a block and tried to render that block in template file. When I tried this method I got "Uncaught Error: Call to a member function assignProductToCategories()" in the template file. Could you please help me to sort out this?
– chinchu
Oct 17 '16 at 9:58
Have you give dependency for "MagentoCatalogApiCategoryLinkManagementInterface" ?
– Ronak Chauhan
Oct 17 '16 at 12:40
Have you give dependency for "MagentoCatalogApiCategoryLinkManagementInterface" ?
– Ronak Chauhan
Oct 17 '16 at 12:40
Yes, I have added. I worked fine.
– chinchu
Oct 18 '16 at 8:48
Yes, I have added. I worked fine.
– chinchu
Oct 18 '16 at 8:48
Hi @RonakChauhan I tried your code but it doesnt seem like working . My products are not getting assigned to category..
– Daniel_12
Oct 30 '18 at 15:18
Hi @RonakChauhan I tried your code but it doesnt seem like working . My products are not getting assigned to category..
– Daniel_12
Oct 30 '18 at 15:18
@Daniel_12 are you getting any error?
– Ronak Chauhan
Oct 30 '18 at 17:24
@Daniel_12 are you getting any error?
– Ronak Chauhan
Oct 30 '18 at 17:24
|
show 1 more comment
I think, this needs an updated answer which does not make use of the object manager. Also, there are some kinks involved which are not mentioned anywhere.
In your constructor, inject the CategoryLinkManagementInterface:
protected $categoryLinkManagement;
public function __construct(
...
MagentoCatalogApiCategoryLinkManagementInterface $categoryLinkManagementInterface,
...
)
$this->categoryLinkManagement = $categoryLinkManagementInterface;
...
Later in your code, assign categories the following way:
$product = $this->productRepository->getById(1337); // or any other way to get a product model/interface
$categoryIds = [
42,
606
];
$this->categoryLinkManagement->assignProductToCategories(
$product->getSku(),
$categoryIds
);
This will replace all previous category assignments. If you want to keep the existing category assignments, use something like this:
$categoryIds = array_unique(
array_merge(
$product->getCategoryIds(),
$categoryIds
)
);
Be aware: The link management defers the category assignment (for the product attribute) to the scheduled indexer. This means that if you make other changes to the product and save it after assignProductToCategories()
$product = $this->productRepository->save($product);
the category assignments will be gone as $product contains either null (if it was a newly created product) or only the previously assigned categories for its attribute. Also,
$product = $this->productRepository->getById($product->getId());
right after assignProductToCategories() will not help for the same reason mentioned above. Either assign categories at the latest possible point in time (when you do not save the product afterwards) or assign the attribute manually before saving again
$product->setCategoryIds($categoryIds);
If you opt to use the latter, you could probably fall back to only using setCategoryIds(). I have not tested either case (assignProductToCategories + setCategoryIds + save or setCategoryIds only + save) for performance impact, so I can not comment on that, but I think the whole circumstance was important to mention.
hi, @Drelling, Could not save product "41859" with position 0 to category 8 getting above error,
– jafar pinjar
Nov 26 '18 at 11:59
Hi @jafarpinjar, is that all you got in terms of error messages? I could think of a few reasons, why this occured: 1. You accidentally used $product->getId() instead of $product->getSku() 2. The product's URL key is not unique (although I think that the error message would be specific) 3. The product is already assigned to category with id 8
– T. Dreiling
Nov 27 '18 at 12:07
1. can we not use $product->getId()? 3. The product is already assigned to category with id 8 – T. if assigned can we not remove it?
– jafar pinjar
Nov 27 '18 at 12:18
1. No, assignProductToCategories() explicitly needs the SKU, not the ID! If that was your error, try again with SKU instead. 3. Ah, I was somewhat wrong here. The error I was thinking of occurs when $categoryIds would contain the same category more than once. You actually need to include category id 8 to keep it in that category. If you don't, it will be removed. So that's how you can remove a product from a category.
– T. Dreiling
Nov 27 '18 at 12:53
The error I was thinking of occurs when $categoryIds would contain the same category more than once. Its not possible is it? because category id is unique, I am passing sku only to this method assignProductToCategories not the id
– jafar pinjar
Nov 27 '18 at 13:22
|
show 1 more comment
I think, this needs an updated answer which does not make use of the object manager. Also, there are some kinks involved which are not mentioned anywhere.
In your constructor, inject the CategoryLinkManagementInterface:
protected $categoryLinkManagement;
public function __construct(
...
MagentoCatalogApiCategoryLinkManagementInterface $categoryLinkManagementInterface,
...
)
$this->categoryLinkManagement = $categoryLinkManagementInterface;
...
Later in your code, assign categories the following way:
$product = $this->productRepository->getById(1337); // or any other way to get a product model/interface
$categoryIds = [
42,
606
];
$this->categoryLinkManagement->assignProductToCategories(
$product->getSku(),
$categoryIds
);
This will replace all previous category assignments. If you want to keep the existing category assignments, use something like this:
$categoryIds = array_unique(
array_merge(
$product->getCategoryIds(),
$categoryIds
)
);
Be aware: The link management defers the category assignment (for the product attribute) to the scheduled indexer. This means that if you make other changes to the product and save it after assignProductToCategories()
$product = $this->productRepository->save($product);
the category assignments will be gone as $product contains either null (if it was a newly created product) or only the previously assigned categories for its attribute. Also,
$product = $this->productRepository->getById($product->getId());
right after assignProductToCategories() will not help for the same reason mentioned above. Either assign categories at the latest possible point in time (when you do not save the product afterwards) or assign the attribute manually before saving again
$product->setCategoryIds($categoryIds);
If you opt to use the latter, you could probably fall back to only using setCategoryIds(). I have not tested either case (assignProductToCategories + setCategoryIds + save or setCategoryIds only + save) for performance impact, so I can not comment on that, but I think the whole circumstance was important to mention.
hi, @Drelling, Could not save product "41859" with position 0 to category 8 getting above error,
– jafar pinjar
Nov 26 '18 at 11:59
Hi @jafarpinjar, is that all you got in terms of error messages? I could think of a few reasons, why this occured: 1. You accidentally used $product->getId() instead of $product->getSku() 2. The product's URL key is not unique (although I think that the error message would be specific) 3. The product is already assigned to category with id 8
– T. Dreiling
Nov 27 '18 at 12:07
1. can we not use $product->getId()? 3. The product is already assigned to category with id 8 – T. if assigned can we not remove it?
– jafar pinjar
Nov 27 '18 at 12:18
1. No, assignProductToCategories() explicitly needs the SKU, not the ID! If that was your error, try again with SKU instead. 3. Ah, I was somewhat wrong here. The error I was thinking of occurs when $categoryIds would contain the same category more than once. You actually need to include category id 8 to keep it in that category. If you don't, it will be removed. So that's how you can remove a product from a category.
– T. Dreiling
Nov 27 '18 at 12:53
The error I was thinking of occurs when $categoryIds would contain the same category more than once. Its not possible is it? because category id is unique, I am passing sku only to this method assignProductToCategories not the id
– jafar pinjar
Nov 27 '18 at 13:22
|
show 1 more comment
I think, this needs an updated answer which does not make use of the object manager. Also, there are some kinks involved which are not mentioned anywhere.
In your constructor, inject the CategoryLinkManagementInterface:
protected $categoryLinkManagement;
public function __construct(
...
MagentoCatalogApiCategoryLinkManagementInterface $categoryLinkManagementInterface,
...
)
$this->categoryLinkManagement = $categoryLinkManagementInterface;
...
Later in your code, assign categories the following way:
$product = $this->productRepository->getById(1337); // or any other way to get a product model/interface
$categoryIds = [
42,
606
];
$this->categoryLinkManagement->assignProductToCategories(
$product->getSku(),
$categoryIds
);
This will replace all previous category assignments. If you want to keep the existing category assignments, use something like this:
$categoryIds = array_unique(
array_merge(
$product->getCategoryIds(),
$categoryIds
)
);
Be aware: The link management defers the category assignment (for the product attribute) to the scheduled indexer. This means that if you make other changes to the product and save it after assignProductToCategories()
$product = $this->productRepository->save($product);
the category assignments will be gone as $product contains either null (if it was a newly created product) or only the previously assigned categories for its attribute. Also,
$product = $this->productRepository->getById($product->getId());
right after assignProductToCategories() will not help for the same reason mentioned above. Either assign categories at the latest possible point in time (when you do not save the product afterwards) or assign the attribute manually before saving again
$product->setCategoryIds($categoryIds);
If you opt to use the latter, you could probably fall back to only using setCategoryIds(). I have not tested either case (assignProductToCategories + setCategoryIds + save or setCategoryIds only + save) for performance impact, so I can not comment on that, but I think the whole circumstance was important to mention.
I think, this needs an updated answer which does not make use of the object manager. Also, there are some kinks involved which are not mentioned anywhere.
In your constructor, inject the CategoryLinkManagementInterface:
protected $categoryLinkManagement;
public function __construct(
...
MagentoCatalogApiCategoryLinkManagementInterface $categoryLinkManagementInterface,
...
)
$this->categoryLinkManagement = $categoryLinkManagementInterface;
...
Later in your code, assign categories the following way:
$product = $this->productRepository->getById(1337); // or any other way to get a product model/interface
$categoryIds = [
42,
606
];
$this->categoryLinkManagement->assignProductToCategories(
$product->getSku(),
$categoryIds
);
This will replace all previous category assignments. If you want to keep the existing category assignments, use something like this:
$categoryIds = array_unique(
array_merge(
$product->getCategoryIds(),
$categoryIds
)
);
Be aware: The link management defers the category assignment (for the product attribute) to the scheduled indexer. This means that if you make other changes to the product and save it after assignProductToCategories()
$product = $this->productRepository->save($product);
the category assignments will be gone as $product contains either null (if it was a newly created product) or only the previously assigned categories for its attribute. Also,
$product = $this->productRepository->getById($product->getId());
right after assignProductToCategories() will not help for the same reason mentioned above. Either assign categories at the latest possible point in time (when you do not save the product afterwards) or assign the attribute manually before saving again
$product->setCategoryIds($categoryIds);
If you opt to use the latter, you could probably fall back to only using setCategoryIds(). I have not tested either case (assignProductToCategories + setCategoryIds + save or setCategoryIds only + save) for performance impact, so I can not comment on that, but I think the whole circumstance was important to mention.
answered Nov 12 '18 at 18:05
T. DreilingT. Dreiling
613
613
hi, @Drelling, Could not save product "41859" with position 0 to category 8 getting above error,
– jafar pinjar
Nov 26 '18 at 11:59
Hi @jafarpinjar, is that all you got in terms of error messages? I could think of a few reasons, why this occured: 1. You accidentally used $product->getId() instead of $product->getSku() 2. The product's URL key is not unique (although I think that the error message would be specific) 3. The product is already assigned to category with id 8
– T. Dreiling
Nov 27 '18 at 12:07
1. can we not use $product->getId()? 3. The product is already assigned to category with id 8 – T. if assigned can we not remove it?
– jafar pinjar
Nov 27 '18 at 12:18
1. No, assignProductToCategories() explicitly needs the SKU, not the ID! If that was your error, try again with SKU instead. 3. Ah, I was somewhat wrong here. The error I was thinking of occurs when $categoryIds would contain the same category more than once. You actually need to include category id 8 to keep it in that category. If you don't, it will be removed. So that's how you can remove a product from a category.
– T. Dreiling
Nov 27 '18 at 12:53
The error I was thinking of occurs when $categoryIds would contain the same category more than once. Its not possible is it? because category id is unique, I am passing sku only to this method assignProductToCategories not the id
– jafar pinjar
Nov 27 '18 at 13:22
|
show 1 more comment
hi, @Drelling, Could not save product "41859" with position 0 to category 8 getting above error,
– jafar pinjar
Nov 26 '18 at 11:59
Hi @jafarpinjar, is that all you got in terms of error messages? I could think of a few reasons, why this occured: 1. You accidentally used $product->getId() instead of $product->getSku() 2. The product's URL key is not unique (although I think that the error message would be specific) 3. The product is already assigned to category with id 8
– T. Dreiling
Nov 27 '18 at 12:07
1. can we not use $product->getId()? 3. The product is already assigned to category with id 8 – T. if assigned can we not remove it?
– jafar pinjar
Nov 27 '18 at 12:18
1. No, assignProductToCategories() explicitly needs the SKU, not the ID! If that was your error, try again with SKU instead. 3. Ah, I was somewhat wrong here. The error I was thinking of occurs when $categoryIds would contain the same category more than once. You actually need to include category id 8 to keep it in that category. If you don't, it will be removed. So that's how you can remove a product from a category.
– T. Dreiling
Nov 27 '18 at 12:53
The error I was thinking of occurs when $categoryIds would contain the same category more than once. Its not possible is it? because category id is unique, I am passing sku only to this method assignProductToCategories not the id
– jafar pinjar
Nov 27 '18 at 13:22
hi, @Drelling, Could not save product "41859" with position 0 to category 8 getting above error,
– jafar pinjar
Nov 26 '18 at 11:59
hi, @Drelling, Could not save product "41859" with position 0 to category 8 getting above error,
– jafar pinjar
Nov 26 '18 at 11:59
Hi @jafarpinjar, is that all you got in terms of error messages? I could think of a few reasons, why this occured: 1. You accidentally used $product->getId() instead of $product->getSku() 2. The product's URL key is not unique (although I think that the error message would be specific) 3. The product is already assigned to category with id 8
– T. Dreiling
Nov 27 '18 at 12:07
Hi @jafarpinjar, is that all you got in terms of error messages? I could think of a few reasons, why this occured: 1. You accidentally used $product->getId() instead of $product->getSku() 2. The product's URL key is not unique (although I think that the error message would be specific) 3. The product is already assigned to category with id 8
– T. Dreiling
Nov 27 '18 at 12:07
1. can we not use $product->getId()? 3. The product is already assigned to category with id 8 – T. if assigned can we not remove it?
– jafar pinjar
Nov 27 '18 at 12:18
1. can we not use $product->getId()? 3. The product is already assigned to category with id 8 – T. if assigned can we not remove it?
– jafar pinjar
Nov 27 '18 at 12:18
1. No, assignProductToCategories() explicitly needs the SKU, not the ID! If that was your error, try again with SKU instead. 3. Ah, I was somewhat wrong here. The error I was thinking of occurs when $categoryIds would contain the same category more than once. You actually need to include category id 8 to keep it in that category. If you don't, it will be removed. So that's how you can remove a product from a category.
– T. Dreiling
Nov 27 '18 at 12:53
1. No, assignProductToCategories() explicitly needs the SKU, not the ID! If that was your error, try again with SKU instead. 3. Ah, I was somewhat wrong here. The error I was thinking of occurs when $categoryIds would contain the same category more than once. You actually need to include category id 8 to keep it in that category. If you don't, it will be removed. So that's how you can remove a product from a category.
– T. Dreiling
Nov 27 '18 at 12:53
The error I was thinking of occurs when $categoryIds would contain the same category more than once. Its not possible is it? because category id is unique, I am passing sku only to this method assignProductToCategories not the id
– jafar pinjar
Nov 27 '18 at 13:22
The error I was thinking of occurs when $categoryIds would contain the same category more than once. Its not possible is it? because category id is unique, I am passing sku only to this method assignProductToCategories not the id
– jafar pinjar
Nov 27 '18 at 13:22
|
show 1 more comment
Assign Products To Category
<?php
$new_category_id = array('100','101');
$sku = 'sku of product';
$objectManager = MagentoFrameworkAppObjectManager::getInstance();
$CategoryLinkRepository = $objectManager->get('MagentoCatalogApiCategoryLinkManagementInterface');
$CategoryLinkRepository->assignProductToCategories($sku, $new_category_id);
Remove Products From Category
<?php
$category_id = 101;
$sku = 'sku of product';
$objectManager = MagentoFrameworkAppObjectManager::getInstance();
$CategoryLinkRepository = $objectManager->get('MagentoCatalogModelCategoryLinkRepository');
$CategoryLinkRepository->deleteByIds($category_id ,$sku);
getting this error, Could not save product with position 0 to category 8
– jafar pinjar
Nov 24 '18 at 10:49
@jafarpinjar this error is related to other customization. If you check this code snippet with fresh Magento install, it will work well. Please check if any third party customization preventing this code from execution
– chirag dodia
Nov 26 '18 at 3:57
hi @chirag dodia, no, I have used this code in custom file and running it by moving to root folder, no customization is used
– jafar pinjar
Nov 26 '18 at 6:00
@jafarpinjar try with fresh product and check is this something related to a particular product?
– chirag dodia
Nov 26 '18 at 11:52
hi @chirag, i got this error, Could not save product "41859" with position 0 to category 8
– jafar pinjar
Nov 26 '18 at 11:55
add a comment |
Assign Products To Category
<?php
$new_category_id = array('100','101');
$sku = 'sku of product';
$objectManager = MagentoFrameworkAppObjectManager::getInstance();
$CategoryLinkRepository = $objectManager->get('MagentoCatalogApiCategoryLinkManagementInterface');
$CategoryLinkRepository->assignProductToCategories($sku, $new_category_id);
Remove Products From Category
<?php
$category_id = 101;
$sku = 'sku of product';
$objectManager = MagentoFrameworkAppObjectManager::getInstance();
$CategoryLinkRepository = $objectManager->get('MagentoCatalogModelCategoryLinkRepository');
$CategoryLinkRepository->deleteByIds($category_id ,$sku);
getting this error, Could not save product with position 0 to category 8
– jafar pinjar
Nov 24 '18 at 10:49
@jafarpinjar this error is related to other customization. If you check this code snippet with fresh Magento install, it will work well. Please check if any third party customization preventing this code from execution
– chirag dodia
Nov 26 '18 at 3:57
hi @chirag dodia, no, I have used this code in custom file and running it by moving to root folder, no customization is used
– jafar pinjar
Nov 26 '18 at 6:00
@jafarpinjar try with fresh product and check is this something related to a particular product?
– chirag dodia
Nov 26 '18 at 11:52
hi @chirag, i got this error, Could not save product "41859" with position 0 to category 8
– jafar pinjar
Nov 26 '18 at 11:55
add a comment |
Assign Products To Category
<?php
$new_category_id = array('100','101');
$sku = 'sku of product';
$objectManager = MagentoFrameworkAppObjectManager::getInstance();
$CategoryLinkRepository = $objectManager->get('MagentoCatalogApiCategoryLinkManagementInterface');
$CategoryLinkRepository->assignProductToCategories($sku, $new_category_id);
Remove Products From Category
<?php
$category_id = 101;
$sku = 'sku of product';
$objectManager = MagentoFrameworkAppObjectManager::getInstance();
$CategoryLinkRepository = $objectManager->get('MagentoCatalogModelCategoryLinkRepository');
$CategoryLinkRepository->deleteByIds($category_id ,$sku);
Assign Products To Category
<?php
$new_category_id = array('100','101');
$sku = 'sku of product';
$objectManager = MagentoFrameworkAppObjectManager::getInstance();
$CategoryLinkRepository = $objectManager->get('MagentoCatalogApiCategoryLinkManagementInterface');
$CategoryLinkRepository->assignProductToCategories($sku, $new_category_id);
Remove Products From Category
<?php
$category_id = 101;
$sku = 'sku of product';
$objectManager = MagentoFrameworkAppObjectManager::getInstance();
$CategoryLinkRepository = $objectManager->get('MagentoCatalogModelCategoryLinkRepository');
$CategoryLinkRepository->deleteByIds($category_id ,$sku);
edited yesterday
Marius♦
168k28324692
168k28324692
answered Mar 29 '18 at 7:22
chirag dodiachirag dodia
1
1
getting this error, Could not save product with position 0 to category 8
– jafar pinjar
Nov 24 '18 at 10:49
@jafarpinjar this error is related to other customization. If you check this code snippet with fresh Magento install, it will work well. Please check if any third party customization preventing this code from execution
– chirag dodia
Nov 26 '18 at 3:57
hi @chirag dodia, no, I have used this code in custom file and running it by moving to root folder, no customization is used
– jafar pinjar
Nov 26 '18 at 6:00
@jafarpinjar try with fresh product and check is this something related to a particular product?
– chirag dodia
Nov 26 '18 at 11:52
hi @chirag, i got this error, Could not save product "41859" with position 0 to category 8
– jafar pinjar
Nov 26 '18 at 11:55
add a comment |
getting this error, Could not save product with position 0 to category 8
– jafar pinjar
Nov 24 '18 at 10:49
@jafarpinjar this error is related to other customization. If you check this code snippet with fresh Magento install, it will work well. Please check if any third party customization preventing this code from execution
– chirag dodia
Nov 26 '18 at 3:57
hi @chirag dodia, no, I have used this code in custom file and running it by moving to root folder, no customization is used
– jafar pinjar
Nov 26 '18 at 6:00
@jafarpinjar try with fresh product and check is this something related to a particular product?
– chirag dodia
Nov 26 '18 at 11:52
hi @chirag, i got this error, Could not save product "41859" with position 0 to category 8
– jafar pinjar
Nov 26 '18 at 11:55
getting this error, Could not save product with position 0 to category 8
– jafar pinjar
Nov 24 '18 at 10:49
getting this error, Could not save product with position 0 to category 8
– jafar pinjar
Nov 24 '18 at 10:49
@jafarpinjar this error is related to other customization. If you check this code snippet with fresh Magento install, it will work well. Please check if any third party customization preventing this code from execution
– chirag dodia
Nov 26 '18 at 3:57
@jafarpinjar this error is related to other customization. If you check this code snippet with fresh Magento install, it will work well. Please check if any third party customization preventing this code from execution
– chirag dodia
Nov 26 '18 at 3:57
hi @chirag dodia, no, I have used this code in custom file and running it by moving to root folder, no customization is used
– jafar pinjar
Nov 26 '18 at 6:00
hi @chirag dodia, no, I have used this code in custom file and running it by moving to root folder, no customization is used
– jafar pinjar
Nov 26 '18 at 6:00
@jafarpinjar try with fresh product and check is this something related to a particular product?
– chirag dodia
Nov 26 '18 at 11:52
@jafarpinjar try with fresh product and check is this something related to a particular product?
– chirag dodia
Nov 26 '18 at 11:52
hi @chirag, i got this error, Could not save product "41859" with position 0 to category 8
– jafar pinjar
Nov 26 '18 at 11:55
hi @chirag, i got this error, Could not save product "41859" with position 0 to category 8
– jafar pinjar
Nov 26 '18 at 11:55
add a comment |
$objectManager = ObjectManager::getInstance();
$catalogProduct = $objectManager->create('MagentoCatalogModelProduct');
$catalogProduct->setSku('sku-1');
$catalogProduct->setName('name');
$catalogProduct->setAttributeSetId(4);
$catalogProduct->setStatus(1); // Status on product enabled/ disabled 1/0
$catalogProduct->setVisibility(4);
$catalogProduct->setTypeId('simple'); // type of product (simple/virtual/downloadable/configurable)
$catalogProduct->setPrice(100);
$catalogProduct->setCategoryIds(['id']); // here you are
$catalogProduct->setStockData([
'is_in_stock' => true,
'qty' => 10
]);
$catalogProduct->setStoreId(1); // $this->storeManagerInterface->getStore()->getId()
$catalogProduct->setWebsiteIds([1]); // $this->storeManagerInterface->getStore()->getWebsiteId()
$catalogProduct->save();
This is a very heavy request and executes very slowly as oppose to Link Manager
– Timik
Aug 16 '18 at 18:53
add a comment |
$objectManager = ObjectManager::getInstance();
$catalogProduct = $objectManager->create('MagentoCatalogModelProduct');
$catalogProduct->setSku('sku-1');
$catalogProduct->setName('name');
$catalogProduct->setAttributeSetId(4);
$catalogProduct->setStatus(1); // Status on product enabled/ disabled 1/0
$catalogProduct->setVisibility(4);
$catalogProduct->setTypeId('simple'); // type of product (simple/virtual/downloadable/configurable)
$catalogProduct->setPrice(100);
$catalogProduct->setCategoryIds(['id']); // here you are
$catalogProduct->setStockData([
'is_in_stock' => true,
'qty' => 10
]);
$catalogProduct->setStoreId(1); // $this->storeManagerInterface->getStore()->getId()
$catalogProduct->setWebsiteIds([1]); // $this->storeManagerInterface->getStore()->getWebsiteId()
$catalogProduct->save();
This is a very heavy request and executes very slowly as oppose to Link Manager
– Timik
Aug 16 '18 at 18:53
add a comment |
$objectManager = ObjectManager::getInstance();
$catalogProduct = $objectManager->create('MagentoCatalogModelProduct');
$catalogProduct->setSku('sku-1');
$catalogProduct->setName('name');
$catalogProduct->setAttributeSetId(4);
$catalogProduct->setStatus(1); // Status on product enabled/ disabled 1/0
$catalogProduct->setVisibility(4);
$catalogProduct->setTypeId('simple'); // type of product (simple/virtual/downloadable/configurable)
$catalogProduct->setPrice(100);
$catalogProduct->setCategoryIds(['id']); // here you are
$catalogProduct->setStockData([
'is_in_stock' => true,
'qty' => 10
]);
$catalogProduct->setStoreId(1); // $this->storeManagerInterface->getStore()->getId()
$catalogProduct->setWebsiteIds([1]); // $this->storeManagerInterface->getStore()->getWebsiteId()
$catalogProduct->save();
$objectManager = ObjectManager::getInstance();
$catalogProduct = $objectManager->create('MagentoCatalogModelProduct');
$catalogProduct->setSku('sku-1');
$catalogProduct->setName('name');
$catalogProduct->setAttributeSetId(4);
$catalogProduct->setStatus(1); // Status on product enabled/ disabled 1/0
$catalogProduct->setVisibility(4);
$catalogProduct->setTypeId('simple'); // type of product (simple/virtual/downloadable/configurable)
$catalogProduct->setPrice(100);
$catalogProduct->setCategoryIds(['id']); // here you are
$catalogProduct->setStockData([
'is_in_stock' => true,
'qty' => 10
]);
$catalogProduct->setStoreId(1); // $this->storeManagerInterface->getStore()->getId()
$catalogProduct->setWebsiteIds([1]); // $this->storeManagerInterface->getStore()->getWebsiteId()
$catalogProduct->save();
answered May 3 '18 at 12:15
Yamen AshrafYamen Ashraf
1794
1794
This is a very heavy request and executes very slowly as oppose to Link Manager
– Timik
Aug 16 '18 at 18:53
add a comment |
This is a very heavy request and executes very slowly as oppose to Link Manager
– Timik
Aug 16 '18 at 18:53
This is a very heavy request and executes very slowly as oppose to Link Manager
– Timik
Aug 16 '18 at 18:53
This is a very heavy request and executes very slowly as oppose to Link Manager
– Timik
Aug 16 '18 at 18:53
add a comment |
Thanks for contributing an answer to Magento Stack Exchange!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f140875%2fassign-products-to-category-programatically-in-magento2%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown