1

While programmatically creating category, using the below code, i got a error

Category with the 'categorgyurl' url_key attribute already exists

code:

        $category = new Mage_Catalog_Model_Category();
        $category->setName('categorgyurl');
        $category->setUrlKey('categorgyurl');
        $category->setIsActive(1);
        $category->setDisplayMode('PRODUCTS');
        $category->setIsAnchor(0);


        $parentCategory = Mage::getModel('catalog/category')->load($root_catid);
        $category->setPath($parentCategory->getPath());              

        $category->save();

how to set, if category url already exits then make it change(ie. Rename it automatically/programmatically).

2 Answers 2

2

Try this code.

$category = Mage::getModel('catalog/category');
$category->setName('categorgyurl');
$category->setUrlKey('categorgyurl');
$category->setIsActive(1);
$category->setDisplayMode('PRODUCTS');
$category->setIsAnchor(0);

$parentCategory = Mage::getModel('catalog/category')->load($root_catid);
$category->setPath($parentCategory->getPath()); 

$categoryWasCreated = false;
$currentUrlKey = $category->getUrlKey();
while (!$categoryWasCreated) {
    $categoryId = Mage::getModel('catalog/category')->load($category->getUrlKey(), 'url_key')->getId();
    if ($categoryId) {
        //if category with this url key exist add some unique part to the name
        //I used here time function but you can use something else
        $uniquePart = time();
        $category->setUrlKey($category->getUrlKey() . $uniquePart);
    } else {
        $category->save();
        $categoryWasCreated = true;
    }
}

Hope that is what you need.

1

I think you do not need to generate URL key every time. Magento will automatically generate URL key from name. so you can remove $category->setUrlKey('categorgyurl'); and then check result.

1
  • Sohil, Even automatic creation of url key if add same category name through this code, i got this error again. I need a solution if category urlkey already exits just rename its url key.
    – Helphin
    Commented Feb 13, 2014 at 6:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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