Quantcast
Channel: SharePoint 2013 - Development and Programming forum
Viewing all articles
Browse latest Browse all 7589

Filling in a PeoplePicker field/control on SP List New Form

$
0
0

For several days of combing forums on SharePoint JavaScript, I am stuck on this problem. I have made a detailed post here because I believe the functions/processes done here are done or useful to many developers and hopefully to reduce any follow-up questions.

I have two lists. The "main" list is the one the user first sees: it details data from invoices. The second list (analysts list) contains

  • the recommendations of an analyst of the invoices (call it column A)
  • analyst comments (column B)
  • associated invoice description, text concatenated from columns in the main list (column C)
  • a number which is the ID of the invoking item in the mail list (column D)
  • analyst identity doing all this (column E, data type People or Group)

Note that for the analysts list, one or more analysts can make recommendations/comments for a single item (invoice) on the main list, thus the creation of two lists. (If it was a one-to-one correspondence, I just make the above columns on the main list clearly.)

In one of the columns of the main list is a button for an invoice item, which opens a new tab which is one of two possibilities

  1. if one or more analysts have already made comments, a list view is shown filtered to show only the analysts having made entries (created items). The analysts will be allowed to edit their own items. Enhanced controls and prompts will be offered in this view (web part) to let users access the Edit and New Item forms.
  2. if no analysts have made entries on the main item, a New Item form for the Analyst List is automatically opened. In every case the New Item form is opened, columns C, D, and E are to be filled in using the script and the controls disabled to the user; the analyst only takes action on columns A and B, the only enabled controls

I have scripted in columns C and D, but am having trouble using the People Picker functions and objects to fill in the analyst's identity

I have included in this post

  • an image of the New Item form of the Analyst list
  • part of the markup of the welcome ASPX page that contains the main (invoices) list web part, namely the scripts to be loaded for this to work. I had to comment out "clienttemplates.js" as it was making the button in the main invoices list column disappear; haven't figured out why although I use JSLink (see next bullet point)
  • the relevant functions of the "invoice-tracking.js" file, which is brought in to the code through JSLink on the web part that is the main (invoices) list

The New Form actually demonstrates that I can fill in columns C ("invoice description") and D ("InvoicesMainID", present only for development purposes), and something was tried and failed in Column E.

On the script:

  1. the entry point sets up the template override to put in the button in the one column of the main list. Function ButtonField() supports that. This is all working code found in a lot of forums
  2. When the button is clicked, AnalystReview() is called and looks for existing analyst entries (by doing REST request for any items having the main list item ID). The successful Ajax request passes to processItem()
  3. processItem() calls setupNewItem() if REST response has zero results (no existing entries), or to another function (not shown) for looking at existing entries
  4. purpose of setupNewItem() is to open a new tab/window and show the New Item.aspx form for the analyst list. It is supposed to put a brake on going to the next function fillNewItem() until relevant scripts are loaded (it does not seem to, so this may need fixing)
  5. fillNewItem() is where the work is done to populate the New Item form fields (columns C, D, E). This is where the code breaks: it breaks on the line:
    SPClientPeoplePicker.SPClientPeoplePickerDict[ppDiv[0].id].AddUnresolvedUserFromEditor(true);
    -->
    Unable to get property 'AddUnresolvedUserFromEditor' of undefined or null reference
  6. in the fillNewItem(), an object SPUser is constructed. It is in library code I made in file 'InterfaceSPUser.js" that gets user properties from SP JSOM for getting user info using client context calls. I can include this if anyone thinks this is an issue.
<script type="text/javascript" src="/_layouts/15/init.js"></script><script type="text/javascript" src="/_layouts/15/MicrosoftAjax.js"></script><script type="text/javascript" src="/_layouts/15/1033/initstrings.js"></script><script type="text/javascript" src="/_layouts/15/1033/strings.js"></script><script type="text/javascript" src="/_layouts/15/SP.UI.Controls.js"></script><!--<script type="text/javascript" src="/_layouts/15/clienttemplates.js"></script>
--><script type="text/javascript" src="/_layouts/15/clientforms.js"></script><script type="text/javascript" src="/_layouts/15/clientpeoplepicker.js"></script><script type="text/javascript" src="/_layouts/15/autofill.js"></script><script type="text/javascript" src="/_layouts/15/sp.runtime.js"></script><script type="text/javascript" src="/_layouts/15/sp.init.js"></script><script type="text/javascript" src="/_layouts/15/sp.ui.dialog.js"></script><script type="text/javascript" src="/_layouts/15/sp.js"></script><script type="text/javascript" src="/_layouts/15/core.js"></script><script type="text/javascript" src="/_layouts/15/SP.Core.JS"></script><script type="text/javascript" src="/_layouts/15/sp.userprofiles.js"></script><script type="text/javascript" src="https://mdsd/SiteAssets/scripts/InterfaceSPUser.js"></script><script type="text/javascript" src="../../SiteAssets/scripts/RESTEmailService.js"></script>
(function () {
   var overrideCtx = {};
   overrideCtx.Templates = {};
   overrideCtx.Templates.Fields = {        "Analyst_x0020_Review_x0020_Decis": { "View": ButtonField}
   };
   SPClientTemplates.TemplateManager.RegisterTemplateOverrides(overrideCtx);
   window.onerror = errorHandler;
})();

