I needed to do this to avoid hard-coding database names when publishing programmatically. So I went in to see how Sitecore does it from the ribbon command (
Sitecore.Shell.Framework.Commands.PublishNow
)After some digging around in the Kernel, I ended up with something along these lines:
Database contextDatabase = Sitecore.Context.Database;
Item itemToPublish = contextDatabase.GetItem("/sitecore/content/home"); //some item that needs to be published
//get all the available targets
List<Database> databases = new List<Database>();
ItemList targets = PublishManager.GetPublishingTargets(contextDatabase);
foreach (Item targetItem in targets)
{
Database database = Factory.GetDatabase(targetItem[FieldIDs.PublishingTargetDatabase]);
if (database != null)
{
databases.Add(database);
}
}
List<Language> languages = new List<Language>();
languages.Add(itemToPublish.Language);
//invoking the static PublishManager.PublishItem
PublishManager.PublishItem(itemToPublish, databases.ToArray(), languages.ToArray(), false, true);
If working within the Sitecore Client, you will want to use
Sitecore.Context.ContentDatabase
instead of Sitecore.Context.Database
Also, if you want to publish in all languages, you can use
LanguageManager.GetLanguages(contextDatabase)
instead.
No comments:
Post a Comment