In the earlier article, we saw how to create the modern pages and add the Out of the Box WebParts programmatically. Now the real requirement would be, how to add our SPFX webparts on the modern pages. That would be the actual requirement from the customers right.
The simple steps are,
1. Get the Page
2. Get the available webparts for that page. Which is similar to the canvas ‘+’ symbol.
3. Identify the Webpart.
4. Add the webpart to appropriate section and column.
5. Save the page.
The piece of code is as follows.
using (var ctx = authMgr.GetSharePointOnlineAuthenticatedContextTenant(siteUrl, userName, password))
{
//Create a page or get the existing page
var page2 = ctx.Web.AddClientSidePage("PageWithSections.aspx", true);
// Add Section
page2.AddSection(CanvasSectionTemplate.ThreeColumn, 5);
// get the available web parts - this collection will include OOTB and custom SPFx web parts..
page2.Save();
// Get all the available webparts
var components = page2.AvailableClientSideComponents();
// add the named web part..
var webPartToAdd = components.Where(wp => wp.ComponentType == 1 && wp.Name == "MYWEBPARTNAME").FirstOrDefault();
if (webPartToAdd != null)
{
ClientSideWebPart clientWp = new ClientSideWebPart(webPartToAdd) { Order = 1 };
//Add the WebPart to the page with appropriate section
page2.AddControl(clientWp, page2.Sections[0].Columns[2]);
}
// the save method creates the page if one doesn't exist with that name in this site..
page2.Save();
}
Very simple and straight forward right.
Happy Coding,
Sathish Nadarajan.
Leave a comment