Question

If you want to create url rewrites programmatically what factory should you use?

Tried a few of them but none have the right methods (like setStoreId, save, setTargetPath and setRequestPath):

Magento\UrlRewrite\Model\UrlRewriteFactory or Magento\UrlRewrite\Model\ResourceModel\UrlRewriteFactory or Magento/UrlRewrite/Service/V1/Data/UrlRewriteFactory (missing save method)

Thanks!

Update: If these are the only factories available how does one save a rewrite?

For example if you use Magento\UrlRewrite\Service\V1\Data\UrlRewriteFactory there is no save method:

$urlRewriteModel = $this->urlRewriteFactory->create();
$urlRewriteModel->setStoreId($storeId);
$urlRewriteModel->setTargetPath("yes");
$urlRewriteModel->setRequestPath("yes2");
$urlRewriteModel->save(); //this fails with no save method

Update2:

Thanks for the help, the final solution looks like this: https://github.com/ClaudiuCreanga/magento2-store-locator-stockists-extension/blob/master/src/Model/UrlRewrite.php#L139

Was it helpful?

Solution

If we take a look at:

vendor/magento/module-catalog-url-rewrite/Model/Category/CanonicalUrlRewriteGenerator.php

        /** @var \Magento\UrlRewrite\Service\V1\Data\UrlRewriteFactory */
         protected $urlRewriteFactory;

           $this->urlRewriteFactory->create()->setStoreId($storeId)
                ->setEntityType(CategoryUrlRewriteGenerator::ENTITY_TYPE)
                ->setEntityId($category->getId())
                ->setRequestPath($urlPath)
                ->setTargetPath($this->categoryUrlPathGenerator->getCanonicalUrlPath($category))

These classes are auto-generate factory classes, we can find them under var/generation folder:

Magento\UrlRewrite\Model\UrlRewriteFactory <= Model class
Magento\UrlRewrite\Model\ResourceModel\UrlRewriteFactory <= Resource Model
Magento\UrlRewrite\Service\V1\Data\UrlRewriteFactory <= Data abstract class for url storage

Shortly, these factory classes create the object instance of themselves.

We can read more here and here.

An example - Create the url rewrites programmatically:

We should use \Magento\UrlRewrite\Model\UrlRewriteFactory

 /** @var $rewrite \Magento\UrlRewrite\Model\UrlRewriteFactory */

$rewrite->setStoreId(
    1
)->setIdPath(
    'product/1/4'
)->setRequestPath(
    'category-2/simple-product.html'
)->setTargetPath(
    'catalog/product/view/id/1'
)->setIsSystem(
    1
)->setCategoryId(
    4
)->setProductId(
    1
)->save();
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top