Question

When I try to create a product with an SKU the same as one that already exists Magento allows the creation but changes the SKU to be xxx-1.

Is there a way to stop this?

Was it helpful?

Solution

The most inclusive way is probably to create a plugin for \Magento\Catalog\Model\ResourceModel\Product and do a beforeSave, and then query the database for any product with that sku and if it exists fail with an error message.

In a module's etc/di.xml

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="\Magento\Catalog\Model\ResourceModel\Product">
        <plugin name="BeforeProductSave" type="MyNamespace\MyModule\Plugin\BeforeProductSave" />
    </type>
</config>

Then create the plugin php in app/code/MyNamespace/MyModule/Plugin/BeforeProductSave.php

<?php
namespace MyNamespace\MyModule\Plugin;

class BeforeProductSave {
    public function __construct(
        \Magento\Catalog\Api\ProductRepositoryInterface $product_repo
    ){
        $this->product_repo = $product_repo;
    }

    public function beforeSave($subject,$object){
        $sku = $object->getData('sku');//this might not work but there is a way to get sku somehow
        $product = $this->product_repo->get($sku);
        if($product->getId()){
            return $object;
        }
        else {
            die("Product $sku already exists");//you can add actual magento2 error handling after you have the rest working
        }
    }
}

I didn't test this code it's just templated from work I've done and by memory but it should at least get you started. You'll have to run setup:di:compile after you add this code to get it working and to test you'll have to create a product.

The nuclear option is to create a preference for the entire \Magento\Catalog\Model\ResourceModel\Product class and exend the \Magento\Catalog\Model\ResourceModel\Product in your preference and rewrite the save function.

OTHER TIPS

It seems question is answered and programmatic solution exists but if anyone needs a quick plug and play addon then below Magento 2 extension should help

https://redchamps.com/product-sku-validator-magento-2-extension.html

Disclosure: This extension is developed by us and it is paid.

Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top