Ways How To Customize Umbraco CMS



Why is Umbraco one of the most popular and powerful CMS system based on ASP.NET framework? 

The most advantage of this CMS that you can create simple websites very quickly and in a very fast way even if you don't have deep knowledge of ASP.NET and C#. But in other cases when you need to create something match bigger or when you need to integrate your website with existing systems or implement complex business logic with workflows or e-commerce systems with few application levels you can and should use powerful of ASP.NET framework.


In current series of articles, we will go for most useful approaches how we can customize Umbraco like extending and access to Umbraco database, custom sections and pages in Umbraco admin portal, custom data editor and configuration controls.

  

  1. Quick guide how to setup and configure Umbraco by Visual Studio
  2. Extending database. Example for saving newsletter subscriptions (Part 1)
  3. Extending admin portal. Creating custom menu and displaying newsletter subscriptions (Part 2)
  4. Creating custom data editors (Part 3)

For example in this article we used Umbraco 7.4.2 with standard theme (Fanoe). If you did not know how to install Umbraco than go to the installation quick guide.

 

Goal. We need to create a simple form which allows website visitors subscribe to newsletters. For example:

All subscribed emails should be saved in a separate table of MS SQL Server database. And that’s all.

I prefer to start with database and database access. Let’s create a new table where will be saved emails of subscribed users. For doing this navigate to your Umbraco DB and create a table. You can use the script below or use a constructor. Just make sure that your fields and table have the same names:

GO
CREATE TABLE [dbo].[ customNewsletterSubscriptions]
(
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[Email] [nvarchar](254) NOT NULL,
	[CreatedOn] [datetime] NOT NULL,
 	CONSTRAINT [PK_NewsletterSubscriptions] PRIMARY KEY CLUSTERED ([Id] ASC)
	WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, 
	LLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO

Then you need to go to your project in Visaul Studio and create class model which will be mapped to our table in database.  Form mapping, we should use attributes from Umbraco.Core.Persistence namespace. We need TableName, PrimaryKey, Column and some others attributes. Also in this namespace present other helpful attributes. Use Umbraco documentation to find more details about them.

Completed class should looks as showed in code below. Instance of NewsletterSubscriptionModel NewsletterSubscriptionModel class represent record in customNewsletterSubscriptions table. Then each column should have his own property with the attribute as shown bellow.

using System;
using Umbraco.Core.Persistence;
using Umbraco.Core.Persistence.DatabaseAnnotations;

namespace UmbracoCustomizationExample.Web.DbModels
{
    [TableName("customNewsletterSubscriptions")]
    [PrimaryKey("Id", autoIncrement = true)]
    [ExplicitColumns]
    public class NewsletterSubscriptionModel
    {
        [Column("Id")]
        [PrimaryKeyColumn(AutoIncrement = true)]
        public int Id { get; set; }

        [Column("Email")]
        public string Email { get; set; }

        [Column("CreatedOn")]
        public DateTime CreatedOn { get; set; }
    }
}

Now we need some controller which should save subscription request. For this purpose we can create Umbraco Surface controller make sure that this controller is in the Controllers folder.

using System;
using System.Web.Mvc;
using Umbraco.Web.Mvc;
using UmbracoCustomizationExample.Web.DbModels;

namespace UmbracoCustomizationExample.Web.Controllers
{
    public class NewsletterSubscriptionController : SurfaceController
    {
        public JsonResult PostSubscription(string email)
        {
            if (!string.IsNullOrWhiteSpace(email))
            {
                var model = new NewsletterSubscriptionModel
                {
                    CreatedOn = DateTime.Now,
                    Email = email
                };
                ApplicationContext.DatabaseContext.Database.Insert(model);
            }
            
            return Json(new { Success = true, Message = $"Your email {email} successfully added to newslatter maling list."});
        }
    }
}

In Controller we have few important places:

  1. Controller is inherited from SurfaceController
  2. Access to database provided by ApplicationContext.DatabaseContext.Database.

The ApplicationContext.DatabaseContext.Database contains all common methods which basically need for work with a database.

And that is all for the backend.

 

Now let’s create simple HTML form:

 

  1. Navigate to Umbraco admin portal and go to Developer section. In this section create Partial View Macro named SubscriptionForm and don’t forget check “Create Macro”.

After that expand Macros folder where you found SubscriptionForm item. For this item select checkboxes as showed below:

 

Then go to Data Types folder, select Grid FrontPage datatype. Select Full width content row configuration and set for this row Macro checkbox. Save changes.

       2. Now go to Visual Studio. In Solution Explorer select option “Show All Elements”.Then include SubscribtionForm.cshtml file to solution.

 

Then put in this file next code bellow. This is very simple form with one text box and button. Its perform POST AJAX action to send email to NewsletterSubscriptionController.

<div style="margin: 25px 0;">
    <span></span>
    <h4>Newsletter <br /><small>Sign up bellow to reciave all the lasted updates & news from our website.</small></h4>
    <div class="input-group">
        <input type="email" class="form-control" placeholder="Your email address" required="Your email addrees is reqired" id="txtEmail">
        <span class="input-group-btn">
            <button class="btn btn-primary" type="button" id="btnSubscribe">Subscribe</button>
        </span>
    </div>
</div>

<script type="text/javascript">
    $(function () {
        var $btnSubscribe = $('#btnSubscribe');
        $btnSubscribe.on('click', function () { postSubscribtionForm(); });
    });

    function postSubscribtionForm() {
        var $txtEmail = $('#txtEmail');
        $.post('@Url.Action("PostSubscription", "NewsletterSubscription")', { email: $txtEmail.val() }, function (response) {
            if (response.Success) {
                $txtEmail.val('');
                alert(response.Message);
            }
        });
    }
</script>



I do not want to spend time with configuring BundleConfig . Therefore I just move my JQuery script to head blog in Maser.cshtml page. Other way my scripts in RenderBody could not use JQuery.

Then we need to go to Content section of Umbraco admin. Select Home page and navigate to content tab. Stroll to bottom and click on (+) button and select Macro. From left bar select macro previous created macro page.



Best Regards. Alexander Mykytyn

Comments (2) -

  • tktiXY4aU

    1/16/2017 7:15:33 PM |

    601962 759728when i was a kid, i really like to receive an assortment of birthday presents like teddy bears and mechanical toys, 576256

Loading