I am trying to develop a module to change the SKU for the product if the product SKU contain auto keyword.
I created events.xml file and added
<event name="catalog_product_save_before">
<observer name="add_sku_handles" instance="vendor\modulename\Observer\AddSkuHandles"/>
</event>
my observer will receive the product, and check if the type is configurable and current SKU have auto keyword, it will find the product category and based on it I will generate the new SKU then update the product SKU $product->setSku($newSku);
and if the product is simple then I will get the parent product SKU and append to it option code then update the SKU. suppose I have this product x in category y and have two simple product z and l.
so the code will change x SKU to 0001-001 and z 0001-001-1 based on attribute mapping code in my module and l will be 0001-001-2.
The first issue was that Magento save the child product then the parent product, so my code will generate the SKU wrongly. I changed my code to apply a different logic. It will ignore all simple products and when the product in the observer is parent it will update the SKU and get all children and update their SKU. This method generates correct SKU but it breaks the relation between products. So after updating when I select product attributes or children from parent it will return an empty result.
How can update the SKU without breaking the relationship or is there a better way to achieve my goal.