1

I am updating produts programmatically and it sometimes happens that an attribute for a product is not used anymore. In that case, the attribute value should of course be removed. However, I can not find a way to do that. The update works just fine, but values aren't getting removed from the model.

I have looked around a bit and it seemed that the following would be the solution:

$product->unsetData($attributeCode);

But this does not remove the value. The attribute code is correct and everything else works perfectly fine. I also checked and it does use the right store.

I have gotten suggestions on doing this directly through the database, but I'd rather do it on the model for safety.

2
  • 2
    Try $product->setData($attributeCode, null);
    – Marius
    Commented Aug 29, 2014 at 8:43
  • 1
    $_Product->setAttributeCode(null); you can also use this
    – Keyul Shah
    Commented Aug 29, 2014 at 8:47

2 Answers 2

4

I suggest making the attribute's value empty:

$product->setData($attributeCode, '');

or:

$product->setAttributeCode('');

or, as you have saved the product you need to save the product object:

$product->unsetData($attributeCode);
$product->save();

This will take effect after the object is saved.

2
  • That makes so much sense, setting the value to nothing. I feel stupid now.. Thanks! Commented Aug 29, 2014 at 9:15
  • This works fine, I have added the full code in my answer. Commented Jan 23, 2020 at 11:01
-1

Here is the full code. This works fine for removing/empty attribute value.

foreach ($collection as $item) { $mypro = "PRODUCT ENTITY ID"; $productRepository=$objectManager>get('\Magento\Catalog\Api\ProductRepositoryInterface'); $product = $productRepository->getById($mypro); $product->setData("PRODUCT_ATTRIBUTE_CODE_GOES_HERE", ''); $product->save(); }

1
  • 1
    Question is about magento 1.X.Not Magento 2.X
    – Amit Bera
    Commented Jan 23, 2020 at 11:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.