0

How do I code a function that force sku input data into url-key input data everytime I update a simple product or groupe product?

This code work only on product creation but I want it to work on product update too. ProductUrlPathGenerator.php

<?php 
namespace Developer\Module\Model;

/**
 * Class AbstractAction
 * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/

class ProductUrlPathGenerator extends \Magento\CatalogUrlRewrite\Model\ProductUrlPathGenerator {

    protected function prepareProductDefaultUrlKey(\Magento\Catalog\Model\Product $product)
    {
        $storedProduct = $this->productRepository->getById($product->getId());
        $storedUrlKey = $storedProduct->getUrlKey();
        return $storedUrlKey ?: $product->formatUrlKey($storedProduct->getSku());
    }



    protected function prepareProductUrlKey(\Magento\Catalog\Model\Product $product)
    {
        $urlKey = $product->getUrlKey();
        return $product->formatUrlKey($urlKey === '' || $urlKey === null ? $product->getSku() : $urlKey);

    }
}

1 Answer 1

0

I found a solution with help from a friend

<?php 
namespace Developer\Module\Model;

/**
 * Class AbstractAction
 * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/

class ProductUrlPathGenerator extends \Magento\CatalogUrlRewrite\Model\ProductUrlPathGenerator {

    protected function prepareProductDefaultUrlKey(\Magento\Catalog\Model\Product $product)
    {
        $storedProduct = $this->productRepository->getById($product->getId());
        $storedUrlKey = $storedProduct->getUrlKey();
        return $storedUrlKey ?: $product->formatUrlKey($storedProduct->getSku());
    }



    protected function prepareProductUrlKey(\Magento\Catalog\Model\Product $product)
    {
        if($product->getSku()!='') {
            return $product->getSku();
        }
        $urlKey = $product->getUrlKey();
        return $product->formatUrlKey($urlKey === '' || $urlKey === null ? $product->getSku() : $urlKey);
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.