What you actually need to do are two things:
- Create the datasource item
- Prevent the dialog from appearing
Creating the datasource is done in the getRenderingDatasource pipeline. Add a processor before the CheckDialogState. In that processor you can put some logic to determine that you actually want to create an item. Once you determined you want to create an item, do so using the Sitecore api (you might need a security disabler and a site switcher). Add the parent to the args.DatasourceRoots
. Once the item is created, you have to set it's path in the arguments: args.CurrentDatasource = datasourceItem.Paths.FullPath;
(args being the GetRenderingDatasourceArgs
).
If you would stop here, the datasource is created and would be shown in the dialog as a prefilled value. It is not filled in
The dialog is a tricky one. Like mentioned in the comments I wrote a blog post on it. What you need to do is override (copy) the command AddRendering (Sitecore.Shell.Applications.WebEdit.Commands.AddRendering). In the run method, before the code where the dialog is opened (ShowModalDialog), you need to adapt the code (if-statement to determine whether to show the dialog or not) and send a WebEditResponse:
WebEditResponse.Eval(FormattableString.Invariant(
$"Sitecore.PageModes.ChromeManager.handleMessage('chrome:placeholder:controladded',
{{ id: '{itemNotNull.ID.Guid.ToString("N").ToUpperInvariant()}',
openProperties: {flag.ToString().ToLowerInvariant()},
dataSource: '{datasourceItem.ID.Guid.ToString("B").ToUpperInvariant()}' }});"));
This way the dialog won't open and the Sitecore editor is still notified that a rendering was added (with the datasource). Without that notification, the rendering will not be added.
ps: it is probably also possible to include the item creation in the addrendering command - didn't test that
Update: links to github repo and marketplace module containing this:
- https://github.com/Gatogordo/LocalDatasources
- https://marketplace.sitecore.net/en/Modules/L/Local_Datasources.aspx