none
Unable to access and update individual webpart property values RRS feed

  • Question

  • The code which follows never seems to pull back any properties for a content editor webpart on my page. Nor does it then subsequently update either. I thought looking at all of the documentation that I've been able to find on updating webparts dynamically using javascript and jquery that I would be able to see something working either with reading common properties or maybe even in updating them. I have traced the execution of the code below through the IE developer tools debugger, and for some reason it doesn't seem to be able to access the individual properties. I do not think its a permissions issue either since the person I'm working with on this sharepoint 2013 project, says I'm a site owner for this page and the one above it. So far as I know I've never been able to get any closer to this working than now, and then only down to being able to retrieve the entire properties collection. After doing that nothing seems to happen and I just get an alert that no changes were made to the Content Editor web part that I want update on this page. I don't seem to be getting any script errors on the page either. 

    I would appreciate any clarification on my code.

    If there's a problem or problems with the code regarding the use of the webPartDefinition, webPart, and webPrat properties objects, properties, or methods. Web Parts are completely new to me and its been a struggle for me to get stuff to work dynamically like the documentation says it should.

    Here's the code:

    <script type="text/ecmascript">

    SP.SOD.executeFunc('sp.js', 'SP.ClientContext', function () {
        console.log("Initiating SP.ClientContext") });
    ExecuteOrDelayUntilScriptLoaded(UpdateSpecificWebPart, "sp.js");

    var webPrtTitles = new Array(5);
    var webPrtTitl = "";

    //function updateWebPartProperties(webPartDef, properties, imgPath)
    function updateWebPartProperties(webPartDef, properties)
    {
     var chngMade = false;
     var hiddnProp;
     var imgLinkProp;
     var hghtProp;
     var widthProp;
     
     try
     {
      // Properties List
      
      if(properties.isPropertyAvailable("Hidden"))
      {
       hiddnProp = properties.get_item("Hidden");
      }
      
      if(properties.isPropertyAvailable("ImageLink"))
      {
       imgLinkProp = properties.get_item("ImageLink");
      }
      
      if(properties.isPropertyAvailable("Height"))
      {
       hghtProp = properties.get_item("Height");
      }
      
      if(properties.isPropertyAvailable("Width"))
      {
       widthProp = properties.get_item("Width");
      }
      
      // generic height webpart property
      if(hghtProp)
      {
       properties.set_item("Height",300);
       
       chngMade = true;
      }
     
      // generic width webpart property
      if(widthProp)
      {
       properties.set_item("Width",200);
       
       chngMade = true;
      }
      /* 
      // generic webpart property
      if(hiddnProp)
      {
       properties.set_item("Hidden",true);
       
       chngMade = true;
      }
      /*
      // image viewer property
      if(imgLinkProp)
      {  
       properties.set_item("ImageLink",imgPath);
       
       chngMade = true;
      }
      */
      
      return chngMade;
     }
     catch(excptn)
     {
      alert("Exception: "+ excptn.name + " - " + excptn.message);
        }
        finally
     {

        }
    }

    function UpdateSpecificWebPart(webPrtTitl)

     try
     {
      //var imgPath = jq("#slctdMembrHidn").val();
      var serverRelativeUrl = _spPageContextInfo.serverRequestPath;
      var myCtx = new SP.ClientContext.get_current();
      var web = myCtx.get_web();
      var oFile = web.getFileByServerRelativeUrl(serverRelativeUrl);
      var limitedWebPartManager = oFile.getLimitedWebPartManager(SP.WebParts.PersonalizationScope.shared);
      var webPrtCnt = 0;
      var webPrtsStr = "";
      
      this.collWebPart = limitedWebPartManager.get_webParts();
      
      myCtx.load(collWebPart, 'Include(WebPart.Properties)');
      
      myCtx.executeQueryAsync(Function.createDelegate(this, function(){VerifyWebPartTitleAndUpdate(webPrtTitl);}),
       function()
       {
        alert('Failure!');
       }
      );
     }
     catch(excptn)
     {
      alert("Exception: '"+ excptn.name + "'  -  " + excptn.message);
        }
        finally
     {

        }
    }

    function VerifyWebPartTitleAndUpdate(webPrtTitl)
    {
     try
     {
      if (this.collWebPart.get_count())
      {
       for (var i = 0; i < this.collWebPart.get_count(); i++)
       {
        var webPartDef = this.collWebPart.getItemAtIndex(i);
        var webPart = webPartDef.get_webPart();
        var properties = webPart.get_properties();
        var webPartTitle = properties.get_item("Title");
          
        if(webPartTitle == webPrtTitl)
        {
         webPartDef.openWebPart();
     
         var webPrtUpdtd = updateWebPartProperties(webPartDef, properties);
         
         if(webPrtUpdtd)
         {
          webPartDef.saveWebPartChanges();
          webPartDef.closeWebPart();
          this.myCtx.load(collWebPart, 'Include(WebPart.Properties)');
          this.myCtx.executeQueryAsync(
          function()
          {
           alert("'"+webPartTitle+"' WEB-PART PROPERTIES UPDATE SUCCESSFUL!");
          },
          function()
          {
           alert("'" + webPartTitle + "' WEB-PART PROPERTIES UPDATE FAILED!"); 
          });
         }
         else
         {
          webPartDef.closeWebPart();
          alert("NO CHANGES MADE TO '" + webPrtTitl + "' WEB-PART.");
         }
        }
       }
      }
      else
      {
       alert("No web parts found.");
      }
     }
     catch(excptn)
     {
      alert("Exception: '"+ excptn.name + "'  -  " + excptn.message);
        }
        finally
     {

        }
    }

    webPrtTitles[0] = "NetOps Content Editor";
     
    webPrtTitl = webPrtTitles[0].toString();

    UpdateSpecificWebPart(webPrtTitl);


    </script>

    Thanks for the help.

    Henry

     
    Monday, March 13, 2017 6:59 PM

