Extending Active Commerce Controllers

Follow

You may find yourself needing to extend an Active Commerce controller to override or add functionality.

Extending the controllers is a pretty straightforward process. Below, we've pulled out some key pieces from one of our training projects below showing an extension of the CheckoutController.

First, we create a new CheckoutController class that inherits from ActiveCommerce.Web.Controllers.CheckoutController. We can add our extensions and overrides here.

namespace ActiveCommerce.GiftMessage.Controllers
{
    public class CheckoutController : ActiveCommerce.Web.Controllers.CheckoutController
    {
        public virtual ActionResult UpdateGiftMessage(string giftMessage)
        {
            //ICheckOut is utilized for storing values in session during checkout
            //Our registered implementation extends the base, and implements IGiftMessage for gift message data

            var checkout = Sitecore.Ecommerce.Context.Entity.GetInstance<ICheckOut>() as IGiftMessage;
            if (checkout != null)
            {
                checkout.GiftMessage = giftMessage;
            }
            return Json(true);
        }
    }
}

Next, we'll remove the base route and register a new route for our new controller:

namespace ActiveCommerce.GiftMessage.Mvc
{
    public class RegisterRoutesInitializeProcessor
    {
        public void Process(PipelineArgs args)
        {
            RegisterRoutes(RouteTable.Routes);
        }

        public static void RegisterRoutes(RouteCollection routes)
        {
            //remove existing checkout controller
            routes.Remove(routes["Checkout"]);

            //map our extended controller
            routes.MapRoute(
                "Checkout",
                "ac/checkout/{action}",
                new { controller = "Checkout", action = "Index" },
                new[] { "ActiveCommerce.GiftMessage.Controllers" }
            );
        }
    }
}

To see the full context of this code, you can view the Gift Message training project on Github.

Have more questions? Submit a request

Comments