API
Version 7.x > API > Add Widget to page programtically View modes: 
User avatar
Member
Member
BeerWill - 10/14/2012 1:06:07 AM
   
Add Widget to page programtically
I am using the Kentico 7 API to create the basics of a site for a client programmatically, and need to be able to add a widget to a page. The widget is based on the "Editable text" webpart, and I simply need to add it to a certain zone on a page, and edit the HTML content inside it. I am already successfully creating the page, putting content in particular "EditableWebParts" and publishing the node, but I'm not sure how to add in a Widget to a zone.

Does anyone have any examples of this?

Thank you,

Will.

User avatar
Kentico Customer Success
Kentico Customer Success
kentico_martind2 - 10/15/2012 10:12:57 AM
   
RE:Add Widget to page programtically
Hi Will,

1. I would recommend you to go through Developing widgets in the Developers Guide.

2. You could also find some examples in CMSSiteManager -> Support -> Api Examples -> Development -> Widgets or just simply your_site/CMSAPIexamples/default.aspx, you can show the code in the bottom windows by clicking the magnyfing glass next to the button.

I hope these examples will help you.

Best regards,
Martin Danko

User avatar
Member
Member
BeerWill - 10/15/2012 5:24:45 PM
   
RE:Add Widget to page programtically
Thanks Martin, but those examples are more about creating/updating the widget itself, rather than using an instance of a widget in code.

ie. What I need to do is:
- Create an instance of a particular widget that already exists
- Add content to a field in that widget
- Add that widget object to a particular page node in a particular zone.

I have been looking at the API examples to try and give my some pointers, but some more specific code for adding a widget to an actual Page would be great.

Thanks,
Will.

User avatar
Kentico Support
Kentico Support
kentico_jurajo - 10/16/2012 6:07:46 AM
   
RE:Add Widget to page programtically
Hi,

It is pretty complex operation - so the API example would be very complex. But, basically you can see how it is done by default in this control: \CMS\CMSModules\PortalEngine\Controls\WebParts\WebpartProperties.ascx.cs

Best regards,
Juraj Ondrus

User avatar
Member
Member
jbagnato-craniamedia - 11/3/2012 1:39:44 AM
   
RE:Add Widget to page programtically
I have been trying to solve this myself for the past few hours and am struggling to find any real documentation of how to do this. One of the sites I work on has many custom widgets and I would like to add a couple widgets when a user is first granted access to a certain group, therefore doing this programatically would be preferred.

I have determined that all of the data for widget information is stored in the CMS_Personalization table, with the properties all stored in xml in the PersonalizationWebParts field.

There is one mention of the PersonalizationInfoProvider which seems to allow you access to the PersonalizationInfo object which seems to contain this information, but there is not additional documentation. This seems to only be used in CMSWebParts\Widgets\WidgetActions.ascx.cs to delete an existing personalization.

The only place I can find where a widget is added is in \CMSWebParts\Widgets\WidgetProperties.ascx.cs in this line

widgetInstance = PortalHelper.AddNewWidget(widgetID, ZoneId, ZoneType, isLayoutZone, templateInstance, null);

I am unsure if this is what actually saves the new personalization or what. I would appreciate any guidance. The xml on the personalization does not appear to be too difficult to understand, I am just not sure which of your objects actually updates the personalization entry.


User avatar
Member
Member
jbagnato-craniamedia - 11/4/2012 2:05:35 PM
   
RE:Add Widget to page programtically
After some trial and error I figured out one solution. Like I had suspected all you need to do is add save a personalization object for the user with the document id of the widget page.

At first I just tried to modify the existing personalization object and resave it. While this updates the dbase correctly, the object stays cached and therefore the new widgets do not show up. I tested this by bouncing the server to drop the cache and sure enough the changes showed up. After trying several things to prevent caching the only solution I could get to work consistently was to just delete the entire personalization object and create a new one any time I needed to update the widgets on the page.

Below is the code I used.
        public void SetupTesterDashboard(List<AddWidgetModel> models)
{
var info = FindOrCreatePersonalizationForCurrentUserDashboard();
info.WebParts = _dashboardHandler.ComposeWebParts(models);
PersonalizationInfoProvider.SetPersonalizationInfo(info);
}

private PersonalizationInfo FindOrCreatePersonalizationForCurrentUserDashboard()
{
return RemoveAndCreatePersonalizationForSpecifiedUserDashboard(CMSContext.CurrentUser.UserID);
}

private static PersonalizationInfo RemoveAndCreatePersonalizationForSpecifiedUserDashboard(int userId)
{
DeleteExistingPersonalizationIfExists(userId);
return new PersonalizationInfo {PersonalizationUserID = userId, PersonalizationDocumentID = dashboardId};
}

private static void DeleteExistingPersonalizationIfExists(int userId)
{
var personalization = PersonalizationInfoProvider.GetUserPersonalization(userId, dashboardId);
if (personalization != null)
PersonalizationInfoProvider.DeletePersonalizationInfo(personalization.PersonalizationID);
}

The dashboardId is just the document id of the page where I am trying to add the widgets. I created a dashboard handler which simply creates the necessary XML for the page. I am sure there is some object Kentico uses to create this xml but I could not find it and found it easier to just create my own.

