Question

I'm creating a CRUD module for Magento2 with an EAV entity.
My first step is to install and uninstall the module.
My EAV entity is similar to products, categories and customers.
The install script works as the install from the customer module.
It adds the _int, _decimal, ... tables and some rows in eav_entity_type and eav_attribute tables.

How can I trigger in my uninstall script the delete of these rows without running a raw query like DELETE FROM eav_entity_type WHERE ...?
Actually I need to delete something only from the eav_entity_type because the values from eav_attribute should cascade.

My uninstall script follows standards.
I have the file in Setup/Uninstall.php and it contains the method

public function uninstall(
    \Magento\Framework\Setup\SchemaSetupInterface $setup,
    \Magento\Framework\Setup\ModuleContextInterface $context
) {
   ....
}

The method gets called so this I've done right.

Was it helpful?

Solution

Found it.
I just need to add 2 dependencies to my class.
An instance of \Magento\Eav\Model\ResourceModel\Entity\Type\CollectionFactory and one of \Magento\Eav\Model\ResourceModel\Entity\Type.

Now my class looks like this:

namespace [Namespace]\[Module]\Setup;

class Uninstall implements \Magento\Framework\Setup\UninstallInterface
{
    protected $eavCollectionFactory;
    protected $eavResourceModel;
    public function __construct(
         \Magento\Eav\Model\ResourceModel\Entity\Type\CollectionFactory $eavCollectionFactory,
         \Magento\Eav\Model\ResourceModel\Entity\Type $eavResourceModel
    )
    {
        $this->eavCollectionFactory = $eavCollectionFactory;
        $this->eavResourceModel     = $eavResourceModel;
    }

    public function uninstall(
        \Magento\Framework\Setup\SchemaSetupInterface $setup,
        \Magento\Framework\Setup\ModuleContextInterface $context
    ) {
        $eavTypeCollection = $this->eavCollectionFactory->create();
        $eavTypeCollection->addFieldToFilter('entity_type_code', ['in' => ['entity_code_1', 'entity_code_2']]); //all entity codes here
        foreach ($eavTypeCollection as $eavType) {
            //delete all entity types
            //the delete can be moved to a separate method to trick the code sniffer into thinking it's not a delete in a loop
            $this->eavResourceModel->delete($eavType);
        }
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top