0

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.

3
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();
    }
  • i want to delete if target path exists – Pradeep Sanku Oct 12 '18 at 10:31
  • Please check updated answer. I didn't test. – Dipak Bhambhani Oct 12 '18 at 10:38
  • Upvote the answer so it will be helpful to other also. – Dipak Bhambhani Oct 12 '18 at 11:27

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.