2

I'm trying to import a CEWP on the page via REST api

I've found an example here but it does not seem to work for me. After posting the data I get a successful 200 Status call with no errors.

Response status code: 200
{  
"__metadata":{  
  "id":"https:/contoso365.sharepoint.com/sites/subsite/_api/web/getfilebyserverrelativeurl('/sites/subsite/Lists/custom/NewForm.aspx')/getlimitedwebpartmanager(1)/ImportWebPart",
  "uri":"https:/contoso365.sharepoint.com/sites/subsite/_api/web/getfilebyserverrelativeurl('/sites/subsite/Lists/custom/NewForm.aspx')/getlimitedwebpartmanager(1)/ImportWebPart",
  "type":"SP.WebParts.WebPartDefinition"
   },
    "WebPart":{  
      "__deferred":{  
         "uri":"https:/contoso365.sharepoint.com/sites/subsite/_api/web/getfilebyserverrelativeurl('/sites/subsite/Lists/custom/NewForm.aspx')/getlimitedwebpartmanager(1)/ImportWebPart/WebPart"
      }
   },
   "Id":"00000000-0000-0000-0000-000000000000"
}

The JavaScript code I'm using:

    var webPartXml = '<?xml version="1.0" encoding="utf-8"?>' +
'<WebPart xmlns="http://schemas.microsoft.com/WebPart/v2">' +
'<Assembly>Microsoft.SharePoint, Version=16.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c</Assembly>' + 
'<TypeName>Microsoft.SharePoint.WebPartPages.ContentEditorWebPart</TypeName>' + 
'<Title>$Resources:core,ContentEditorWebPartTitle;</Title>' +
'<Description>$Resources:core,ContentEditorWebPartDescription;</Description>' +
'<PartImageLarge>/_layouts/15/images/mscontl.gif</PartImageLarge>' +
'</WebPart>' ;

var zoneId = "Main";
var zoneIndex = 10;
var pageUrl = "/sites/subsite/Lists/custom/NewForm.aspx"; 

importWebPart("https://contoso365.sharepoint.com/sites/subsite", pageUrl , webPartXml, zoneId, zoneIndex);

function importWebPart(webUrl, pageUrl, webPartXml, zoneId,zoneIndex) {
    var url = webUrl + "/_api/web/getfilebyserverrelativeurl('" + pageUrl + "')/getlimitedwebpartmanager(1)/ImportWebPart";

    spr.requestDigest('https://contoso365.sharepoint.com/sites/subsite/')
    .then(function (digest) {
        return spr.post(url, {
            body: {"webPartXml": webPartXml},
            headers: {
                'X-RequestDigest': digest,
                "Accept": "application/json;odata=verbose",
            }
        });
    })
    .then(function (response) {
        if (response.statusCode === 204) {
            console.log('Web part has been imported successfully');
        }
        else{
            console.log("status code: " +response.statusCode);
            console.log("Message: " + JSON.stringify(response.body.d));
        }

    }, function (err) {
        if (err.statusCode === 404) {
            console.log('Page not found!');
        } else {
           console.log(err);
        }
    });
}

More Info:

  • The url of the web part page is 100% correct
  • Web part Zone is correct
  • I was able to perform other posts with no issues

Does anyone has a working example of the JavaScript method of adding a CEWP via REST?

  • 1
    I see you are accessing a NewForm.aspx and can imagine Microsoft considers those a a bit special. Have you tried it to a page in a Library? (the example uses a default.aspx) to rule out other issues? – Danny '365CSI' Engelman Oct 27 '16 at 7:39
3

Looks like it's impossible to add a web part to the page over REST at this moment. What a shame.

The AddWebPart_Client method of the SPLimitedWebPartManager class is the client-side equivalent of the AddWebPart method. Unfortunately, this method is decorated with a ClientCallableMethod attribute having ClientLibraryTargets=ClientLibraryTargets.NonRESTful, making this method unusable from REST calls.

– pholpar Jul 22 at 12:24

0

I know it isn't entirely what you asked for, but perhaps it might be of some benefit to the question, I have something similar in our PowerShell module for adding a web part to a page. It uses CSOM not REST, but maybe it will translate.

