Skip to content

SPLookupAddNew for SharePoint 2010

by on November 22, 2010

A better version of the $().SPServices.SPLookupAddNew for SharePoint 2010 which leverages the SP popup functionality.

There may be some unnecessary code, but I have left it for now as this does work and I don’t want to break anything.


 

// Function which provides a link on a Lookup column for the user to follow
// which allows them to add a new value to the Lookup list.
// Based on http://blog.mastykarz.nl/extending-lookup-fields-add-new-item-option/
// by Waldek Mastykarz
// altered for SharePoint 2010 by Emerson Bruce
$.fn.SPServices.SPLookupAddNew2010 = function(options) {

  var opt = $.extend({}, {
   lookupColumn: "",    // The display name of the Lookup column
   promptText: "Add new {0}",  // Text to use as prompt + column name
   completefunc: null,    // Function to call on completion of rendering the change.
   debug: false     // If true, show error messages;if false, run silent
  }, options);

  // Find the lookup column's select (dropdown)
  var lookupSelect = new dropdownCtl(opt.lookupColumn);
  if(lookupSelect.Obj.html() == null && opt.debug) { errBox("SPServices.SPLookupAddNew", "lookupColumn: " + opt.lookupColumn, "Column not found on page");return;}

  var newUrl = "";
  var lookupListUrl = "";
  var lookupColumnStaticName = "";
var lookupListID ="";
  // Use GetList for the current list to determine the details for the Lookup column
  $().SPServices({
   operation: "GetList",
   async: false,
   listName: $().SPServices.SPListNameFromUrl(),
   completefunc: function (xData, Status) {
    $(xData.responseXML).find("Field").each(function() {
     if($(this).attr("DisplayName") == opt.lookupColumn) {
      lookupColumnStaticName = $(this).attr("StaticName");
      // Use GetList for the Lookup column's list to determine the list's URL
      $().SPServices({
       operation: "GetList",
       async: false,
       listName: $(this).attr("List"),
       completefunc: function (xData, Status) {
        $(xData.responseXML).find("List").each(function() {
         lookupListUrl = $(this).attr("WebFullUrl");
         lookupListID = $(this).attr("ID"); 

         // Need to handle when list is in the root site
         lookupListUrl = lookupListUrl != SLASH ? lookupListUrl + SLASH : lookupListUrl;
        });
       }
      });
      // Get the NewItem form for the Lookup column's list
      $().SPServices({
       operation: "GetFormCollection",
       async: false,
       listName: $(this).attr("List"),
       completefunc: function (xData, Status) {
        $(xData.responseXML).find("Form").each(function() {
         if($(this).attr("Type") == "NewForm") newUrl = $(this).attr("Url");
        });
       }
      });
      // Stop looking;we're done
      return false;
     }
    });
   }
  });

  if(lookupListUrl.length == 0 && opt.debug) {
   errBox("SPServices.SPLookupAddNew",
    "lookupColumn: " + opt.lookupColumn,
    "This column does not appear to be a lookup column");
   return;
  }
  if(newUrl.length > 0) {
   // Build the link to the Lookup column's list enclosed in a div with the id="SPLookupAddNew_" + lookupColumnStaticName
newLink = "<div id='SPLookupAddNew_" + lookupColumnStaticName + "'> <a class='ms-addnew' id='idHomePageNewItem' onclick='javascript:NewItem2(event, \"" + lookupListUrl + "_layouts/listform.aspx?PageType=8&ListId=" + lookupListID + "&RootFolder=\");javascript:return false;' target='_self' href='' >" + opt.promptText.replace(/\{0\}/g, opt.lookupColumn) + "</a> </div>";

   // Append the link to the Lookup columns's formbody table cell
   $(lookupSelect.Obj).parents("td.ms-formbody").append(newLink);
  } else if(opt.debug) {
   errBox("SPServices.SPLookupAddNew",
    "lookupColumn: " + opt.lookupColumn,
    "NewForm cannot be found");
   return;
  }
  // If present, call completefunc when all else is done
  if(opt.completefunc != null) opt.completefunc();
};