function ButtonField(ctx) {
   var itemId = ctx.CurrentItem.ID;

   return "<input type='button' value='Open Analyst Log For This Item' " + "style='margin:auto;padding:0px 8px;height:23px;' onclick='AnalystReview(" + itemId + ")'/>";
}

function AnalystReview(itemId) {
  var site = "https://mdsd/sdu",
     listTitle = "Invoices - Analyst Recommendation - Comments",
     request = "/_api/web/lists/GetByTitle('" + listTitle + "')/items",
     filter = "?$filter=InvoicesMainID eq '" + itemId + "'";
     httpRequest(site + request + filter, "GET", processItem);
}

function httpRequest(urlText, methodText, successCallback) {
   $.ajax ({
     url: urlText,
     method: methodText,
     headers: {
       "Accept": "application/json;odata=verbose"
     },
     contentType: "application/json;odata=verbose",
     success: successCallback,
     error: function(reqObj, errorStatusString, optionalExceptionObject ) {
       alert( "ERROR!\n\n" +"Contact the developer with this error message below\n\n" +"Message: " + errorStatusString
       );
     }
   });
}

function processItem(responseData, returnStatusString, responseObj) {
// Note: 'this' reference is to the request object (why?)
// so all the AJAX properties are accessible
   var results, invoicesMainId;
	
   invoicesMainId = Number(this.url.match(/InvoicesMainID eq '(\d*)'/)[1]);
   if (typeof responseData == "string")
      responseData = JSON.parse(responseData);
   results = responseData.d.results; // SharePoint JSON object
   if (results.length == 0)
      setupNewItem(invoicesMainId); // show a new item form with associated id inserted
   else
      showListViewEditableItem(invoicesMainId); // show list view and offer a new item control
}

function setupNewItem (invoicesMainId) {
   var win,
   formUrl = "/sdu/Lists/Invoices%20%20Analyst%20Decisions%20%20Comments/NewForm.aspx" +"?invoicesMainId=" + invoicesMainId;
   win = window.open(formUrl, "_blank");
   if (!win || win == null || typeof win == "undefined" || win.closed)
      alert("The browser's popup blocker is enabled for this site\n\n" +"Please disable the popup blocker for this site\n" +"and reload the page");

   win.document.onreadystatechange = function () {
     if (win.document.readyState == "complete") {
        ExecuteOrDelayUntilScriptLoaded("clientpeoplepicker.js", "SPClientPeoplePicker");
        fillNewItem(win);
     }
   }
}

function fillNewItem(win) {
   var  invoicesMainId, spUser;

   invoicesMainId = win.location.search.match(/invoicesMainId=(\d*)/)[1];	
   httpRequest(
        "https://mdsd/sdu/_api/web/lists/GetByTitle('Invoices Main List')/items(" + 
	   invoicesMainId + ")?$select=Invoice_x0020_Type,Title","GET",
	function (responseData) {
	  $(win.document).contents().find("input[title^='Invoice Description']").val(
            responseData.d.Invoice_x0020_Type +" " + responseData.d.Title);
          $(win.document).contents().find("input[title^='Invoice Description']").attr("disabled", "disabled");
        }
   );
   $(win.document).contents().find("input[title^='InvoicesMainID']").val(invoicesMainId);
   $(win.document).contents().find("input[title^='InvoicesMainID']").attr("disabled", "disabled");

   spUser = new SPUser();
   spUser.setCallback(function () {
      this.setCallback(function () {
         var ppDiv, analystFieldEditor;
				
         ppDiv = $(win.document).contents().find(
             "div[id$='ClientPeoplePicker'][title='Analyst']");
         analystFieldEditor = ppDiv.find("[title='Analyst']");
         analystFieldEditor.val(spUser.lastName + ", " + spUser.firstName);
         SPClientPeoplePicker.SPClientPeoplePickerDict[ppDiv[0].id].
               AddUnresolvedUserFromEditor(true);
         $(win.document).contents().find("input[title^='Analyst']").attr("disabled", "disabled");
      });
      spUser.loadUserProperties(this.getLoginName());
   });
   spUser.loadCurrentUser();
}


Viewing all articles
Browse latest Browse all 7589

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>