In a recent question that popped up on Stackoverflow, the user was trying to add some content via the Page Editor, but if the datasource was not set they were using code to create a child item under the current item and set that to the datasource. I suggested setting the
Datasource Location and
Datasource Template fields on the Rendering and just let the user handle the action via the “Select the Associated Content” dialog.
Unfortunately I couldn’t find a good blog post which covered the information I was trying to portray, or my Google skills were lacking a bit. For those seasoned Sitecore developers, this should be pretty second nature, but hopefully useful info for those new to Sitecore and finding their way around.
The following is out-of-the-box functionality, and provides a very user friendly way to add a component to a page and then associate existing or create a new item of a predefined template.
Prompt user to “Set the Associated Content”
In your sublayout definition item, select a template in the
Datasource Template field. This is used to restrict the type of item that a user can select from the content tree, or the type of item that will be created if they want to create a new item instead.
Also set the
Datasource Location field, this restricts the location in the content tree the user is able to select an item from or where the new item should be created. You can use an absolute location(e.g.
/sitecore/content/some-location) or use
./ to locate the item under the under context item. Both these fields need to be set in order to force the dialog to pop up:
Make sure you have added the control to the
Allowed Controls field in the placeholder. Now you should be able to select the control from the Page Editor:
(Yes, don’t be shy to set a Thumbnail for the control either to make it look a bit prettier )
Once you add the control you will be presented with a “Select the Associated Content” dialog. You can either select an existing item (from the location you set earlier) or create a new content item of the type you specified in
Datasource Template. Give the item a name click OK.
The related content item will now be created, the rendering added in the Page Editor and the Datasource of the rendering automatically set to your newly created item. The content is also immediately editable without having to click the save button:
If you want to change the datasource item to something else, or create a new associated item click the button highlighted in red and you can repeat the process.
Yup, no code required 🙂