Advertisements
24 Comments
  1. schaefjen permalink

    Hi Emerson,
    can you please explain what I have to do to test your functionality?
    I only have the Imtech.SharePoint.ExtendedLookupFields.wsp and I know that I can change the script TEMPLATE\CONTROLTEMPLATES\Imtech\ExtendedLookupFields.ascx, but that seems to be the wrong place…
    Many Thanks!

    • This is a variation of the SPLookupAddNew, which is part of the SPServices jQuery plugin. You can find more information here: http://spservices.codeplex.com/

      Basically, you can put the jQuery code into a web part on the form page. I use a text file for content, because the content editor likes to change my content on save, for some reason, even when I am in advanced html edit mode.

      1) Create a Library called “Javascript”
      2) Upload your version of jQuery .js file to the library (or you can link to the correct version on google)
      3) Upload SPServices .js file to the library (add the code above to the .js file, so it is available to use)
      4) Create a .txt file for the raw jQuery and SPServices script you are using to cutomize the form & upload it to the “Javascript” Library. This is where all the magic happens and you will put your customized code calling SPServices, and any other jQuery here. You must call both the jQuery .js and the SPServices .js file – in that order.
      5) Add a Content web part to the page, and type in the location of the text file for the content.
      6) Test the form

      This is a minor update to get the code to work without “losing” the user. Previously, new windows would pop up – this version works with the popup overlays in 2010. It will not work in 2007 as it does not have this functionality.

      Use the original SPServicesAddNew if you are using 2007.

      • schaefjen permalink

        Many Thanks!
        I‘m using SharePoint Foundation in a German version.
        $.fn.SPServices.SPLookupAddNew for a simple lookup column is working.
        $.fn.SPServices.SPLookupAddNew for a multi lookup column is not working: the function dropdownCtl returns null instead of “M”
        Do I need an additional else for German?
        // Multi-select: This will find the multi-select column control on English and most other languages sites where the Title looks like ‘Column Name possible values’
        } else if((this.Obj = $(“select[ID$=’SelectCandidate’][Title^='” + colName + ” ‘]”)).html() != null) {
        this.Type = “M”;
        // Multi-select: This will find the multi-select column control on a Russian site (and perhaps others) where the Title looks like ‘Выбранных значений: Column Name’
        } else if((this.Obj = $(“select[ID$=’SelectCandidate’][Title$=’: ” + colName + “‘]”)).html() != null) {
        this.Type = “M”;
        If I try to test $.fn.SPServices.SPLookupAddNew2010, I get some errors in this line:
        newLink = ” ” + opt.promptText.replace(/\{0\}/g, opt.lookupColumn) + “ “;
        Is there something missing after href?

  2. schaefjen permalink

    This line:
    newLink = "<div id='SPLookupAddNew_" + lookupColumnStaticName + "'> <a class='ms-addnew' id='idHomePageNewItem' onclick='javascript:NewItem2(event, \"" + lookupListUrl + "_layouts/listform.aspx?PageType=8&ListId=" + lookupListID + "&RootFolder=\");javascript:return false;' target='_self' href=" >" + opt.promptText.replace(/\{0\}/g, opt.lookupColumn) + "</a> </div>";

    • timen permalink

      Are you using this sollution with SP2007 or 2010? And if you’re using 2010 do you got it working with multi-select column?

  3. Looks like a typo caused by the WordPress editor, try changing the double quote after href to two single quotes (it is an empty link, just to make it a link with hover functionality).

  4. Amir Fouladvand permalink

    Hello
    i am not e developer and i am using shp2010 just as an administrator.
    is there any step-by-step guide to do this on shp2010 ?
    Regards

  5. see the reply above where the steps 1-6 are outlined. If there is a specific area you are having trouble with, please let me know – this is an addition to the spservices jquery plugin (they may have updated it for 2010 since this post so my solution may not be required).

  6. timen permalink

    Hello Emerson, the popup functionality worked great. This way its possible to add a new item to a different list without losing the already filled input fields. This was just what we needed.

    But then i got a complaint that the loopkup field, that was updated with addlookupnew, wasn’t updated anymore. And indeed it doesnt work anymore and really don’t have a clue what caused this to happen.

    Do you have a idea whats happening here?

  7. I am not sure what “addlookupnew” is – can you post the full error, or better yet, a link to a screenshot?

    • timen permalink

      Sorry for the typo I meant SPLookupAddNew2010. And the problem only occurs with a multi lookup column. When the dialog/iframe gets refreshed it doesn’t update the multi lookup column.

  8. This may not work properly with a multi-lookup column – I don’t beleive I have ever used one. I will look into it when I have some time, but let me know if you find the solution or have a tweak to the code. You could also check and see if there is a newer version of spservices available on codeplex which is compatible with 2010 – they may have reloved this issue if so.

    • timen permalink

      I’ve updated the spservices library and still no luck. It was working perfectly but somehow something changed. I’ve got you’re sollution running on 3 server and theys all stopped. I would really appreciate it if you could help met out.

  9. Did you install the service pack for sharepoint, or an update to the servers? Microsoft updates can break preexisting functionality.

    These scripts run on web services within sharepoint, so if permissions, etc change, it is possible they could all break. Check ssl’s, alternate access mappings, etc.

    You can also check to make sure scripts are allowed on the browser/machine you are using (look in Tools in IE).

    Unfortunately, there are so many places where errors could occur, I cannot guess what might cause it.

    I suspect that it is something in your setup overall which changed.

  10. also, if you overwrote the whole library, the spservices script may no longer contain splookupaddnew2010 if you did not edit the file. Try testing the splookupaddnew function and see if that works now – it may have been updated for 2010 at this point.

    All I can say is test, test, test.

  11. Deepali permalink

    Its not working with a multi lookup column in Sp2010….anyone has solution for this problem?

  12. I do not beleive this was ever capable of working with a lookup column – I think that is a different control. I know I did some testing with external content type lookups, and that did not work either.

  13. Matt permalink

    Excellent job, your fix works perfectly 🙂

  14. Chris permalink

    Emerson,

    I have the SPService Addnew function working and are having the issue where we are losing the form data so I am trying to implement your solution but I can’t work out where do we actually use/put your code?

  15. bryan permalink

    I have follwered your steps but nothing happens here is the code

    <script src='’ type=”text/javascript”>

    <script src='’ type=”text/javascript”>

    $.fn.SPServices.SPLookupAddNew2010 = function(options) {

    var opt = $.extend({}, {
    lookupColumn: “Columns (fileds)”, // The display name of the Lookup column
    promptText: “Add new {0}”, // Text to use as prompt + column name
    completefunc: null, // Function to call on completion of rendering the change.
    debug: false // If true, show error messages;if false, run silent
    }, options);

    // Find the lookup column’s select (dropdown)
    var lookupSelect = new dropdownCtl(opt.lookupColumn);
    if(lookupSelect.Obj.html() == null && opt.debug) { errBox(“SPServices.SPLookupAddNew”, “lookupColumn: ” + opt.lookupColumn, “Column not found on page”);return;}

    var newUrl = “”;
    var lookupListUrl = “”;
    var lookupColumnStaticName = “”;
    var lookupListID =””;
    // Use GetList for the current list to determine the details for the Lookup column
    $().SPServices({
    operation: “GetList”,
    async: false,
    listName: $().SPServices.SPListNameFromUrl(),
    completefunc: function (xData, Status) {
    $(xData.responseXML).find(“Field”).each(function() {
    if($(this).attr(“DisplayName”) == opt.lookupColumn) {
    lookupColumnStaticName = $(this).attr(“StaticName”);
    // Use GetList for the Lookup column’s list to determine the list’s URL
    $().SPServices({
    operation: “GetList”,
    async: false,
    listName: $(this).attr(“List”),
    completefunc: function (xData, Status) {
    $(xData.responseXML).find(“List”).each(function() {
    lookupListUrl = $(this).attr(“WebFullUrl”);
    lookupListID = $(this).attr(“ID”);

    // Need to handle when list is in the root site
    lookupListUrl = lookupListUrl != SLASH ? lookupListUrl + SLASH : lookupListUrl;
    });
    }
    });
    // Get the NewItem form for the Lookup column’s list
    $().SPServices({
    operation: “GetFormCollection”,
    async: false,
    listName: $(this).attr(“List”),
    completefunc: function (xData, Status) {
    $(xData.responseXML).find(“Form”).each(function() {
    if($(this).attr(“Type”) == “NewForm”) newUrl = $(this).attr(“Url”);
    });
    }
    });
    // Stop looking;we’re done
    return false;
    }
    });
    }
    });

    if(lookupListUrl.length == 0 && opt.debug) {
    errBox(“SPServices.SPLookupAddNew”,
    “lookupColumn: ” + opt.lookupColumn,
    “This column does not appear to be a lookup column”);
    return;
    }
    if(newUrl.length > 0) {
    // Build the link to the Lookup column’s list enclosed in a div with the id=”SPLookupAddNew_” + lookupColumnStaticName
    newLink = ” ” + opt.promptText.replace(/\{0\}/g, opt.lookupColumn) + “ “;

    // Append the link to the Lookup columns’s formbody table cell
    $(lookupSelect.Obj).parents(“td.ms-formbody”).append(newLink);
    } else if(opt.debug) {
    errBox(“SPServices.SPLookupAddNew”,
    “lookupColumn: ” + opt.lookupColumn,
    “NewForm cannot be found”);
    return;
    }
    // If present, call completefunc when all else is done

    if(opt.completefunc != null) opt.completefunc();
    };

  16. bryan permalink

    the bottom closing script tag was cut off and the extra opening script at the top isnt in my original code. I have boht jquery and spservices referecend at the top of my script. the original SPLookupAddNew runs just fine

  17. Alex permalink

    Ms. Bruce,
    Sorry to comment on such a long-past post, but I’m trying to implement your extension, and am continually receiving the error that $ is not defined in your js file. I’ve tried editing the file with $=jQuery; and $.noConflict(); but it doesn’t seem to be working. I’m new to implementing jQuery extensions to SharePoint2010 and am probably just missing something simple. Any ideas?

  18. Alex permalink

    Ms. Bruce,
    Found the problems: I had to comment out the original SPLookupAddNew, paste your code into the space, then fix a couple syntax issues–like declaring newLink as a var and properly capitalizing new DropdownCtl 🙂

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: