Dynamically create Categories

Vote:
 

Hi,

Is there a way to dynamically create categories from my c# code which I can use in the categories field in EPiServer?

I have found a way to do this:

var root = Category.GetRoot();
root.Categories.Add(new Category("name", "description"));

However, this should be done once on EPiServer initialization. Should I create a plugin or use a descriptor for it?

Hope somebody can help!

#87842
Jun 24, 2014 13:16
Vote:
 

Hello Hans

It sounds like you should use an EPiServer Initialisation module for this:

http://world.episerver.com/Documentation/Items/Developers-Guide/EPiServer-Framework/7/Initialization/Creating-an-Initialization-Module/

It might also be worth checking for the existence of the category before inserting it to avoid any issues.

David

#87847
Edited, Jun 24, 2014 14:04
Vote:
 

I'm using following fragment to create new categories from code (keep in mind that code will execute *every* time app pool will start - so you should take care of avoiding multiple creation of the same category):

namespace MyProject.Web.Initialization
{
    [InitializableModule]
    [ModuleDependency(typeof(InitializationModule))]
    public class CategorySetup : IInitializableModule
    {
        public void Initialize(InitializationEngine context)
        {
            CreateIfNotExists("Key", "Display Name", 1);
        }

        public void Uninitialize(InitializationEngine context)
        {
        }

        public void Preload(string[] parameters)
        {
        }

        private void CreateIfNotExists(string name, string description, int order)
        {
            if (string.IsNullOrEmpty(name))
            {
                throw new ArgumentNullException("name");
            }
            if (string.IsNullOrEmpty(description))
            {
                throw new ArgumentNullException("description");
            }

            var categories = CategoryList.LoadCategories();
            if (categories.Contains(name))
            {
                return;
            }

            var category = new Category(name, description)
                           {
                                   Available = true,
                                   Parent = Category.GetRoot(),
                                   SortOrder = order
                           };

            category.Save();
        }
    }
}
#87852
Edited, Jun 24, 2014 14:24
This topic was created over six months ago and has been resolved. If you have a similar question, please create a new topic and refer to this one.
* You are NOT allowed to include any hyperlinks in the post because your account hasn't associated to your company. User profile should be updated.