How to find if target path in custom url rewrite exists in magento 2
-
15-04-2021 - |
質問
how to check if the target path for custom url is present in the url rewrite table in magento 2.
I had created custom url rewrite using following code.
$urlRewriteModel = $this->_urlRewriteFactory->create();
$urlRewriteModel->addData(
[
'entity_type' => \Magento\UrlRewrite\Controller\Adminhtml\Url\Rewrite::ENTITY_TYPE_CUSTOM,
'entity_id' => 0,
'request_path' => "abc",
'target_path' => "xyz/index/view/id/".$displayText['videoData']['id'],
'redirect_type' => \Magento\UrlRewrite\Model\OptionProvider::PERMANENT,
'store_id' => 1,
'description' => null,
'is_autogenerated' => 0,
'metadata' => null
]
);
$urlRewriteModel->getResource()->save($urlRewriteModel);
This data add when i save any new record in from admin. if i edit same record then also it will call. so i want to know if that target record is already ther in magento 2. if yes delete and add again using above code.
解決
protected $_urlRewrite;
public function __construct(
\Magento\UrlRewrite\Model\UrlRewrite $urlRewrite
) {
$this->_urlRewrite = $urlRewrite;
}
$UrlRewriteCollection=$this->_urlRewrite->getCollection()->addFieldToFilter('target_path', 'path_to_check')
$deleteItem = $UrlRewriteCollection->getFirstItem();
if ($UrlRewriteCollection->getFirstItem()->getId()) {
// target path does exist
$deleteItem->delete();
}
他のヒント
The current answer is great, but using interfaces is always the best
Try using the following code:
public function __construct(
\Magento\UrlRewrite\Model\UrlFinderInterface $urlFinder
) {
$this->urlFinder = $urlRewrite;
}
...
$data = [
\Magento\UrlRewrite\Service\V1\Data\UrlRewrite::REQUEST_PATH => 'requst_path',
\Magento\UrlRewrite\Service\V1\Data\UrlRewrite::TARGET_PATH => 'target_path',
\Magento\UrlRewrite\Service\V1\Data\UrlRewrite::STORE_ID => 'storeId',
];
$url = $this->urlFinder->findOneByData($data); // returns null if not found
I hope this answer will help someone in the future.
所属していません magento.stackexchange