Back up

Code Pharaoh

Creating a custom context menu item in Umbraco 7

#Umbraco #c#


Whenever I am creating a new Umbraco site I like to stress test the menus to make sure they can accommodate a large number of pages, to do this I need to create a large number of pages, this normally involves creating a single page and then copying that page over and over to build up a section of content. Unfortunately the process for copying a page in Umbraco requires about five or six clicks for each copy. I decided I wanted to create a little package that would allow me to 'Duplicate' a page in Umbraco rather than using the copy functionality. To do this I wanted to add in a new context menu item for each node in the site to add my new duplicate functionality along side the existing copy functionality native to Umbraco.

It turns out that doing this is pretty easy (note, You should be familiar with writing Angular plugins for Umbraco 7 and storing them in the App_plugins folder):

You can use the Application Event Handler plugin type to intercept the TreeControllerBase.MenuRendering event and add in your new control.

 

using Umbraco.Core;
using Umbraco.Web.Trees;
namespace CP.UmbracoDuplicateContent.ApplicationEvents
{
    public class DuplicateContent : ApplicationEventHandler
    {
        protected override void ApplicationStarted(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext)
        {
            TreeControllerBase.MenuRendering += ContentTreeController_MenuRendering;
        }
        private void ContentTreeController_MenuRendering(Umbraco.Web.Trees.TreeControllerBase sender, Umbraco.Web.Trees.MenuRenderingEventArgs e)
        {
            switch (sender.TreeAlias)
            {
                case "content":
                    var i = new Umbraco.Web.Models.Trees.MenuItem("duplicateNode", "Duplicate");
                    //optional, if you dont want to follow conventions, but do want to use a angular view
                    i.AdditionalData.Add("actionView", "/App_Plugins/DuplicateNode/DuplicateNodeView.html");
                    i.Icon = "user-females-alt";
                    //insert at index 5
                    if (e.Menu.Items.Count > 5)
                    {
                        e.Menu.Items.Insert(5, i);
                    }
                    break;
            }
        }
    }
}

 

You can see above that we are hooking into the Menu Rendering event and if the menu being rendered is the 'Content' menu then we insert our new menu item at position 5, I also do a test to make sure there are more than 5 items in the menu so as not to add my duplicate function into the root context menu. Check out the repo for this code and please feel free to contribute if you spot any errors or improvements that can be made.

This code was originally found in this gist made by Per Ploug.

Here is how the item looks when added to the menu: