I've constructed a dynamic placeholder using the top answer in this post: https://stackoverflow.com/questions/15134720/sitecore-dynamic-placeholders-with-mvc.
This implementation uses the GUID of the current context item to generate a unique id to append to the end of each dynamic placeholder. Instead of using a GUID, I would like the placeholder keys to be sequential. For example, if there is one dynamic row placeholder on the page, the placeholder would become row1. If two row placeholder are on a page, they would be row1, and row2. Three would be row1, row2, and row3. And so on.
I have successfully implemented the code from the above post in my environment, but I've been unable to get the sequential count of dynamic placeholders to work. Originally, I tried a static variable on the placeholder class, but the value of that field persisted on page refresh (If I started with row1, row2 on refresh I would get row3, row4). Next I tried to read the number of row placeholders on the page from the current context item, however the list that is returned never contains the row placeholder, only its parent.
Here is the rendering which contains the dynamic placeholder call:
<div class="row_block">
@Html.Sitecore().DynamicPlaceholder("row")
</div>
And here is my modified SitecoreHelper class from the original post:
public static class SitecoreHelper
{
public static HtmlString DynamicPlaceholder(this Sitecore.Mvc.Helpers.SitecoreHelper helper, string dynamicKey)
{
int id = GetId(dynamicKey);
return helper.Placeholder(string.Format("{0}{1}", dynamicKey, id++));
}
private static int GetId(string placeHolderName)
{
bool NeedIncrement = false;
int IncrementStep = 0;
var myPlaceholders = ContextService.Get().GetInstances<PlaceholderContext>();
foreach (PlaceholderContext myPHContext in myPlaceholders)
{
if (myPHContext.PlaceholderName == placeHolderName || myPHContext.PlaceholderName.StartsWith(placeHolderName))
{
NeedIncrement = true;
IncrementStep++;
}
}
if (!NeedIncrement)
{
IncrementStep = 1;
}
return IncrementStep;
}
}
Is there an way for me to generate sequential ids for these placeholder keys based on the number of times the base dynamic key appears? Thanks for the help!