Ensure only one instance of a particular page type can be created at a specific location

Tom Troughton asked on April 1, 2016 11:54

What is the best approach to ensure an editor can only create a single instance of a specific page type in a particular location?

Correct Answer

Dawid Jachnik answered on April 1, 2016 12:11

Hello,

Interesting... Maybe try use events handler ?

for example:

using CMS.Base;
using CMS.DocumentEngine;
using System;

[CustomDocumentEvents]
public partial class CMSModuleLoader
{
/// <summary>
/// Attribute class that ensures the loading of custom handlers.
/// </summary>
private class CustomDocumentEvents : CMSLoaderAttribute
{
    /// <summary>
    /// The system executes the Init method of the CMSModuleLoader attributes when the application starts.
    /// </summary>
    public override void Init()
    {
        // Assigns custom handlers to events
        DocumentEvents.Insert.Before += DocumentInsert_Before;
    }

    private void DocumentInsert_Before(object sender, DocumentEventArgs e)
    {
        var doc = e.Node;
        if (doc == null) return;
        if (doc.ClassName != "pageclassname") return;

        var quanity = DocumentHelper.GetDocuments(doc.ClassName)
            .WhereLike("NodeAliasPath", e.TargetParentNode.NodeAliasPath)
            //others conditions
            .Count;
        if (quanity > 1)
            throw new Exception("Only single instance of this page type is allowed in this location!");
    }
}
}
5 votesVote for this answer Unmark Correct answer

Recent Answers


Tom Troughton answered on April 1, 2016 13:02

Thanks, yes, that would work. Curious to know if there are other approaches e.g. if Kentico provides something out-of-the-box to achieve this? I assume it's a fairly common requirement, for example when creating landing pages for dedicated content areas...

0 votesVote for this answer Mark as a Correct answer

Dawid Jachnik answered on April 1, 2016 13:09

I think you could achive this by other way using page scopes and define macro condition that checks the quantity of pages of specified type. It will be similar to my examply, but in K#.

3 votesVote for this answer Mark as a Correct answer

Brenden Kehren answered on April 1, 2016 15:17

Nat, as Dawid suggests, there is no way OOTB to handle this from a simple/singular solution. What Dawid provides is a pretty simple straightforward solution. Only downfall I'd see with it is it's hard coded for only that one document type and count. If you wanted to make this more robust you could create a custom module for it or simply use a custom table and add entries in there which have Page Type class names, node location and count. Then you'd do a lookup in a custom table to find any matching records for this node and then run your GetDocuments() method.

0 votesVote for this answer Mark as a Correct answer

   Please, sign in to be able to submit a new answer.