All replies

  • Hi Henry,

    Basic on your description. You want to load properties of a content editor web part on your page, and then change the properties of the web part using JavaScript client object model.

    To get the special property, you could call “properties.get_fieldValues()["pName"]);”. If you don’t know how many properties the  web part have, you could use IE debug tools “F12” ,through function “add watch” and input “properties.get_fieldValues()” to watch it. Then you could watch the properties as below.

    Here is the document can help you.
    https://msdn.microsoft.com/en-us/library/office/jj246541.aspx
    I have changed your source code an test it in my SharePoint environment. And it well done.
    You could copy the source code into your content edit web part and try it.

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script><script>
    SP.SOD.executeFunc('sp.js', 'SP.ClientContext', function () { 
         console.log("Initiating SP.ClientContext") });
    var webPrtTitles = new Array(5);
    var webPrtTitl = "";
    var serverRelativeUrl = _spPageContextInfo.serverRequestPath;
    var myCtx = new SP.ClientContext.get_current();
    
    function updateWebPartProperties(webPartDef, properties)
    {
      var chngMade = false;
      var hiddnProp;
      var imgLinkProp;
      var hghtProp;
      var widthProp;  
      try
      {
       // Properties List   
       alert("webPartDef.hidden:"+properties.get_fieldValues()["Hidden"]);
       alert("webPartDef.TitleIconImageUrl:"+properties.get_fieldValues()["TitleIconImageUrl"]);
       hghtProp = properties.get_fieldValues()["Height"];
       widthProp = properties.get_fieldValues()["Width"] ;
       // generic height webpart property
       if(hghtProp)
       {
        properties.set_item("Height","300");    
        chngMade = true;
       }
      
       // generic width webpart property
       if(widthProp)
       {
        properties.set_item("Width","700");
        chngMade = true;
       }   
       return chngMade;
      }
      catch(excptn) 
      {
       alert("Exception: "+ excptn.name + " - " + excptn.message);
         }
         finally 
       {
        }
    }
    function UpdateSpecificWebPart(webPrtTitl)
    { 
      try
      {
       //var imgPath = jq("#slctdMembrHidn").val();
       var web = myCtx.get_web();
       var oFile = web.getFileByServerRelativeUrl(serverRelativeUrl);
       var limitedWebPartManager = oFile.getLimitedWebPartManager(SP.WebParts.PersonalizationScope.shared);
       var webPrtCnt = 0;
       var webPrtsStr = "";
       this.collWebPart = limitedWebPartManager.get_webParts();
       myCtx.load(collWebPart, 'Include(WebPart.Properties)');
       myCtx.executeQueryAsync(Function.createDelegate(this, function(){VerifyWebPartTitleAndUpdate(webPrtTitl);}),
        function() 
        {
         alert('Failure!');
        }
      );
      }
      catch(excptn) 
      {
                    alert("Exception: '"+ excptn.name + "'  -  " + excptn.message);
      }
      finally 
      {
      }
    }
    function VerifyWebPartTitleAndUpdate(webPrtTitl) 
     {
      try
      {
       if (this.collWebPart.get_count()) 
       {
        for (var i = 0; i < this.collWebPart.get_count(); i++) 
        {
         var webPartDef = this.collWebPart.getItemAtIndex(i);
         var webPart = webPartDef.get_webPart();
         var properties = webPart.get_properties();
         var webPartTitle = properties.get_item("Title");
         alert("cur part title:"+webPartTitle);
         if(webPartTitle == webPrtTitl)
         {
          webPartDef.openWebPart();
          var webPrtUpdtd = updateWebPartProperties(webPartDef, properties);
          if(webPrtUpdtd)
          {
           webPartDef.saveWebPartChanges();
           webPartDef.closeWebPart();
           this.myCtx.load(collWebPart, 'Include(WebPart.Properties)');
           this.myCtx.executeQueryAsync(
           function() 
           {
            alert("'"+webPartTitle+"' WEB-PART PROPERTIES UPDATE SUCCESSFUL!");
           },
           function(send,args)
           {
            alert("'" + webPartTitle + "' WEB-PART PROPERTIES UPDATE FAILED!"+args.get_message()); 
           });
          }
          else
          {
           webPartDef.closeWebPart();
           alert("NO CHANGES MADE TO '" + webPrtTitl + "' WEB-PART.");
          }
         }
        }
       }
       else 
       {
        alert("No web parts found.");
       }
      }
      catch(excptn) 
      {
       alert("Exception: '"+ excptn.name + "'  -  " + excptn.message);
         }
         finally 
        {
        }
    }
    webPrtTitles[0] = "NetOps Content Editor";  
    webPrtTitl = webPrtTitles[0].toString();
    UpdateSpecificWebPart(webPrtTitl);
    </script>

    Best regards,

    Bruce Pu



    Please remember to <b>mark the replies as answers</b> if they help.<br/> If you have feedback for TechNet Subscriber Support, contact <a href="mailto:tnmff@microsoft.com"> tnmff@microsoft.com</a>.


    • Edited by Bruce_Pu Thursday, March 16, 2017 4:58 AM
    Thursday, March 16, 2017 4:57 AM
  • Bruce, I have made some significant progress on this issue too, due to rechecking and eliminating some logic from my code I am now able to access and manipulate some Image Viewer Web Part properties. Currently my goal is to automatically refresh my page, once all of the jquery stuff behind the scenes is done executing. I have a select drop-down box and when I select an entry from it that's when everything is supposed to execute. ultimately the page I'm working to complete will be like an overview page showing several different areas of information about the person selected from the drop-down. I want their name to appear above a picture of them and I want the image to be unique to the person selected. Right now I seem to be having difficulty with the dummy image I'm using being for the previous person selected and not the current person selected, so I know I have a logic problem somewhere, just not sure where yet. Here's a complete copy of my current javascript code:

    <script type="text/javascript">

    SP.SOD.executeFunc('sp.js', 'SP.ClientContext', function () { 
        console.log("Initiating SP.ClientContext") });
    ExecuteOrDelayUntilScriptLoaded(processSelectedTeamMember, "sp.js");
    ExecuteOrDelayUntilScriptLoaded(UpdateSpecificWebPart, "sp.js");

    var jq = jQuery.noConflict();

    var picPath = "";
    var filRefFnd = false;
    var host = location.hostname;
    var prtcl = location.protocol;
    var webPrtTitles = new Array(5);
    var webPrtTitl = "";
    var qryStrTmMmbr;
    var qryStrName;
    var slctdTmMmbr;
    var slctdName;


    function UpdateWebPartProperties(webPartDef, properties, imgPath)
    {
    var chngMade = false;
    var hiddnProp;
    var imgLinkProp;
    var hghtProp;
    var widthProp;

    try
    {
    // Properties List

    hiddnProp = properties.get_item("Hidden");
    imgLinkProp = properties.get_item("ImageLink");
    hghtProp = properties.get_item("Height");
    widthProp = properties.get_item("Width");

    // generic height webpart property
    if((typeof hghtProp != 'undefined') && (hghtProp != null))
    {
    properties.set_item("Height","300");

    chngMade = true;
    }

    // generic width webpart property
    if((typeof widthProp != 'undefined') && (widthProp != null))
    {
    properties.set_item("Width","200");

    chngMade = true;
    }

    // generic webpart property
    if((typeof hiddnProp != 'undefined') && (hiddnProp != null))
    {
    if(hiddnProp)
    {
    properties.set_item("Hidden",false);

    chngMade = true;
    }
    }

    // image viewer property
    if((typeof imgLinkProp != 'undefined') && (imgLinkProp != null))
    {
    properties.set_item("ImageLink",imgPath);

    chngMade = true;
    }


    return chngMade;
    }
    catch(excptn) 
    {
    alert("Exception: "+ excptn.name + " - " + excptn.message);
        }
        finally 
    {

        }
    }

    function UpdateSpecificWebPart(webPrtTitl)
    {
    try
    {
    if((typeof webPrtTitl != 'undefined') && (webPrtTitl != null))
    {
    var imgPath = jq("#slctdMembrHidn").val();
    var serverRelativeUrl = _spPageContextInfo.serverRequestPath;
    var myCtx = new SP.ClientContext.get_current();
    var web = myCtx.get_web();
    var oFile = web.getFileByServerRelativeUrl(serverRelativeUrl);
    var limitedWebPartManager = oFile.getLimitedWebPartManager(SP.WebParts.PersonalizationScope.shared);
    var webPrtCnt = 0;
    var webPrtsStr = "";

    this.collWebPart = limitedWebPartManager.get_webParts();

    myCtx.load(collWebPart, 'Include(WebPart.Properties)');

    myCtx.executeQueryAsync(Function.createDelegate(this, function(){VerifyWebPartTitleAndUpdate(myCtx, collWebPart, webPrtTitl,imgPath);}),
    function() 
    {
    alert('WEBPARTS COLLLECTION QUERY FAILURE!');
    }
    );
    }
    }
    catch(excptn) 
    {
    alert("Exception: '"+ excptn.name + "'  -  " + excptn.message);
        }
        finally 
    {

        }
    }

    function GetWebPartDefinition(collWebPart, properties, webPrtTitl)
    {
    var trgtWebPartDef;

    try
    {
    for (var i = 0; i < collWebPart.get_count(); i++) 
    {
    var webPartDef = collWebPart.getItemAtIndex(i);
    var properties = webPartDef.get_webPart().get_properties();
    var webPartTitle = properties.get_item("Title");

    if(webPartTitle == webPrtTitl)
    {
    trgtWebPartDef = webPartDef;
    return trgtWebPartDef;
    }
    }

    throw new Exception("TARGET WEB PART NOT FOUND ON PAGE!");
    }
    catch(excptn) 
    {
    alert("Exception: '"+ excptn.name + "'  -  " + excptn.message);
        }
        finally 
    {

        }
    }

    function VerifyWebPartTitleAndUpdate(myCtx, collWebPart, webPrtTitl, imgPath) 
    {
    try
    {
    if (collWebPart.get_count()) 
    {
    var webPartDef = GetWebPartDefinition(collWebPart, properties, webPrtTitl);
    var properties = webPartDef.get_webPart().get_properties();

    myCtx.load(properties);
    myCtx.executeQueryAsync(Function.createDelegate(this, function(){UpdateTargetWebPart(myCtx, webPartDef, properties, imgPath, webPrtTitl);}),
    function() 
    {
    alert('PROPERTIES QUERY FAILURE!');
    });
    }
    else 
    {
    alert("NO WEB PARTS FOUND ON PAGE!");
    }
    }
    catch(excptn) 
    {
    alert("Exception: '"+ excptn.name + "'  -  " + excptn.message);
        }
        finally 
    {

        }
    }

    function UpdateTargetWebPart(myCtx, webPartDef, properties, imgPath, webPrtTitl)
    {
    try
    {
    webPartDef.openWebPart();
    //webPartDef.moveWebPartTo("Zone 2",3);

    var webPrtUpdtd = UpdateWebPartProperties(webPartDef, properties, imgPath);

    if(webPrtUpdtd)
    {
    webPartDef.saveWebPartChanges();
    webPartDef.closeWebPart();
    myCtx.load(webPartDef);
    myCtx.executeQueryAsync(
    function() 
    {
    console.log("'"+webPrtTitl+"' WEB-PART PROPERTIES UPDATE SUCCESSFUL!");
    },
    function(sender, args)
    {
    alert("'" + webPrtTitl + "' WEB-PART PROPERTIES UPDATE FAILED!\nERROR INFO ( MESSAGE-" +args.get_message() + ", \nSTACK-" + args.get_stackTrace() + ").");
    });
    }
    else
    {
    webPartDef.closeWebPart();
    alert("NO CHANGES MADE TO '" + webPrtTitl + "' WEB-PART.");
    }
    }
    catch(excptn) 
    {
    alert("Exception: '"+ excptn.name + "'  -  " + excptn.message);
        }
        finally 
    {

        }
    }

    function getListData(myval)
    {
    try
    {
    var serverRelativeUrl=_spPageContextInfo.serverRequestPath;
    var myCntxt = new SP.ClientContext.get_current();
    var oWeb = myCntxt.get_web();
    var picLibName = "Picture Library";
    var list = oWeb.get_lists().getByTitle(picLibName);

    if(list)
    {
    var items = list.getItems(SP.CamlQuery.createAllItemsQuery());

    myCntxt.load(items);
    myCntxt.executeQueryAsync(
    Function.createDelegate(this,function(){captureCorrectPicturePath(items,myval);}),
    function(sendera,args)
    {
      console.log(args.get_message());
    }
    );
    }
    else
    {
    alert("PICTURE LIBRAYR '"+picLibName.toString()+"' NOT FOUND!");
    }
    }
    catch(excptn) 
    {
    alert("Exception: '"+ excptn.name + "'  -  " + excptn.message);
        }
        finally 
    {

        }
    }

    function captureCorrectPicturePath(items,myval) 
    {
    try
    {
    filRefFnd = false;

    for(var i = 0; i < items.get_count(); i++) 
    {
    var item = items.getItemAtIndex(i);    
    var fields = item.get_fieldValues(); 
    var title = fields.Title.toString();

    if(myval == title)
    {
    picPath = fields.FileRef.toString();
    picPath = prtcl + "//" + host + picPath;
    jq("#slctdMembrHidn").val(picPath).trigger('change');
    filRefFnd = true;

    break;
    }
    }
    }
    catch(excptn) 
    {
    alert("Exception: '"+ excptn.name + "'  -  " + excptn.message);
        }
        finally 
    {

        }
    }

    function processSelectedTeamMember(myval)
    {
        getListData(myval);
    }

    function refreshPage(slctdTmMmbr,slctdName)
    {
    var rawUrl = window.location.toString();
    var slctdTmMmbrFnd = false;
    var slctdNameFnd = false

    if(rawUrl.indexOf('?') > -1)
    {
    rawUrl = rawUrl.substring(0,rawUrl.indexOf('?'));
    //alert("rawURL=("+rawUrl+")");
    }

    if((slctdTmMmbr != 'undefined') && (slctdTmMmbr != null) && (slctdTmMmbr.length > 0))
    {
    slctdTmMmbrFnd = true;
    rawUrl = rawUrl + "?slctdTmMmbr="+slctdTmMmbr;
    }

    if((slctdName != 'undefined') && (slctdName != null) && (slctdName.length > 0))
    {
    slctdNameFnd = true;

    if(slctdTmMmbrFnd)
    {
    rawUrl = rawUrl + "&amp;slctdName="+slctdName;
    }
    else
    {
    rawUrl = rawUrl + "?slctdName="+slctdName;
    }
    }

    window.location = rawUrl;
    }

    function processQueryStringParms()
    {
    var qryVarsInfo = "";
    var qryStr = document.URL.split('?')[1];
    var qryStrVars; 
    var slctdName = "";
    var slctdTmMmbr = ""; 

    if((typeof qryStr != 'undefined') && (qryStr != null) && (qryStr.length > 2))
    {
    var qryStrVars = qryStr.split('&');

    for(indx in qryStrVars)
    {
    var qryVarStr = qryStrVars[indx];

    var myKey = "";
    var myKeyValue = "";
    var qryVar = qryVarStr.split('=');

    myKey = qryVar[0];
    myKeyValue = qryVar[1];

    if(myKey == "slctdTmMmbr")

    slctdTmMmbr = myKeyValue.toString();
    }
    else if(myKey == "slctdName")
    {
    slctdName = myKeyValue.toString();
    }
    else
    {
    alert("UNKNOWN PARAMETER FOUND IN URL!");
    }
    }
    }
    else
    {
    //alert("THE QUERY-STRING IS 'undefined', null, or TOO SHORT TO BE VALID!");
    }

    if(slctdName)
    {
    //alert("THE 'slctdName' VALUE IS ("+slctdName+").");
    jq("#tstTitle").text(slctdName);
    }
    else
    {
    console.log("THE 'slctdName' PARAMETER NOT FOUND!");
    //alert("THE 'slctdName' PARAMETER NOT FOUND!");
    }

    if(slctdTmMmbr)
    {
    //alert("THE 'slctdTmMmbr' VALUE IS ("+slctdTmMmbr+").")
    //jq("#slctdTeamMember").val(slctdTmMmbr);
    }
    else
    {
    console.log("THE 'slctdTmMmbr' PARAMETER NOT FOUND!");
    //alert("THE 'slctdTmMmbr' PARAMETER NOT FOUND!");
    }


    }

    jq(document).ready(function()
    {
        jq("#slctdTeamMember").on("change", function(event)
        {
    slctdTmMmbr = jq("#slctdTeamMember").val().toString();
            
    if(slctdTmMmbr != " ")
            {
    // format name title
    slctdName = jq("#slctdTeamMember").find('option:selected').attr("name");
    jq("#tstTitle").text(slctdName);

                processSelectedTeamMember(slctdTmMmbr);
            }
    else
    {
    slctdName = "";
    slctdTmMmbr = "";
    jq("#tstTitle").text("");
    jq("#slctdMembrHidn").val(" ").trigger('change');
    }

    jq("#slctdMembrHidn").bind('change', function(event)
    {
    webPrtTitles[0] = "NetOps Team Member Image";

    webPrtTitl = webPrtTitles[0].toString();

        UpdateSpecificWebPart(webPrtTitl);

    setTimeout(refreshPage(slctdTmMmbr,slctdName), 1000);
    });
        });

    processQueryStringParms();
    });

    </script>

    in case you're interested. The person's name part works fine, but as I said the image part always seems to be one iteration, behind, so I keep seeing the previously-selected person's image, instead of the currently-selected person's image.

    Thanks again for all the help thus far.

    Henry

    Thursday, March 16, 2017 5:40 AM