How to delete attribute group by id Magento 2?

You can remove the attribute group by the group id in Magento 2.

You can see a list of attribute groups from the Stores -> Attribute -> Attribute Set -> Click on Any attribute set.

Remove Attribute Group Record by the delete method with group id as an argument in the ProductAttributeGroupRepositoryInterface.

<?php
namespace Jesadiya\RemoveAttributeGroup\Model;

use Exception;
use Magento\Catalog\Api\ProductAttributeGroupRepositoryInterface;

class RemoveAttributeGroup
{
    /**
     * @var ProductAttributeGroupRepositoryInterface
     */
    private $productAttributeGroup;

    public function __construct(
        ProductAttributeGroupRepositoryInterface $productAttributeGroup
    ) {
        $this->productAttributeGroup = $productAttributeGroup;
    }

    /**
     * Delete Product Attribute Group By Id
     *
     * @return bool
     */
    public function removeAttributeGroup()
    {
        $isDeletedProductAttributeGroup = false;
        $groupId = 1;
        try {
          $isDeletedProductAttributeGroup = $this->productAttributeGroup->delete($groupId);
        } catch (Exception $exception) {
          throw new Exception($exception->getMessage());
        }

        return $isDeletedProductAttributeGroup;
    }
}

Now Call the method,
echo $isRemoveAttributeGroupSuccess = $this->removeAttributeGroup();

Output:
Boolean

One Reply to “How to delete attribute group by id Magento 2?”

  1. 1. Argument 1 passed to MagentoCatalogModelProductAttributeGroupRepository::delete() must be an instance of MagentoEavApiDataAttributeGroupInterface, integer given. You should actually use `deleteById`
    2. Your method `JesadiyaRemoveAttributeGroupModelRemoveAttributeGroup::removeAttributeGroup` should be able to get argument `$groupId`
    3. If you want to return boolean value – just catch all exceptions and don’t throw them! It’s debugging hell, but… if that’s your goal, it’s acceptable.

    Method after changes should look like this:

    public function removeAttributeGroup(int $groupId)
    {
    try {
    $isDeletedProductAttributeGroup = $this->productAttributeGroup->deleteById($groupId);
    } catch (Exception $exception) {
    $isDeletedProductAttributeGroup = false;
    }

    return $isDeletedProductAttributeGroup;
    }

    However it’s really nasty to do it this way.

Leave a Reply