Search code examples
sitecoresitecore7

Sitecore Set the Number of Components


Is it possible to set the number of components in placeholder?

We can add as many as components in placeholder by using "Add to here" in gray box even the component has been already added.

I'd like to say that

In plcaceholder named 'bodyArea', you can set only one component in 'bodyArea' placeholder and you will not add any other component additionally.

Is there anyway how to do this??


Solution

  • There could be many ways, but this is what I used before.

    // Check the number of renderings in placeholder
    public static bool numberOfRenderings(string placeholderName)
    {
        bool rendering = true;
        var renderingReferences = Sitecore.Context.Item.Visualization.GetRenderings(Sitecore.Context.Device, true);
        int renderingsInPlaceholder = renderingReferences.Where(r => r.Placeholder.EndsWith('/' + placeholderName, StringComparison.OrdinalIgnoreCase)).Count();
    
        if (renderingsInPlaceholder > 1)
        {
            return rendering = false;
        }
        return rendering;
    }
    

    In View.cshtml

    if (@yourObject.numberOfRenderings("your-placeholder-key")) {
        @Html.Sitecore().Placeholder("your-placeholder-key")
    }
    else 
    {
        @Html.Raw("<div>Only one rendering item is available in this placeholder.</div>")
    }