function Add-WebPartToView{
    <#
        .SYNOPSIS
        Adds a web part to a page
        .DESCRIPTION    
        Adds the supplied web part XML definition to a web part zone
        .PARAMETER WebUrl 
        The URL of the web to add a web part
        .PARAMETER Page 
        The server relative url of the page to add the webpart to
        .PARAMETER wpXML
        The web part XML definition
        .PARAMETER Zone 
        The web part zone to add the web part to
        .PARAMETER Index 
        The index value of the web part, determines it's positioning in the zone
        .EXAMPLE
        The following would add a content editor web part to a list view in the main web part zone with an index of zero
        $url = "https://tenant.sharepoint.com/sites/site"
        $page = "/sites/site/Documents/forms/es.aspx"
        $zone = "Main"
        $index = "0"
        $xmldef = '<?xml version="1.0" encoding="utf-8"?>
            <WebPart xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/WebPart/v2">
              <Title>Content Editor</Title>
              <FrameType>None</FrameType>
              <Description>Allows authors to enter rich text content.</Description>
              <IsIncluded>true</IsIncluded>
              <ZoneID>Main</ZoneID>
              <PartOrder>0</PartOrder>
              <FrameState>Normal</FrameState>
              <Height />
              <Width />
              <AllowRemove>true</AllowRemove>
              <AllowZoneChange>true</AllowZoneChange>
              <AllowMinimize>true</AllowMinimize>
              <AllowConnect>true</AllowConnect>
              <AllowEdit>true</AllowEdit>
              <AllowHide>true</AllowHide>
              <IsVisible>true</IsVisible>
              <DetailLink />
              <HelpLink />
              <HelpMode>Modeless</HelpMode>
              <Dir>Default</Dir>
              <PartImageSmall />
              <MissingAssembly>Cannot import this Web Part.</MissingAssembly>
              <PartImageLarge>/_layouts/15/images/mscontl.gif</PartImageLarge>
              <IsIncludedFilter />
              <Assembly>Microsoft.SharePoint, Version=16.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c</Assembly>
              <TypeName>Microsoft.SharePoint.WebPartPages.ContentEditorWebPart</TypeName>
              <ContentLink xmlns="http://schemas.microsoft.com/WebPart/v2/ContentEditor" />
              <Content xmlns="http://schemas.microsoft.com/WebPart/v2/ContentEditor"><![CDATA[?<img alt="Printable Controlled Documents" src="/sites/site/SiteAssets/image.jpg" style="margin: 5px; width: 120px;"/>]]></Content>
              <PartStorage xmlns="http://schemas.microsoft.com/WebPart/v2/ContentEditor" />
            </WebPart>'
        Add-WebPartToView -WebUrl $url -Page $page -wpXML $xmldef -Zone $zone -Index $index
    #>
    param(
        [Parameter(Mandatory=$true)][string]$WebUrl,
        [Parameter(Mandatory=$true)][string]$Page,
        [Parameter(Mandatory=$true)][string]$wpXML,
        [Parameter(Mandatory=$true)][string]$Zone,
        [Parameter(Mandatory=$true)][string]$Index
    )
    begin{
        $context = New-Object Microsoft.SharePoint.Client.ClientContext($WebUrl)
        $context.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($credential.UserName, $credential.Password)
        $web = $context.Web
        $context.Load($web)
    }
    process{
        $WPManager = $web.GetFileByServerRelativeUrl($page).GetLimitedWebPartManager("Shared")
        $wpd = $WPManager.ImportWebPart($wpXML)
        $file = $web.GetFileByServerRelativeUrl($page).GetLimitedWebPartManager("Shared").AddWebPart($wpd.WebPart, $Zone, $Index)
        $context.Load($file)
        $context.ExecuteQuery()
    }
    end{
        $context.Dispose()
    }
}

There is something similar on the PnP GitHub page, again, using CSOM. Perhaps it can be adapted for REST.

  • thank you Eric, I'll try it, but I already have a working CSOM example that adds the web part to the page. I've rewritten it to use REST, but this is where I have the problem. I'm using the same page, URLs, web part Zone, web part XML, everything seems to be the same, but it's not working for some reason. I will have to compare the CSOM and REST calls via Fiddler to see what's the difference – Denis Molodtsov Oct 27 '16 at 13:37
  • ah ok, if you have it working via CSOM, then it is either an error in translating it to REST or it is a limitation of REST. Your Fiddler traces might show that or if you try it in browser dev tools. – Eric Alexander Oct 27 '16 at 13:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.