Question

I found some regions in a specific countries are obsolete and new ones are missing.

I know how to add region by installData.php in a custom module but i dont know how to remove the obsolete ones.

What is the best way to do it?

Was it helpful?

Solution

I found this method in Magento\Framework\Setup\ModuleDataSetupInterface

public function deleteTableRow($table, $idField, $rowId, $parentField = null, $parentId = 0);

so i managed with a patch:

<?php
namespace Vendor\RegionFix\Setup\Patch\Data;

use Magento\Directory\Model\RegionFactory;
use Magento\Framework\Setup\Patch\DataPatchInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;

class SudSardegna implements DataPatchInterface
{
    /**
     * @var ModuleDataSetupInterface
     */
    protected $moduleDataSetup;

    /**
     * @var RegionFactory
     */
    protected $_regionFactory;


    public function __construct(
        ModuleDataSetupInterface $moduleDataSetup,
        RegionFactory $regionFactory
    ){
        $this->moduleDataSetup = $moduleDataSetup;
        $this->_regionFactory = $regionFactory;
    }

    /**
     * {@inheritdoc}
     */
    public function apply()
    {
        $obsoleteRegions = [
            'CI' => 'Carbonia-Iglesias',
            'VS' => 'Medio Campidano',
            'OG' => 'Ogliastra'
        ];

        $newRegions = [
            'SU' => 'Sud Sardegna'
        ];

        foreach ($newRegions as $code => $name) {

            $binds = ['country_id'   => 'IT', 'code' => $code, 'default_name' => $name];
            $this->moduleDataSetup->getConnection()->insert($this->moduleDataSetup->getTable('directory_country_region'), $binds);
            $regionId = $this->moduleDataSetup->getConnection()->lastInsertId($this->moduleDataSetup->getTable('directory_country_region'));


            $binds = ['locale'=> 'it_IT', 'region_id' => $regionId, 'name'=> $name];
            $this->moduleDataSetup->getConnection()->insert($this->moduleDataSetup->getTable('directory_country_region_name'), $binds);
        }

        foreach ($obsoleteRegions as $code => $name) {
            $region = $this->_regionFactory->create();
            $regionId = $region->loadByCode($code, 'IT')->getId();
            $this->moduleDataSetup->deleteTableRow($this->moduleDataSetup->getTable('directory_country_region'),'region_id',$regionId);
            $this->moduleDataSetup->deleteTableRow($this->moduleDataSetup->getTable('directory_country_region_name'),'region_id',$regionId);
        }
    }

    /**
     * {@inheritdoc}
     */
    public static function getDependencies()
    {
        return [];
    }

    /**
     * {@inheritdoc}
     */
    public function getAliases()
    {
        return [];
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top