Sitecore PowerShell: Programmatically Adding Renderings to a Dynamic Placeholder

For a past project, I wrote a lot of migration scripts using PowerShell for Sitecore. One challenge that came up frequently was to add renderings to Dynamic Placeholders. Dynamic Placeholders have a path as such:

/top-level-placeholder/destination-placeholder-{parent rendering’s unique id}-#

The tricky bit is that the Parent Rendering’s Unique ID is not assigned until the Parent Rendering is placed on the page in question.

One of the Renderings using Dynamic Placeholders in our new solution is an Accordion. The Accordion control has two components:

  1. A Parent Accordion Rendering which contains a Dynamic Placeholder named “Accordion-Children” for any number of Accordion Child Renderings.
  2. Accordion Child Renderings to reside in the Parent Accordion’s Dynamic Placeholder, “Accordion-Children”

The example below uses my Add-NewRendering function as illustrated in my other blog: Sitecore PowerShell Rendering Helper Functions, so be sure to check that out too.

function Copy-AccordionRichText {
		$destinationPage, # Sitecore Page Item where the Accordion resides
		$accordionParentRenderingInstance # The Accordion Parent rendering, retrieved from $destinationPage 

	# Create-RenderingDatasource is a simple function that creates a new 
	# Sitecore Item of type AccordionChild
	$accordionChildDatasource = Create-RenderingDatasource `
		-parentPath $destinationPage.Paths.FullPath `
		-datasourceName "Accordion Child - $($sourceDatasourceItem.Name)" `
		-datasourceType $destinationTemplateIDs.AccordionChildID

	# Populate the new AccordionChild Fields
	$accordionChildDatasource.Fields[$destinationFieldIDs.AccordionChild.Heading].Value = “Accordion Child Heading”
	$accordionChildDatasource.Fields[$destinationFieldIDs.AccordionChild.Text].Value = “Accordion Child Text”
	$accordionChildDatasource.Editing.EndEdit() | Out-Null # Swallow Out-Null’s output 

	Add-NewRendering `
		-databaseName "master" `
		-dataSourceID $accordionChildDatasource.ID `
		-pageItem $destinationPage `
		# Here’s where we build the Dynamic Placeholder Path
		-placeHolder "/vca-body/Accordion Children-$($accordionParentRenderingInstance.UniqueID.ToString())-0" `
		-renderingItemID $destinationItemIDs.Renderings.AccordionChild `
		-renderingIndex 0