User avatar
Kentico Support
Kentico Support
kentico_jurajo - 11/5/2012 2:41:07 AM
   
RE:Add Widget to page programtically
Hi,

This is also the way how you can do it. However, if you want to have it "clean" I would like to recommend our consulting services where our solution architect will prepare exact code sample for you.

Best regards,
Juraj Ondrus

User avatar
Kentico Consulting
Kentico Consulting
kentico_mirekr - 12/1/2012 2:34:01 AM
   
RE:Add Widget to page programtically
Hi,

here is an example on how to add "EDITOR" widget to the page via Kentico API:
        // Create new instance of the Tree provider
TreeProvider tree = new TreeProvider(CMSContext.CurrentUser);

// Initialize variables
string culture = "en-US";
string aliasPath = "/Articles/Static";
string widgetName = "DesignElement";
string zoneID = "zoneA";

// Get document
TreeNode staticNode = tree.SelectSingleNode(CMSContext.CurrentSiteName, aliasPath, culture);

if (staticNode != null)
{
// Get widget
WidgetInfo insertWidget = WidgetInfoProvider.GetWidgetInfo(widgetName);

// Get PageInfo of the document
PageInfo docPageInfo = CMSWebPartPropertiesPage.GetPageInfo(staticNode.NodeAliasPath, staticNode.DocumentPageTemplateID, culture);

// Get template instance
PageTemplateInstance templateInstance = CMSPortalManager.GetTemplateInstanceForEditing(docPageInfo);

// Get page template info
PageTemplateInfo pti = templateInstance.ParentPageTemplate;

// Add widget to the page into "Editor Widget Zone" with ID = "ZoneA"
WebPartInstance newWidget = PortalHelper.AddNewWidget(insertWidget.WidgetID, zoneID, WidgetZoneTypeEnum.Editor, false, templateInstance);

// Set custom widget properties
newWidget.SetValue("Title", "Sample title");

// Save the changes
CMSPortalManager.SaveTemplateChanges(docPageInfo, templateInstance, WidgetZoneTypeEnum.Editor, ViewModeEnum.Edit, tree);
}

Here is an example on how to add "USER" widget to the page via Kentico API:
        // Create new instance of the Tree provider
TreeProvider tree = new TreeProvider(CMSContext.CurrentUser);

// Initialize variables
string culture = "en-US";
string aliasPath = "/Articles/Static";
string widgetName = "DesignElement";
string zoneID = "zoneA";

// Get document
TreeNode staticNode = tree.SelectSingleNode(CMSContext.CurrentSiteName, aliasPath, culture);

if (staticNode != null)
{
// Get widget
WidgetInfo insertWidget = WidgetInfoProvider.GetWidgetInfo(widgetName);

// Get PageInfo of the document
PageInfo docPageInfo = CMSWebPartPropertiesPage.GetPageInfo(staticNode.NodeAliasPath, staticNode.DocumentPageTemplateID, culture);

// Get template instance
PageTemplateInstance templateInstance = CMSPortalManager.GetTemplateInstanceForEditing(docPageInfo);

// Get page template info
PageTemplateInfo pti = templateInstance.ParentPageTemplate;

// Add widget to the page into "Editor Widget Zone" with ID = "ZoneA"
WebPartInstance newWidget = PortalHelper.AddNewWidget(insertWidget.WidgetID, zoneID, WidgetZoneTypeEnum.User, false, templateInstance);

// Set custom widget properties
newWidget.SetValue("Title", "Sample title");

// Save the changes
CMSPortalManager.SaveTemplateChanges(docPageInfo, templateInstance, WidgetZoneTypeEnum.User, ViewModeEnum.LiveSite, tree);
}

Just for an information, widgets can be stored on DB level in different tables depending how they are used.

Here is a brief summary:

Dashboard page widgets (CMSDesk, CMS Site Manager)
-- CMS_Personalization (PersonalizationDashboardName, PersonalizationWebParts)
User personalization widgets (used on LIVE site)
-- CMS_Personalization (PersonalizationDocumentID, PersonalizationWebParts)
Page editor widgets (document "Page" tab)
-- CMS_Document (DocumentWebParts)
Page editor widgets (page template "Design" tab)
-- CMS_PageTemplate (PageTemplateWebParts)
Inline widgets (used in "Editable text" web part on "Page" tab)
-- CMS_Document (DocumentContent)
Document Group widgets
-- CMS_Document (DocumentGroupWebParts)

Hope that helps.

Miro [Kentico Consulting Services]

User avatar
Member
Member
BeerWill - 3/16/2013 11:25:30 PM
   
RE:Add Widget to page programtically
Thanks Miro - that helped me a lot. I can now add my Widget to the Page (rather than the overall template) using the API.

Now just having issues accessing the content!

User avatar
Kentico Support
Kentico Support
kentico_jurajo - 3/18/2013 1:27:05 PM
   
RE:Add Widget to page programtically
Hi,

Could you please describe current issues in more details or maybe start a new separate thread on this issue?

Best regards,
Juraj Ondrus