CheckUniqueCodeName function for Categories

Novice User asked on October 30, 2017 18:46

I want to add categories with same name under different parents. Kentico gives me Not a unique code name error. I am trying to use CheckUniqueCodeName() function but it is returning false. I cant find any examples/documentation. Can any body explains how this functions works with regards to categories.

   if (myCategory.CheckUniqueCodeName())
                {
                    CategoryInfoProvider.SetCategoryInfo(myCategory);

                }
                else
                {
                    Random random = new Random();
                    int RndNum = random.Next(1000);
                    myCategory.CategoryName = NewCatDisplayName + RndNum   ;
                    CategoryInfoProvider.SetCategoryInfo(myCategory);


                }

Correct Answer

Peter Mogilnitski answered on October 30, 2017 22:05

The category code name MUST be unique, but the category display name can be anything. Category code Name in terms of SQL is CategoryName and it is clustered index. Where in the tree you create a category is not important, but CategoryName must be unique.

Image Text

So CheckUniqueCodeName runs SQL query and returns true or false, if have 2 records in the DB like above I try to create a new category under TEST:

// Gets the parent category
CategoryInfo parentCategory = CategoryInfoProvider.GetCategoryInfo("TEST", SiteContext.CurrentSiteName);
if (parentCategory != null)
{
        // Creates a new category object
        CategoryInfo subcategory = new CategoryInfo();

        // Sets basic properties
        subcategory.CategoryDisplayName = "SOMENEWCATEGORY";
        subcategory.CategoryName = "TEST";
        subcategory.CategorySiteID = SiteContext.CurrentSiteID;
        subcategory.CategoryEnabled = true;

        // Assigns to the parent category
        subcategory.CategoryParentID = parentCategory.CategoryID;
        Response.Write("is Unique: " + subcategory.CheckUniqueCodeName());

        subcategory.CategoryName = "TEST123123";
        Response.Write("is Unique: " + subcategory.CheckUniqueCodeName());

}

I will get

is Unique: False is Unique: True

I think you a have a logical problem here: you probably create categories in a loop or something and you need to move out your Random random = new Random(); out of your loop. I think that your random returns the same value.

0 votesVote for this answer Unmark Correct answer

   Please, sign in to be able to submit a new answer.