Experience Sitecore ! | All posts tagged 'Helix'

Experience Sitecore !

More than 200 articles about the best DXP by Martin Miles

Updating existing presentation details of base template's standard values after it has been set on derived templates

Problem: let's imagine the situation when you may have some complex template inheritance. You would like to set presentation details for each of these templates' standard values, somehow like below:

A - define layout, and header/footer common holders that will be shared for all sites (we've got a multisite setup for now)

B - define footer and header on a site level so that they remain the same within each of implemented sites 

C - define base page template that will add the rest of presentation shared between the pages (but not homepage)

Once you set presentation for standard values of A, you can go to standard values of B and see these changes, so that you add only B-specific components; the same exact story will be when you will go next to std. values of C an so on. So far, so good.

The problem occurs when you want to modify presentation coming with a base template after a derived presentation is already set. In that case, you will not see any difference, that may be seen a weird for a while. In our example, imagine you've set presentation for std. values of all three templates - A, B and then C, and then decided to add one more component to a presentation on A template (or change datasource item of existing etc.). You do changes for std. values of A, save it and as you see - these changes come into a play for template A, however, once you open B or C  they won't be there...

Explanation: let's think what in fact Standard Values are - just the default values for each of field defined in that (or parent) template. In the second case if a field has standard values for both parent and inherited template - it simply overrides parent value with inherited child's value. But, wait for a second - presentation is also stored in fields of Standard Template that all pages inherit from, how that makes possible, does it simply override?

No, for such particular cases when presentation fields are involved - override behaviour would not work at all. Let's look at our example - template A defines layout and header/footer sublayout and all that goes within __Renderings field - it's where (shared, not versioned) presentation is stored in XML-serialised format. But then, it would be overridden by setting concrete footer with no layout. Since it is the same field - it will lose layout at template B level and entire behaviour does not make any sense. To address this issue Sitecore implements a feature called Layout Deltas - so that presentation fields are not stupidly overwritten. Instead, after we defined default presentation for template A, it goes as is, as A does not have any base template with presentation set. But when setting presentation for B - it will only save the difference between itself and presentation of base template (if exists). When page is being rendered, Sitecore is wise enough to construct resulting page presentation from all the base templates only adding deltas with each derived template. That is how Layout Deltas work.

One may create multilevel presentation inheritance of standard values, appending more and more presentation on each of derived levels. However, when we want to adjust the presentation of base template (A) of current template (B) - changes will be affected only for A, but not B or C if they already have layout deltas defined. That behaviour raises questions without a doubt.

Solution: what we need to do to in order to ensure changing presentation details for A will be affected for all derived templates' items is to recourse inheritance tree of A and re-calculate layout delta for each of them with recent updates from A. In order to get this done I have re-worked a solution suggested by ... The difference is that since that time we now got a feature called Versioned Layouts, so that we need to operate both fields - __Renderings and __Final Renderings correspondingly. Apart from that I have tested it for a while and fixed few of stability issues.

Implementation: when we change presentation - we change the field, so eventually the holding item is being updated. In order to intercept this we add a pipeline processor for item:saving event:

<?xml version="1.0" encoding="utf-8"?>
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/" xmlns:set="http://www.sitecore.net/xmlconfig/set/">
  <sitecore>
    <events>
      <event name="item:saving">
        <handler type="Sitecore.Foundation.Presentation.Services.LayoutInheritance, Sitecore.Foundation.Presentation" method="OnItemSaving"/>
      </event>
    </events>
  </sitecore>
</configuration>

And the code. I am using XmlDeltas.GetDelta() and XmlDeltas.ApplyDelta() static classes of Sitecore.Data.Fields namespace to make this work.

using System;
using Sitecore;
using Sitecore.Data;
using Sitecore.Data.Events;
using Sitecore.Data.Fields;
using Sitecore.Data.Items;
using Sitecore.Data.Managers;
using Sitecore.Data.Templates;
using Sitecore.Diagnostics;
using Sitecore.Events;
using Sitecore.Globalization;
using Sitecore.SecurityModel;

namespace Sitecore.Foundation.Presentation.Services
{
    public class LayoutInheritance
    {
        public void OnItemSaving(object sender, EventArgs args)
        {
            Item item = Event.ExtractParameter(args, 0) as Item;
            PropagateLayoutChanges(item);
        }

        private void PropagateLayoutChanges(Item item)
        {
            if (StandardValuesManager.IsStandardValuesHolder(item))
            {
                Item oldItem = item.Database.GetItem(item.ID, item.Language, item.Version);

                PropagateLayoutChangesForField(item, oldItem, FieldIDs.LayoutField);
                PropagateLayoutChangesForField(item, oldItem, FieldIDs.FinalLayoutField);
            }
        }

        private void PropagateLayoutChangesForField(Item item, Item oldItem, ID layoutField)
        {
            string layout = item[layoutField];
            string oldLayout = oldItem[layoutField];

            if (layout != oldLayout)
            {
                string delta = XmlDeltas.GetDelta(layout, oldLayout);
                foreach (Template templ in TemplateManager.GetTemplate(item).GetDescendants())
                {
                    ApplyDeltaToStandardValues(templ, layoutField, delta, item.Language, item.Version, item.Database);
                }
            }
        }

        private void ApplyDeltaToStandardValues(Template template, ID layoutField, string delta, Language language, Sitecore.Data.Version version, Database database)
        {
            if (template?.StandardValueHolderId != (ID)null)
            {
                try
                {
                    Item item = ItemManager.GetItem(template.StandardValueHolderId, language, version, database, SecurityCheck.Disable);

                    if (item == null)
                    {
                        Log.Warn($"Foundation.Presentation: Item is null {template.StandardValueHolderId} in database {database.Name}", template);
                        return;
                    }

                    Field field = item.Fields[layoutField];

                    if (field == null)
                    {
                        Log.Warn($"Foundation.Presentation: Field is null in item {item.ID} in database database.Name", item);
                        return;
                    }

                    if (!field.ContainsStandardValue)
                    {
                        string newFieldValue = XmlDeltas.ApplyDelta(field.Value, delta);
                        if (newFieldValue != field.Value)
                        {
                            using (new EditContext(item))
                            {
                                LayoutField.SetFieldValue(field, newFieldValue);
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    Log.Info($"Foundation.Presentation: Exception {e.Message}", e);
                    throw;
                }
            }
        }
    }
}
As I am using Helix in my development, I created a foundation module Presentation and placed the above code and config into it correspondingly. 

Hope this helps someone!

Helix + Glass Mapper + T4 Templates = Code Generation

The objective of given exercise is to achieve automatic code generation of Glass Mapper model (an interface) from a corresponding serialized interface template.

First of all, you need to install Visual Studio Extension for T4 templates: for Visual Studio 2017 or 2015. Also very recommend installing Devart T4 Editor - a markup highlighter and intellisense for T4 templates, that is also a plugin for Visual Studio 2017 or 2015.

Another prerequisite is Glass Mapper itself, obviously. I would advise going with BoC.Glass.Mapper.Sc by Chris Van Steeg from Sitecore NuGet repository. The fork contains several fixes for code-first and content search usage (project fork GitHub page).

The main thing you need is Sitecore CodeGenerator, located in https://github.com/hermanussen/sitecore.codegenerator

You'll also need to have "base" templates - GlassGenerator.tt and GlassMappedClassTemplate.tt as below:


SitecoreTemplates.tt - is the template you are going to copy to each module where you may need to generate models, you may want to rename each instance of it to reflect module name.

Once copied, just paste a list of your interfaces templates into SitecoreTemplates.tt (or WhateverYouCallIt.tt, in the example below I called that same as a module name) and save the file, or optionally right-clicking "SitecoreTemplates.tt" and choosing "Run Custom Tool". You'll see you interfaces magically generated as the child items of *.tt file, with all the references set up (in my case ILink.gen.cs and ILinkMenuItem.gen.cs)

NavigationTemplates.tt (from Feature/Navigation module):

<#@ template language="C#" debug="True" #>
<#@ output extension="gen.txt" #>
<#@ include file="T4Toolbox.tt" #>
<#@ include file="$(SolutionDir)tools\CodeGeneration\T4.Templates\base\GlassGenerator.tt" #>
<#
	GlassGenerator generator = new GlassGenerator(
			"master",
			new [] { 
					"/sitecore/templates/Feature/Navigation/_Link",
					},
			(fieldId, fieldOptions) =>
				{
				});
    generator.Run();
    
	WriteLine("These files were generated:");
#>



I am attaching these TT files for your convenience below:

GlassGenerator.tt (3.6KB), GlassMappedClassTemplate.tt (3.8KB) and SitecoreTemplates.tt (1020B).

If you need to change the way how the code is being generated please consider modifying "GlassGenerator.tt" and "GlassMappedClassTemplate.tt" file located in "Configuration\CodeGeneration\Templates\Base\" solution folder.


Notes: you may have Sitecore.CodeGenerator as a part of your solution, or unload from it - code generation still would work, just please make sure template files are referencing the right paths. Samples provided above are configured as at the image above.


Helix: An approach for restoring WebRoot to an initial state of vanilla Sitecore installation

I have an interesting approach to organizing work with Helix. Imagine a quite standard situation, when you have an already running solution with a code base outside web folder, into which gulp script deploys into. Actually, default Helix scenario.

So, you've been working on some module, then halfway down you've renamed that module or simply decided to remove it from solution. After changes finishing with renaming /deleting, and following redeploying the solution, you may potentially get an error (or not get it), but in any case, sooner or later you find out that your web folder still has an old module in a previous stage, dll and configs. To fix that, a DLL of that module needs to be deleted from bin folder manually, as well as all the corresponding old config files from App_Config/Include folder. Not a nice approach...

Things get even worse if you continuously repeat that delete/rename exercise with other modules, increasing chances of malfunction or false positive, and the far you go with that - the more complicated is to clean up the ends. Can you imagine how many unwanted trails are left in your web folder?

For sanity purpose, it is the best practice to ensure that your code is deployed into a clean copy of Sitecore at webroot so that you can be sure that it functions as expected (or not). So how would you achieve obtaining an exactly the same clean Sitecore as you have installed initially, and make this procedure super quick and repeatable? In case you are working on Sitecore previous to version 9 and have used SIM tool in order to install your Sitecore instance, then the answer is obvious - just use SIM backup / restore for that Sitecore instance, quick and reliable. But what if not? What if you are using the latest Sitecore 9?

The method I am suggesting may be sort of arguably, however, it does the job perfectly, quickly and keeps things consistent and at the same place. What I do - I create an isolated git branch called SitecoreFiles_CM at the same git repository where the main codebase sits, and commit an initial state of Sitecore to that branch. Saying initial I mean exactly the same files as they were installed, before Sitecore was even ever accessed - a clean installation. Of course, not all the files are pushed to remote: things like configurations with my individual (for my local dev instance) passwords do not need to be shared with other developers as well as Sitecore license file. That's why on top of that branch that is pushed to remote, I create one more local commit having these individual settings/changes that I do not push. When I have a need to restore vanilla Sitecore, I navigate to web folder and restore folder to that commit. The next step is git clean command required to get rid of the rest of unversioned files on top of vanilla Sitecore that were deployed from the codebase. As simple, as functional.

  git reset --hard
  git clean -fdx


Both codebase and the corresponding vanilla Sitecore are kept together at the same git repo, for consistency.

Additional benefit: with git diff, you may always see the difference between current web folder state and initial clean install. Not to say, that you can restore each individual file from that set!

When doing platform version upgrades, I upgrade my major codebase along with SitecoreFiles_CM branch, so they again remain consistent Looking ahead, no one stops you from having also a SitecoreFiles_CD branch with a CD set of files, however that is outside of current discussion.

Hope this helps!

Know your tools: The easiest way to install Habitat - Habitat Solution Installer

Working with Helix often encourages you to perform quick look-ups into the live-standard-implementation - Habitat project. That's why you have to have it installed. I remember the first time I installed Sitecore Habitat in October 2015 and how complicated that seemed at glance.

Luckily we now got a nice tool, that does exactly what it is named for - Habitat Solution Installer written by Neil Shack. So, let's go ahead and install Habitat into a new non-traditional destination using that tool.

Firs of all, let's grab Habitat Solution Installer itself from Sitecore Marketplace. Once downloaded, run HabitatInstaller.exe.


First screen takes three most important Habitat setting that we usually need to change as well as asks for the solution root folder where it will install the code. Once Install is clicked - it will download an archive of master branch from Habitat GitHub repository.


Then it will extract downloaded archive into temporal folder. By the way, you may alternate both path to master archive and your temporal files folder by clicking Settings button on the first (main) screen.


After extracting files, it will run npm install so you need to have node installed as a prerequisite.


Once finished, Habitat Solution Installer will display confirmation box.


So, what it has done - it installed and configured project code folder. But what hasn't it done?

1. It does not install Sitecore. You need to have it installed as another prerequisite, so that you provide Sitecore web folder and hostname to installer as shown on first screenshot. The best way would be to install using SIM (marketplace link). While installing Sitecore, make sure you're installing the right version corresponding to to codebase at Habitat master branch, you may look it up at Habitat Wiki page.

2. Not just to say you need to install Sitecore itself, you also need to install Web Forms for Marketers of the version corresponding to you Sitecore instance. And to ensure WFFM installation not failing, you need to install MongoDB prior to. Luckily that can be done in one click using SIM:


Finally, when all above is done, you may run gulp tasks from Task (View => Other Windows => Task Runner Explorer in Visual Studio 2015). Since npm install was already done for you - tasks are loaded as normal:


That's it! After Sitecore items are deserialised into your Sitecore instance, you'll be able to run Habitat website (however do not forget to publish from master to web unless you run it in live mode). The final result comes in you browser:


Know your tools: The easiest way to add a new project into your Helix solution

UPDATE: just came across a better solution from kamsar, that generates code, serialization and tests for the module. Please use that one instead of described below, however, the principle described below is exactly the same so you may refer for the sake of understanding.

---------------------------- original text below ----------------------------

I have found a great solution that makes adding a new project into existing Helix / Habitat solution so transparent and painless - Prodigious Helix Generator.

The guidance is well done and describes all thee steps. Is is soooo easy, and removes pain of fixing some forgotten references / namespaces / etc after you accidentally found out. It also optionally creates TDS project skeleton for your module, once you need to serialise items (why not to add Unicorn in addition to?).

So, to make it work you need to install yeoman first and afterwards the generator tool itself:

npm install -g yo
npm install -g generator-prodigious-helix

One important thing to mention is that not to mess with the paths and to get new module generated under the right path - run it at the root of your solution / repo.

You are at a choice of 3 options. In order to add a foundation, type in:

yo prodigious-helix:foundation

to make a feature:

yo prodigious-helix:feature

and for project even simpler:

yo prodigious-helix

As for example, below I am creating a new foundation module called AdminTools for the solution named HelixSolution. That will result in creating me a project called HelixSolution.Foundation.AdminTools within a same name folder (created) at the right path under Foundation folder. All the namespaces, references, settings and naming conventions would be auto-generated and correct!


After answering those 3 questions, you'll get your stuff generated:


That's it!

The only thing I noticed it that it appends solution name under App_config folder: App_Config\Include\HelixSolution\Feature\Feature.AdminTools.config so depending on your setup you may need to move Feature\Feature.AdminTools.config one level up into Include folder.

Hope it will start saving your time as much as it saves mine.

Migrating existing code to Helix. Fixing invalid dynamic placeholders

Recently I have inherited a project that utilised dynamic placeholder in a weird way:

public static HtmlString DynamicPlaceholder(this SitecoreHelper helper, string placeholderKey)
{
    if (string.IsNullOrEmpty(RenderingContext.Current.Rendering?.DataSource))
        return helper.Placeholder(placeholderKey);

    var currentRenderingId = Guid.Parse(RenderingContext.Current.Rendering.DataSource);
    return helper.Placeholder($"{placeholderKey}_{currentRenderingId}");
}

instead of more commonly used way suggested by Jason Bert:

namespace DynamicPlaceholders.Mvc.Extensions
{
	public static class SitecoreHelperExtensions
	{
		public static HtmlString DynamicPlaceholder(this SitecoreHelper helper, string placeholderName)
		{
			string text = PlaceholdersContext.Add(placeholderName, RenderingContext.Current.Rendering.UniqueId);
			return helper.Placeholder(text);
		}
	}
}

In two words, the first approach generates placeholder name using an ID of datasource item. The second approach is more traditional and is default for Helix. It was suggested by Jason Bert and also utilised by sitecore - that relies on rendering's UniqueID. In both cases, dynamic placeholders look like: /content/name-of-placeholder_017c3643-0fef-475c-95d2-bb1107beb664.

So I need to update it across entire solution. Let's iterate our items.

First of all, I do not need to go through all of item, but only those that are pages and have presentation configured, as I am going to adjust it. Secondly, those items are located under /sitecore/content folder. As many of you should know, presentation details (or deltas) for a page are kept within two fields of Standard Template - Renderings and Final Renderings that correspond to configuration you see at Shared Layout and Final Layout tabs. These thoughts resulted in using following Sitecore query to identify those items:

/sitecore/content//*[@__Renderings != '' or @__Final Renderings != '']

So far, so good. Also need to mention that I will perform the operation for master database only and for Default device:

private const string DatabaseName = "master";
private const string DefaultDeviceId = "{FE5D7FDF-89C0-4D99-9AA3-B5FBD009C9F3}";

I am using Sitecore presentation API in order to achieve my goal. Below is my Iterate() method:

public Dictionary<Item, List<KeyValuePair<string, string>>> Iterate()
{
    var result = new Dictionary<Item, List<KeyValuePair<string, string>>>();

    var master = Factory.GetDatabase(DatabaseName);
    var items = master.SelectItems(ItemsWithPresentationDetailsQuery);

    var layoutFields = new[] {FieldIDs.LayoutField, FieldIDs.FinalLayoutField};

    foreach (var item in items)
    {
        foreach (var layoutField in layoutFields)
        {
            var changeResult = ChangeLayoutFieldForItem(item, item.Fields[layoutField]);

            if (changeResult.Any())
            {
                if (!result.ContainsKey(item))
                {
                    result.Add(item, changeResult);
                }
                else
                {
                    result[item].AddRange(changeResult);
                }
            }
        }
    }

    return result;
}

That method iterates through each item from returned from the query and calls ChangeLayoutFieldForItem for that item twice - for both presentation fields Renderings and Final Renderings.

private List<KeyValuePair<string, string>> ChangeLayoutFieldForItem(Item currentItem, Field field)
{
    var result = new List<KeyValuePair<string, string>>();

    string xml = LayoutField.GetFieldValue(field);

    if (!string.IsNullOrWhiteSpace(xml))
    {
        LayoutDefinition details = LayoutDefinition.Parse(xml);

        var device = details.GetDevice(DefaultDeviceId);
        DeviceItem deviceItem = currentItem.Database.Resources.Devices["Default"];

        RenderingReference[] renderings = currentItem.Visualization.GetRenderings(deviceItem, false);

        var datasourceGuidsToRenderingUniqueIdMap = renderings
            .Where(r => !string.IsNullOrWhiteSpace(r.Settings.DataSource))
            .Select(r => new KeyValuePair<string, string>(Guid.Parse(r.Settings.DataSource).ToString(), r.UniqueId));

        if (device?.Renderings != null)
        {
            foreach (RenderingDefinition rendering in device.Renderings)
            {
                if (!string.IsNullOrWhiteSpace(rendering.Placeholder))
                {
                    var verifiedPlaceholderKey = FixPlaceholderKey(rendering.Placeholder, datasourceGuidsToRenderingUniqueIdMap);
                    result.Add(new KeyValuePair<string, string>(rendering.Placeholder, verifiedPlaceholderKey));
                    rendering.Placeholder = verifiedPlaceholderKey;
                }
            }

            string newXml = details.ToXml();

            using (new EditContext(currentItem))
            {
                LayoutField.SetFieldValue(field, newXml);
            }
        }
    }

    return result;
}

Further down it creates a list of matches for all the renderings within current presentation field of that particular item - datasource GUIDs matching to unique rendering IDs to go through it and do a replacement - that is done in FixPlaceholderKey method. Once everything is replaced, save the field by calling LayoutField.SetFieldValue() of course wrapping that call with EditContext as we are modifying item's field value.

FixPlaceholderKey is a simple method that just does case insensitive replacement by using Regex:

private string FixPlaceholderKey(string renderingInstancePlaceholder, IEnumerable<KeyValuePair<string, string>> map)
{
    var value = renderingInstancePlaceholder;

    foreach (var oldValue in map)
    {
        value = Regex.Replace(value, oldValue.Key, Guid.Parse(oldValue.Value).ToString(), RegexOptions.IgnoreCase);
    }

    return value;
}

That is pretty everything about the dynamic placeholder fixing logic.

But as for my case - I was aware that I'll need to run this dynamic placeholder replacements few more times in future and will likely need to implement some other similar small tools. So I decided that it would be great to place it under /sitecore/admin folder along with other admin tools - exact location by purpose! And since we're now going Helix, I decided to follow good principles and created a foundation module called AdminTools, where I will be adding similar admin folder tools. So here's how it looks for me in the Solution Explorer:


FixDynamicPlaceholders.aspx is a classical ASP.NET WebForm with one line markup (ah-h, I was so lucky not to deal with Webforms for couple past years till the moment)

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="FixDynamicPlaceholders.aspx.cs" Inherits="HomeServeUsa.Foundation.AdminTools.sitecore.admin.Maintenance.FixDynamicPlaceholders" %>

and the codebehind. Since FixDynamicPlaceholders.aspx is admin tool page - codebehind is inherited from Sitecore.sitecore.admin.AdminPage:

public partial class FixDynamicPlaceholders : AdminPage
{
    protected void Page_Load(object sender, EventArgs e)
    {
        var fixRenderings = new DynamicPlaceholdersModifyService();
        var result = fixRenderings.Iterate();

        OutputResult(result);
    }

    private void OutputResult(Dictionary<Item, List<KeyValuePair<string, string>>> result)
    {
        Response.ContentType = "text/html";

        Response.Write($"<h1>{result.Count} items processed</h1>");
        foreach (var pair in result)
        {
            Response.Write($"<h3>{pair.Key.Paths.FullPath}</h3>");

            foreach (var kvp in pair.Value)
            {
                if (kvp.Key != kvp.Value)
                {
                    Response.Write($"<div>{kvp.Key} ==> {kvp.Value}</div>");
                }
            }
        }
    }
}

Finally, it is complete. Hope this helps someone!

P.S. of course, that would be easier (and more elegant) to perform with Sitecore PowerShell extension. But unfortunately I am the only person in the organisation who uses it regardless of my promotional activity.

Why am I getting "Item is not a template" error on data items in Content Editor?

Very simple and even stupid error I have met few times, just want to describe it here to make it google-searchable so that it might help someone.

Image you're going across you content items , and when clicking by one of your data items, you see similar screen, saying: Item "/sitecore/content/Home/Data/Simple item" is not a template.



First of all, why does I got yellow screen? Well, the error is quite descriptive, saying that my Simple item is not a template.

Sure, it isn't, we know that and can prove that by clicking Content tab, that will show us exactly the item's data:


But why on earth do I see other two tabs, that shouldn't be there for data item?

The answer can be either of two cases:

1. Simple silly case - the template of you item is either directly inherited from default Template item (located at /sitecore/templates/System/Templates/Template) rather than Standard template (/sitecore/templates/System/Templates/Standard template).


In that case simply replace one with Standard template to fix.

2. More complex case - when you're likely to have a complicated inheritance chain, especially if you are working with Helix or playing around Habitat. It that case your data item is based on a composite template, that is likely to inherit multiple other templates, at least one of which inherits from Template rather than Standard template, exactly as described in a case above. Solution is the same as above - identify the culprit and change inheritance to Standard template.

Finally your data will be based on correct set of templates and you won't evidence unwanted tabs anymore.

Hope this post helps someone!

Helix project, MVC routing and the form posting back to controller. Part 3 - Adding validation

In previous post we have created an MVC form, that submits to a feature controller and set up the routing to make it all work. In this part we'll add validation to that form. This part does not differ from traditional MVC approach, however let's make our form smooth and complete.

1. Add validation controls into a page for each of inputs:

@using (Html.BeginRouteForm(MvcSettings.SitecoreRouteName, FormMethod.Post))
{
    @Html.LabelFor(x => x.FirstName)
    @Html.TextBoxFor(x => x.FirstName)
    @Html.ValidationMessageFor(x => x.FirstName)

    @Html.LabelFor(x => x.LastName)
    @Html.TextBoxFor(x => x.LastName)
    @Html.ValidationMessageFor(x => x.LastName)

    @Html.LabelFor(x => x.Email)
    @Html.TextBoxFor(x => x.Email)
    @Html.ValidationMessageFor(x => x.Email)









}
2. Model needs to be updated with validation action filter attributes, provided by DataAnnotations:
using System.ComponentModel.DataAnnotations;

namespace YourSolution.Feature.Test.Models
{
    public class TestModel
    {
        [Display(Name = nameof(FirstNameLabel), ResourceType = typeof(TestModel))]
        [Required(ErrorMessageResourceName = nameof(Required), ErrorMessageResourceType = typeof(TestModel))]
        [MinLength(3, ErrorMessageResourceName = nameof(MinimumLength), ErrorMessageResourceType = typeof(TestModel))]
        public string FirstName { get; set; }

        [Display(Name = nameof(LastNameLabel), ResourceType = typeof(TestModel))]
        [Required(ErrorMessageResourceName = nameof(Required), ErrorMessageResourceType = typeof(TestModel))]
        [MinLength(3, ErrorMessageResourceName = nameof(MinimumLength), ErrorMessageResourceType = typeof(TestModel))]
        public string LastName { get; set; }

        [Display(Name = nameof(EmailLabel), ResourceType = typeof(TestModel))]
        [EmailAddress(ErrorMessageResourceName = nameof(InvalidEmailAddress), ErrorMessageResourceType = typeof(TestModel))]
        [Required(ErrorMessageResourceName = nameof(Required), ErrorMessageResourceType = typeof(TestModel))]
        public string Email { get; set; }

        // Labels and validation messages: instead of hardcoded you may take it from Dictionary
        public static string FirstNameLabel => "First name";
        public static string LastNameLabel => "Last name";
        public static string EmailLabel => "E-mail";
        public static string Required => "Please enter a value";
        public static string MinimumLength => "Should be at east 3 characters";
        public static string InvalidEmailAddress => "please enter valid email address";
    }
}
3. Last but not the least, need to decorate POST action with validation action filter attribute, that runs validation prior to executing controller and returns validated view model on failure or runs into controller action if there no errors. So, updated controller action:
        [HttpPost]
        [ValidateModel]
        public ActionResult Test(TestModel loginInfo)
        {
            // do something on successful form submission
            return new RedirectResult("/SuccessfulResultPage");
        }
4. And of course, the ValidateModelAttribute class itself:
using System.Web.Mvc;

namespace YourSolution.Feature.Test.Attributes
{
    public class ValidateModelAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var viewData = filterContext.Controller.ViewData;

            if (!viewData.ModelState.IsValid)
            {
                filterContext.Result = new ViewResult
                {
                    ViewData = viewData,
                    TempData = filterContext.Controller.TempData
                };
            }
        }
    }
}

5. After running gulp commands for updating views and DLL libraries, an updated page would do validation similar to:


That's it! Finally, our feature project named Test would have the following structure in Solution Explorer:



Thanks for reading!

Helix project, MVC routing and the form posting back to controller. Part 2 - Creating a form

In previous part, we created a test feature, as a part of a Helix-based solution. We also created a page and rendering and wired it together. So, now it's time to create a form.

As a start, let's create a controller, as it is referenced from rendering definition item:

namespace YourSolution.Feature.Test.Controllers
{
    public class TestController : Controller
    {
        public ActionResult Test()
        {
            return View();
        }
    }
}

Then create corresponding Razor view..

@using Sitecore.Mvc.Configuration
@model YourSolution.Feature.Test.Models.TestModel

@using (Html.BeginRouteForm(MvcSettings.SitecoreRouteName, FormMethod.Post))
{
    @Html.LabelFor(x => x.FirstName)
    @Html.TextBoxFor(x => x.FirstName)
    
    @Html.LabelFor(x => x.LastName)
    @Html.TextBoxFor(x => x.LastName)

    @Html.LabelFor(x => x.Email)
    @Html.TextBoxFor(x => x.Email)
}



.. and model that represents our form, to be passed between controller and view:

namespace YourSolution.Feature.Test.Models
{
    public class TestModel
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Email { get; set; }
    }
}

As we are working with a project outside of webroot, we need to use gulp in order to copy this view into corresponding folder on the website (or you may copy that manually), same for the feature DLL.

After refreshing browser you will see the view. Obviously, when trying to hit "Submit" button - nothing happens as there's no POST controller action method. So let's add the one:

namespace YourSolution.Feature.Test.Controllers
{
    public class TestController : Controller
    {
        public ActionResult Test()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Test(TestModel loginInfo)
        {
            // do something
        }
    }
}

Still not there... why? Let's troubleshoot that. First thing to do is to find out where form does POST to. In webinspector, it shows:

  <form action="/test" method="post"> ... </form>

So far so good - that looks correct (form POSTs to itself). But how /test URL corresponds to YourSolution.Feature.Test.Controllers.Test() method of YourSolution.Feature.Test feature project?

That's where routing comes into a play. As you know, feature is just a single project that is built into individual DLL and is deployed into /bin folder of project webroot along with other libraries. So how do we wire up /test with that particular method?

We apply config patch Feature.Test.config in order to add a pipeline processor right before the one that initializes MVC routes.






      
    
  

After running gulp configuration task this patch will be put into YourSolution/Website/App_Config/Include/Features folder along with custom configuration include file patches for other feature modules. Corresponding processor will be the following:

using System.Web.Mvc;
using System.Web.Routing;
using Sitecore.Pipelines;

namespace YourSolution.Feature.Test.Pipelines
{
    public class RegisterWebApiRoutes
    {
        public void Process(PipelineArgs args)
        {
            RouteTable.Routes.MapRoute("Feature.Test.Api", "api/test/{action}", new { controller = "Test" });
        }
    }
}

Finally the last bit to make routing work - modify _ViewStart.schtml view file on the project level. Here is it:

@{
    Layout = (this.ViewContext.IsChildAction) || (this.ViewContext.RouteData.Values.ContainsKey("scIsFallThrough") && 
        Convert.ToBoolean(this.ViewContext.RouteData.Values["scIsFallThrough"])) ? null : "~/Views/Shared/_Layout.cshtml";
}

If you have done everything correctly, after gulp'ing your assets into web folder and refreshing the page in browser, you'll see a form similar to the one below:


That's it! Now the form is fully functional and POSTs to a controller, however in order to make things even better - let's apply form validation.

References:

Sitecore Helix Documentation


Helix project, MVC routing and the form posting back to controller. Part 1 - Prerequisites

At the moment I am working on challenging project that is powered by Sitecore 8.2and follows Helix principles.

Last week I implemented a Feature, that has an MVC form posting back to its controller (here I mean native MVC, not Web Forms for Marketers) module. "Not a big deal" - I thought initially... and spent more time that positively expected until finally got it implemented.

The difference between Helix project and more traditional Sitecore MVC application is that in Helix your assets - controllers, views, statics etc. are kept within an individual project for a particular Feature (or Foundation, or Project - depending on what functionality you're implementing).

Prerequisites.

I assume you already have your Helix solution ready (you may use Habitat, as an "instance" of Helix). So let's start with Sitecore.

I create a page called Test under website root using one of page templates. Next, a rendering is required to be assigned into a placeholder on a page. I create a controller rendering named Test and put it under this feature folder (also called Test). Please notice, that I have to specify controller with fully qualified name with a name of assembly where this controller resides.


Tip: do not forget to publish your items, unless you're working in a live mode from Master DB directly.


Next, let's create a project structure in Solution Explorer. As we're building a Feature, create a solution folder under Feature folder in Visual Studio and name it Test (as a feature name). Create a class library project within that folder following Helix naming conventions YourSolution.Feature.Test with the same namespace and assembly name. The easiest probably would be simply to copy project folder from an existing feature and change namespace / types there.


You need to have Web config to the project root. Please ensure you are referencing the same .NET version as set in Target Framework of the project, in my example it is 4.5.2:






  





      



      



      



      



      
    
  




    
  






    
  


Also you need to have web.config within the /Views folder to make IntelliSense work properly





Below is the minimum references you'll need to have. DataAnnotations library is not essential, for sure, but is included because it'll be needed at step 3):



At this stage we're set. Let's mote to the next step - creating and wiring up a MVC form on a rendering.

References:

Sitecore Helix Documentation