Quantcast
Channel: Marc D Anderson's Blog » jQuery library for SharePoint Web Services
Viewing all 109 articles
Browse latest View live

Problem with jQuery 1.7+ and SPServices

$
0
0

<UPDATE dateTime=”2012-12-04″>

This issue is resolved in v0.7.0+. See this post for more details, including the SPFilterNode function. </UPDATE>

<UPDATE dateTime=”2011-11-15T11:59GMT-1″>

Steve Workman has come up with a much improved way to do the selecting for things like z:row in general – it’s much faster, as Steve’s statistics show – and it also works with jQuery 1.7. I’ve added it to the latest alpha for v1.6.3 (which I will probably rename v0.7.0). More details to come, but this issue is going to be resolved in the upcoming release of SPServices.

</UPDATE>

Alert reader Dustin Meany pinged me yesterday with a brief email through this blog:

http://bugs.jquery.com/ticket/10377 — I think you should update the documentation for SPServices…

Ah, if the issue were only as small as his email. The ticket on the jQuery site talks about the fact that the notation that I’ve been recommending to parse through the results of a call to the Web Services, like:

$(xData.responseXML).find("[nodeName='z:row']").each(function() {
  // Do something
});

is no longer valid in jQuery 1.7.

I’ve confirmed in my main test pages that jQuery 1.7 no longer matches on any z:rows in calls to GetListItems. That breaks the majority of the “value added” functions in SPServices. The [nodeName='z:row'] notation has proved highly useful to ensure cross-browser compatibility, and that was the reason I’ve been recommending it in the first place. Because GetListItems uses the somewhat odd namespace of z:row, not all browsers react the same way. Of course GetListItems is the single most used Web Service operation with SPServices. Most of the other operations, which are used less often, do not use this type of namespace.

So the question is how we as a development community handle this. Based on the suggestion in the jQuery ticket, I could implement a function in SPServices itself that probably will solve the issues for the SPServices value-added functions. There are only ten calls in SPServices at the moment that use the [nodeName='z:row'] notation. However, there are thousands of you out there who have your own custom scripts written on top of SPServices that will break if you move to jQuery 1.7+.

The suggestion of switching to the .find("z\\:row, row") notation may work. I’ve quickly tested it with IE9, Chrome 15, Safari 5.1, and Firefox 7.0, all on my Windows 7 laptop. I don’t trust my cursory test, of course; there’s more work to do.

I hold no sway over the jQuery development team. They make their decisions without any knowledge of my little SPServices library or probably even SharePoint.

This, along with the XSL timeout issue I wrote about yesterday, may prove to be a big blow to those of us who choose to develop in SharePoint’s Middle Tier. As the standard bearer for this little movement, I can only do so much to make noise about how important and useful these development techniques are. When these types of roadblocks are put up, there’s little I can do to change things.


jQuery Library for SharePoint Web Services (SPServices) v0.7.0 Beta 1 Available

$
0
0

Tonight I posted the first (we always hope the only) beta for SPServices v0.7.0. Initially I was calling this release v0.6.3, but when jQuery 1.7 was released and it caused problems with SPServices, I decided to bump the version so that the sevens matched. Get it? 1.7 and v0.7.0? Such are the complex decisions we make about software version numbering. (Those of you who wonder why I still am using sub- version 1.0 numbering – it’s just because I feel like it. No real reason.)

One of the biggest things in this new beta is compatibility with jQuery 1.7. In a previous post, I talked about the fact that the .find("[nodeName='z:row']") syntax no longer worked with jQuery 1.7. This was a real annoyance, but due to some great work by Steve Workman, I think there’s an even better selection method in v0.7.0. Unfortunately, if you’d like to move to jQuery 1.7 in your environment, you’ll have to change the syntax in all of your code as well. What the jQuery team decides to change is out of my hands, of course, so occasionally this sort of thing will happen.

There’s an new function in SPServices called SPFilterNode, which is really quite simple, but it solves the problem, based on Steve’s work.

// This method for finding specific nodes in the returned XML was developed by Steve Workman. See his blog post
// http://www.steveworkman.com/html5-2/javascript/2011/improving-javascript-xml-node-finding-performance-by-2000/
// for performance details.
$.fn.SPFilterNode = function(name) {
  return this.find('*').filter(function() {
    return this.nodeName === name;
  });
};

Here is an example of the syntax for calling this new function:

$(xData.responseXML).SPFilterNode("z:row").each(function() {

There are several benefits to having this function. First, it works in jQuery 1.7 as well as an earlier versions, going back at least to version 1.4.2, which is as far back as I tested. Second, as you can see if you read through Steve’s benchmarking results, it’s very efficient, even more efficient than the .find("[nodeName='z:row']") syntax. Third, if there is a change like this in a future version of jQuery, I can simply replace the function’s workings and all will continue to function well. Note that you only need to use SPFilterNode, and the .find("[nodeName='z:row']") syntax for that matter, when SharePoint’s Web Services return namespaced elements in the XML *and* you want to ensure cross-browser compatibility. If the nodes have names like “item” or “region”, or any other simple name which isn’t preceded with something and a colon, then .find(“item”) or .find(“region”) works fine. Of course, SPFilterNode will also work, but it’s not necessary.

If you are using SPServices and can do some regression testing, I’d certainly appreciate it, as will the other almost 8000 people who have downloaded SPServices v0.6.2 and may want to upgrade. Just be sure that you use the new SPFilterNode function if you are retrieving data from GetListItems with jQuery 1.7 or else it will seem as though you aren’t get anything back from the call.

I’ll publish the rest of the release notes when I release a stable version of v0.7.0, but if you’d like to see what’s in this version, check out the download page. As usual, it’s a mix of bug fixes, performance enhancements, and new features,.

Adding JSON Capability to SPServices

$
0
0
JSON Card -- Front

Image by superfluity via Flickr

For quite a while, I’ve gotten requests to offer some sort of JSON conversion capability in SPServices. The requests have often been fairly non-specific, meaning that they haven’t mentioned a particular Web Service operation, like GetListItems or GetWeb. However, I think that most people want to be able to get convert the XML they get back from GetListItems to JSON. This would be useful because a lot of the other jQuery plugins out there want JSON to work with.

I’ve written the beginnings of a function I will include in the next release of SPServices, and I wanted to offer it up for suggestions and requests. I want this converter function, which I’ve called SPXmlToJson, to be generally useful within an SPServices context. I don’t want to build a general-purpose converter; there are quite a few good ones out there. Generally, the data returned from SharePoint’s SOAP Web Services operations is fairly “flat”. By “flat”, I mean that there isn’t a huge amount of nesting. For example, GetListItems (which I expect to be the main context for using this function) simple passes back a z:row element for each item in the list with all of the column values as attributes.

Here’s an example:

<GetListItemsResponse xmlns="http://schemas.microsoft.com/sharepoint/soap/">
<GetListItemsResult>
    <listitems xmlns:s="uuid:BDC6E3F0-6DA3-11d1-A2A3-00AA00C14882" xmlns:dt="uuid:C2F41010-65B3-11d1-A29F-00AA00C14882" xmlns:rs="urn:schemas-microsoft-com:rowset" xmlns:z="#RowsetSchema">
      <rs:data ItemCount="22">
        <z:row ows_DocIcon="gif" ows_FileSizeDisplay="21530" ows_LinkFilename="cascaded_multiselect.GIF" ows_Title="3" ows_Modified="2011-07-05 12:17:54" ows_Editor="3;#Marc D Anderson" ows_Edit="0" ows_TestColumn="bar" ows__ModerationStatus="3" ows__Level="255" ows_ID="58" ows_owshiddenversion="5" ows_UniqueId="58;#{DF636FD7-2B27-4826-9E44-33E1F68F7EC4}" ows_FSObjType="58;#0" ows_Created_x0020_Date="58;#2011-04-13 00:35:51" ows_ProgId="58;#" ows_FileLeafRef="58;#cascaded_multiselect.GIF" ows_CheckoutUser="3;#Marc D Anderson" ows_FileRef="58;#Intranet/cascaded_multiselect.GIF" ows_MetaInfo="58;#vti_parserversion:SR|12.0.0.6421 vti_lmt:SW|Thu, 22 Oct 2009 03:42:52 GMT Order:DW|5800.00000000000 TestColumn:SW|bar vti_author:SR|SERVER\\username vti_lastwidth:IX|641 vti_winfileattribs:SW|00000000 vti_modifiedby:SR|SERVER\\username ContentTypeId:SW|0x01010077FE74FF93862D419170F4A09DD0BBC5 vti_ct:SW|Thu, 22 Oct 2009 03:42:52 GMT vti_lat:SW|Wed, 13 Apr 2011 04:34:58 GMT ContentType:SW|Document vti_title:SW|3 vti_sourcecontrolmultiuserchkoutby:VR|FSERVER\\\\username vti_lastheight:IX|286 " ows_Last_x0020_Modified="58;#2011-07-05 13:10:22"></z:row>
        <z:row ows_DocIcon="rtf" ows_FileSizeDisplay="1322" ows_LinkFilename="ChatLog.rtf" ows_Title="4" ows_Modified="2011-07-05 12:17:55" ows_Editor="3;#Marc D Anderson" ows_Edit="0" ows_TestColumn="bar" ows__ModerationStatus="3" ows__Level="255" ows_ID="59" ows_owshiddenversion="5" ows_UniqueId="59;#{7C8C1F98-E56C-4B8C-9BFB-50A4948BDC7D}" ows_FSObjType="59;#0" ows_Created_x0020_Date="59;#2011-04-13 00:35:52" ows_ProgId="59;#" ows_FileLeafRef="59;#ChatLog.rtf" ows_CheckoutUser="3;#Marc D Anderson" ows_FileRef="59;#Intranet/ChatLog.rtf" ows_MetaInfo="59;#vti_parserversion:SR|12.0.0.6421 vti_lmt:SW|Mon, 11 Apr 2011 17:09:08 GMT Order:DW|5900.00000000000 ContentTypeId:SW|0x01010077FE74FF93862D419170F4A09DD0BBC5 vti_ct:SW|Mon, 11 Apr 2011 17:09:08 GMT vti_lat:SW|Wed, 13 Apr 2011 04:34:59 GMT ContentType:SW|Document TestColumn:SW|bar vti_sourcecontrolmultiuserchkoutby:VR|SERVER\\\\username vti_title:SW|4 vti_author:SR|SERVER\\username vti_winfileattribs:SW|00000000 vti_modifiedby:SR|SERVER\\username " ows_Last_x0020_Modified="59;#2011-07-05 13:10:22"></z:row>
      </rs:data>
    </listitems>
  </GetListItemsResult>
</GetListItemsResponse>

Once you get past the enclosing “wrapper”, it’s very flat data: just a single element per item. Most of the other operations return similar structures (thought there’s precious little consistency). What I am thinking of is having the SPXmlToJson function accept a flat nodeset, which it will convert and return a JSON object. This ought to provide a very basic conversion capability that I can build on over time, as needed.

Here’s the function as it stands, and I’ve also made it available on the SPServices site in the latest alpha for v0.7.1. Please let me know what you think. Will this be enough? If not, what other options would you like to have available? What other operations are you likely to use SPXmlToJson with? Try it out and let me know your ideas.

Thanks for Paul Tavares and others for the help and nudging to get me to this point.

// This function converts a nodeset to JSON
$.fn.SPServices.SPXmlToJson = function(options) {

  var opt = $.extend({}, {
  ns: ""    // A flat XML nodeset (as from GetListItems)
  }, options);

  var json = [];

  opt.ns.each(function() {
  var row = {};
  var rowAttrs = this.attributes;
  for (var e=0; e < rowAttrs.length; e++) {
    var thisNodeName = rowAttrs[e].name;
    var trimmedNodeName = thisNodeName.indexOf("ows_") !== -1 ? thisNodeName.substring(4) : thisNodeName;
    row[trimmedNodeName] = rowAttrs[e].value;
  }
  json.push(row);
  });
  return json;
}; // End $.fn.SPServices.SPXmlToJson
Enhanced by Zemanta

Finding the Distribution of Column Types in a SharePoint List with SPServices

$
0
0

I just went through a little exercise that was simple, but fun, and I thought I’d share. As part of building my new SPXmlToJson function for SPServices, I wanted to spin through some of my lists to see what the various types of columns were and count the occurrences. Sure, I could have probably just looked in the SDK somewhere for the exhaustive list, but I though it would be a useful exercise to code something. The idea was to call GetList on a particular list, go through all of the columns in the results, and list out the number of times each column type shows up.

Since I am building a function to emit JSON, knowing what type of objects I need to create is important. Each column has a type, of course, which you select when you create the column. In the UI, the column types are things like “Single line of text”, “Choice”, or “Lookup”, as you’re probably used to seeing:

Create a List Column - Column TypesHowever, those aren’t the values that SharePoint stores in the list settings. If you work with the SharePoint Object Model with managed code, you’re used to seeing SPFieldType (yup, that link is where I could have gone to see the full list without resorting to my code).

SPFieldType in the SharePoint SDK

In the Web Services (at least GetList), we see an attribute simply named “Type” for each “Field”. Yes, fields are columns. Isn’t it grand how inconsistent some of the naming in SharePoint is?

Here’s the script I ended up with.  Since I’m focused on JSON, I wanted to play around with the various options for storing the data. I ended up with an array of typeName/typeCount values, which I could then sort in various ways. My first cut was to sort the types alphabetically and show them as simple list bullets.

$(divId).html(waitMessage).SPServices({
  operation: "GetList",
  listName: "Sales Opportunities",
  completefunc: function (xData, Status) {

    var types = [];
    $(xData.responseXML).find("Fields > Field").each(function() {

      // If we already have this type in the array, increment the count...
      var match = false;
        for(i = 0; i < types.length; i++) {
          if(types[i].typeName === $(this).attr("Type")) {
            types[i].typeCount++;
            // No need to loop further
            match = true;
          }
        }

      // ...otherwise, add it to the array with a count of 1
      if(!match) {
        var thisType = {typeName: $(this).attr("Type"), typeCount: 1};
        types.push(thisType);
      }
    });

    types.sort(function(a, b){
      var typeA = a.typeName.toLowerCase(), typeB = b.typeName.toLowerCase();
      // We want to sort the type strings, ascending
      if (typeA < typeB) return -1;
      if (typeA > typeB) return 1;
      // If they are equal, return 0 (no sorting)
      return 0;
    });

    var out = "<ul>";
    for(i=0; i < types.length; i++) {
      out += "<li>" + types[i].typeName + " = " + types[i].typeCount + "</li>";
    }
    out += "</ul>";

    $(divId).html("").append("<b>This is the output from the GetList operation:</b>" + out);
  }
});

What I ended up with is something like this:

Column Types Sorted AlphabeticallyTo see the column type sorted by number of occurrences, I simply changed the sort function to this:

types.sort(function(a, b){
  // To sort descending, subtract a from b; ascending would be the reverse
  return b.typeCount - a.typeCount;
});

This gave me output like this:

Column Types Sorted by Number of OccurencesSince I’ve found the SDK page for SPFieldType, this is throwaway code, but it’s not throwaway learning. It’s a little snippet of script that taught me a few things about formatting data for working storage on the client in script and also showed me what the internal types were for the columns which I use most often in my testing for SPServices. Note that while I’m using SPServices, and therefore jQuery, most of the heavy lifting in my script is plain old JavaScript.

SPServices v0.7.1ALPHA7 Available for Testing

$
0
0

I posted a new alpha of SPServices v0.7.1 today.logo250x150

Even though I just released v0.7.0 in early December, I’ve been working steadily to get some great new functionality and performance improvements into v0.7.1 as well as to fix some rather obscure bugs.

You can see the details of what is included in this alpha on the download page, but perhaps what will be of widest interest are some significant performance improvements to SPCascadeDropdowns and SPDisplayRelatedInfo. If you use those functions, I’d really appreciate you trying the alpha out and letting me know whether the improvements are noticeable to you. The initial setup time in the form won’t be faster, but the cascading in the page ought to be. (The better tuned your SharePoint farm and the more horsepower you have, the less improvement you are likely to see.)

I’ve also added a new function called SPXmlToJson. With it, I hope to offer a generic XML to JSON conversion utility. The first focus is on the XML returned by GetListItems, but I plan to expand upon it as people request additional capabilities. If you’re into playing with JSON, please take a look and give me your thoughts and suggestions. Be kind and remember that this is just an alpha.

JQuery
Image via Wikipedia

The main reason for getting v0.7.0 (the prior release) out there was to release a version which was compatible with jQuery 1.7.x. As goeth jQuery, so goeth SPServices; the jQuery team doesn’t sit still for long, so I can’t really, either. In fact, jQuery 1.7.1 has already been out for a while and we can see 1.8 on the horizon. As part of the new jQuery releases, there are always some significant performance improvements as well as new capabilities. As with most software, there are also capabilities which are deprecated, which may by removed in the future.

Because of all of these changes to jQuery itself, along with my accompanying changes to SPServices, I would strongly encourage you to try to keep up with the releases as best you can. I know that this can be difficult, especially in large enterprise environments where the release cycles can be complex and time consuming.

Given the constraints that many people probably have when it comes to upgrading SPServices, I’m wondering what a good release cycle would be. There have already been over 2000 downloads of v0.7.0, yet I’m getting near the time when I might want to put v0.7.1 out there. What would work best for you? Fewer releases with more changes or more releases with fewer changes? There are many considerations to this, I know. If nothing else, the documentation can only represent one point in time (I’m loathe to try to keep historical versions; maintenance would be a nightmare). If you are using an older version of SPServices, like say v0.5.8, then the docs are pretty far off for you, as will be my blog posts and articles elsewhere. Let me know what you think!

Enhanced by Zemanta

SPServices v0.7.1ALPHA8 Available for Testing

$
0
0

Yup, the alphas are coming fast and furious these days.

SPServicesI just posted a new alpha of SPServices v0.7.1. The most significant change in this alpha is the ability to have multiple child columns for a parent column in SPCascadeDropdowns. This was something I always intended it to do, but the last time I tried to work through it, probably well over a year ago, I wasn’t up to the challenge. This time I was, and I think that the function may also even be a teeny bit faster than it was in ALPHA7.

Here’s an example. In this simple list form, I’ve got a parent column called State and two child columns, one called City and the other called Second City.

By making two calls to SPCascadeDropdowns, both City and Second City are filtered based on the choice of State. I’ve also chosen to convert Second City from a “complex” dropdown to a “simple” dropdown by setting the simpleChild option to true.

$().SPServices.SPCascadeDropdowns({
  relationshipList: "Cities",
  relationshipListParentColumn: "State",
  relationshipListChildColumn: "Title",
  parentColumn: "State",
  childColumn: "City", // Child 1
  debug: true
});
$().SPServices.SPCascadeDropdowns({
  relationshipList: "Cities",
  relationshipListParentColumn: "State",
  relationshipListChildColumn: "Title",
  parentColumn: "State",
  childColumn: "Second City", // Child 2
  simpleChild: true,
  debug: true
});

Enjoy, and let me know if you have a chance to try it out.

SPServices v0.7.1ALPHA13 Available for Testing

$
0
0

Faster and more furious, that’s what I always aim for.

SPServices

I’ve been working hard on this next release of SPServices. I’ve been lucky to have some down time between projects to do it. Yes, I’m happy to have the gap so that I can do more and do it better; I’ve been able to make even more significant improvements because I’ve has the focused time. It’s a great feeling to look at my old code and know that I can do a lot better now. This version of SPServices is going to be leaner and faster than ever before. As I tweeted the other day:

Developing, documenting & maintaining open source software is a hell of a good way to become a better developer.
@sympmarc
Marc D Anderson

Alpha13, which I just posted is, I think, a good one to think of as RC1. Before I get too busy again with client work, I want to get it out there for some of you to test. If you are an SPServices user and can do some testing, especially regression testing, I’d really appreciate it.

There’s also some new stuff that I’ve built into the last few alphas:

  • Better error messages for SPCascadeDropdowns, SPDisplayRelatedInfo, and SPFilterDropdown. If you have debug mode on and the listName is incorrect, you’ll get a clearer message.
  • Improvements to the new SPXmlToJson function. All of the documented options now work as advertised and I’ve optimized the code quite a bit.
  • SPCascadeDropdowns and SPDisplayRelatedInfo now have a matchOnId option. If matchOnId is set to true, the ID of the Lookup column is used rather than the text value. This can be handy where the same text value means different things, like the place-name of Springfield, which can be found in 34 of the US States. By default the behavior of the function remains the same, of course.
  • New operations: Lists.ApplyContentTypeToList, Lists.CreateContentType, Lists.DeleteContentType, Lists.GetListItemChanges, Lists.UndoCheckOut, Lists.UpdateContentType, SiteData.GetWeb
  • Numerous (and I do mean numerous) improvements for efficiency.

Enjoy, and let me know if you have a chance to try it out.

New SPServices Page on Facebook

$
0
0

SPServicesYesterday, due to a suggestion from Stefan Bauer (@StfBauer) (though he wasn’t the first, truth be told), I created a Facebook page for SPServices. I’ll use it to post some of the same information that you see here, but obviously it’ll be more SPServices-focused.

Christian Stahl (@CStahl) pointed out that it’ll be a great place for folks to post information about how they are using SPServices in the wild, and I totally agree. Sometimes people use the discussions on the Codeplex site to do this, but I doubt that very many people see the posts. Perhaps using the ubiquitousness of Facebook will help get the word out more.

Let me know what other things you might find useful on the Facebook page, and enjoy!


jQuery Library for SharePoint Web Services (SPServices) v0.7.1 Beta 1 Available

$
0
0

Today I’ve posted the first beta for SPServices v0.7.1. While it is only a point release, it contains more significant changes than its sibling, v0.7.0, which was mainly focused on publishing a version which would work with jQuery 1.7.

If you are willing and able, I’d appreciate you testing this beta in any places where you are currently using earlier versions of SPServices so that you can help identify any regressions. I’ve made some significant changes to the core capabilities of SPServices which will make it smaller and more efficient.

Here are the full details on what is included in this release:

See all items in the Issue Tracker here.

New Functionality

Alpha Issue Tracker Item Function Operation Description
ALPHA3-6 9755 $().SPXmlToJson NA Convert XML data to JSON
ALPHA11 9751 $().SPServices.SPDisplayRelatedInfo NA SPDisplayRelatedInfo Matching on ID Instead of Text
ALPHA11 633 $().SPServices.SPCascadeDropdowns NA SPCascadeDropdowns() – Using IDs on Query to populate child column rather than values

ALPHA13 – Streamlined SPXmlToJson. This is RC1 for the new function.

New Operations

Alpha Web Service Operation Options MSDN Documentation Issue Tracker Item
ALPHA1 Lists GetVersionCollection [WebURL], strlistID, strlistItemID, strFieldName Lists.GetVersionCollection Method 8322
ALPHA2 SiteData GetSite [WebURL] SiteData.GetSite Method 9718
ALPHA2 SiteData GetSiteUrl Url SiteData.GetSiteUrl Method 9718

ALPHA12 Lists.ApplyContentTypeToList, Lists.CreateContentType, Lists.DeleteContentType, Lists.GetListItemChanges, Lists.UndoCheckOut, Lists.UpdateContentType, SiteData.GetWeb

Bug Fixes and Efficiency

Alpha Issue Tracker Item Function Description
ALPHA2 9754 $().SPServices New Internal Function: siteDataFixSOAPEnvelope
ALPHA2 9744 $().SPServices.SPComplexToSimpleDropdown Bug in SPComplexToSimpleDropdown
ALPHA5 7705 $().SPServices.SPUpdateMultipleListItems SPUpdateMultipleListItems – Add completefunc
ALPHA6 9785 $().SPServices.SPFilterDropdown Extend SPFilterDropdown with CAMLQueryOptions or RecursiveAll
ALPHA7 9793 $().SPServices.SPCascadeDropdowns SPCascadeDropdowns Performance Tweaks
ALPHA7 9794 $().SPServices.SPDisplayRelatedInfo SPDisplayRelatedInfo Performance Tweaks
ALPHA8 7876 $().SPServices.SPCascadeDropdowns SPCascadeDropdowns – 1 parent; multiple children
ALPHA9 9810 $().SPServices.SPCascadeDropdowns SPCascadeDropdowns Shouldn’t Show Null Values
ALPHA9 9811 $().SPServices.SPComplexToSimpleDropdown completefunc not called in SPComplexToSimpleDropdown
ALPHA10 9789 $().SPServices.SPComplexToSimpleDropdown SPComplexToSimpleDropdown when column is not required

jQuery Library for SharePoint Web Services (SPServices) v0.7.1 Released

$
0
0

Today I’m releasing SPServices v0.7.1. If you are using an earlier version of SPServices, I strongly suggest that you upgrade to this version. Not only does it have some cool new stuff in it, I’ve managed to squeeze some considerable performance improvments out of some of the most used functions, like SPCascadeDropdowns and SPDisplayRelatedInfo. In my test environments, I see a noticeable improvement in both functions.

While v0.7.1 is only a point release and follows its sibling v0.7.0 quickly, it actually contains far more changes.

One of the cool new things is a new function called $().SPXmlToJson. I’ve gotten quite a few requests over the years for SPServices to output JSON rather than just XML. I’ve resisted to some degree because it wasn’t entirely clear how many people might use it. As jQuery has become a more and more common part of the SharePoint development toolset, it seemed to finally make sense to add it in. Keep in mind that I can’t ask SharePoint for JSON from the SOAP Web Services; they return XML. What SPXmlToJson does is take that XML output and convert it into JSON. Of course that introduces some overhead, so use it wisely. This first implementation is firmly aimed at GetListItems, but it will also work with other “flat” XML. As folks express a need for enhancements to the function, I’ll try to work on them.

Another nice enhancement is to allow you to request that SPCascadeDropdowns and SPDisplayRelatedInfo perform their logic using the item IDs rather than the item values. The latter is more the approach that SharePoint uses in many cases, but the former is a far more robust and database-like approach.

I’ve also added in some of the missing Web Service operations that people have asked for, including Lists.ApplyContentTypeToList, Lists.CreateContentType, Lists.DeleteContentType, Lists.GetListItemChanges, Lists.UndoCheckOut, Lists.UpdateContentType, SiteData.GetWeb, SiteData.GetSite, and SiteData.GetSiteUrl.

There are numerous other performance improvements and some edge condition bugs I’ve managed to fix.

I’ll be updating the documentation over the next day or so. Keep in mind that the documentation always represents the capabilities of the current version.

Here are the details on some of what is included in this release; see all items in the Issue Tracker here.

New Functionality

Alpha Issue Tracker Item Function Operation Description
ALPHA3-6 9755 $().SPXmlToJson NA Convert XML data to JSON
ALPHA11 9751 $().SPServices.SPDisplayRelatedInfo NA SPDisplayRelatedInfo Matching on ID Instead of Text
ALPHA11 633 $().SPServices.SPCascadeDropdowns NA SPCascadeDropdowns() – Using IDs on Query to populate child column rather than values

ALPHA13 – Streamlined SPXmlToJson. This is RC1 for the new function.

New Operations

Alpha Web Service Operation Options MSDN Documentation Issue Tracker Item
ALPHA1 Lists GetVersionCollection [WebURL], strlistID, strlistItemID, strFieldName Lists.GetVersionCollection Method 8322
ALPHA2 SiteData GetSite [WebURL] SiteData.GetSite Method 9718
ALPHA2 SiteData GetSiteUrl Url SiteData.GetSiteUrl Method 9718

ALPHA12 Lists.ApplyContentTypeToList, Lists.CreateContentType, Lists.DeleteContentType, Lists.GetListItemChanges, Lists.UndoCheckOut, Lists.UpdateContentType, SiteData.GetWeb

Bug Fixes and Efficiency

Alpha Issue Tracker Item Function Description
ALPHA2 9754 $().SPServices New Internal Function: siteDataFixSOAPEnvelope
ALPHA2 9744 $().SPServices.SPComplexToSimpleDropdown Bug in SPComplexToSimpleDropdown
ALPHA5 7705 $().SPServices.SPUpdateMultipleListItems SPUpdateMultipleListItems – Add completefunc
ALPHA6 9785 $().SPServices.SPFilterDropdown Extend SPFilterDropdown with CAMLQueryOptions or RecursiveAll
ALPHA7 9793 $().SPServices.SPCascadeDropdowns SPCascadeDropdowns Performance Tweaks
ALPHA7 9794 $().SPServices.SPDisplayRelatedInfo SPDisplayRelatedInfo Performance Tweaks
ALPHA8 7876 $().SPServices.SPCascadeDropdowns SPCascadeDropdowns – 1 parent; multiple children
ALPHA9 9810 $().SPServices.SPCascadeDropdowns SPCascadeDropdowns Shouldn’t Show Null Values
ALPHA9 9811 $().SPServices.SPComplexToSimpleDropdown completefunc not called in SPComplexToSimpleDropdown
ALPHA10 9789 $().SPServices.SPComplexToSimpleDropdown SPComplexToSimpleDropdown when column is not required

SPServices Example: UserProfileService.GetUserProfileByName

$
0
0

People post working bits of code all the time on the SPServices site at Codeplex, and I don’t always do a good job of making them known to others. Usually I add good examples to the documentation pages, but I don’t always get to it. Sometimes by seeing what someone else has done, we get inklings of what we may be able to do ourselves. Of course, there’s also the willy-nilly copy-and-paste from the Interwebs approach, but I discourage using others’ code (including mine) without understanding what it does.

All that said, nileshc posted a nice little snippet the other day that I thought I’d share. SPServices has a function called SPGetCurrentUser that returns, well, information about the current user. I wrote it early on based on a trick from Einar Otto Stangvik (@einaros). It’s a good function because it works with any version or license of SharePoint (2007 and 2010), but it’s not exactly efficient or elegant. It basically loads the _layouts/userdisp.aspx page and screen scrapes the values from it. (Who knew that screen scraping would once again be cool, and even useful?)

If you’re using MOSS or SharePoint Server 2010, then you also have the User Profile Service at your disposal. nileshc‘s example takes advantage of this Web Service to grab information about the current user from the User Profile using GetUserProfileByName instead, which gives you a lot more to work with. I’ve adapted nileshc’s script slightly to make the call to SPGetCurrentUser if the logon isn’t currently known.

function get_user_profile_by_login(login) {

  var user = {};

  var params = {
    operation: 'GetUserProfileByName',
    async: false,
    completefunc: function (xData, Status) {
      $(xData.responseXML).SPFilterNode("PropertyData").each(function() {
        user[$(this).find("Name").text()] = $(this).find("Value").text();
      }); // end each

      // Easy names
      user.login = user.AccountName;
      user.full_name = user.PreferredName;
      user.email = user.WorkEmail;

    } // end completefunc
  };

  if (login != null) {
    params.accountName = login;
  } else {
    params.accountName = $().SPServices.SPGetCurrentUser({
      fieldName: "Name"
    });
  }

  $().SPServices(params);

  return user;
}

Bug in SPServices v0.7.1 with UpdateListItems Fixed in v0.7.1a

$
0
0


I’ll admit that I sometimes make mistakes. Here’s a clear one. When I made some changes to the way I initialize the default options in SPServices to help slim down the footprint, I missed testing a few things. Luckily, alert SPServices user mbroschat caught it very soon after I released v0.7.1 and I was able to get a fix in place quickly.

If you see a script error like

line 20
char 11560
‘updates.length’ is null or not an object code: 0

then you are seeing the bug. I used to initialize most of the default values for the options to empty strings (“”), but I removed that wasteful code in v0.7.1. Unfortunately I missed this one effect in my testing.

If you’ve downloaded v0.7.1, then please return to the SPServices site on Codeplex and download the replacement v0.7.1a. It contains a fix for this issue and no other changes.

Sorry for any issues.

SVG version of Bug silk.png by Avatar

Image via Wikipedia

Enhanced by Zemanta

Cool SPServices Developments Today

$
0
0

A couple of cool things happened today with SPServices that I thought I’d capture in a post.

First, I saw a couple of tweets this morning from Ryan Kirkman (@ryan_kirkman). Ryan runs a CDN for JavaScript solutions called cdnjs.

CDNJS was started in January 2011 as an attempt to speed up the web. It was hosted on Amazon until CloudFlare took over hosting using their own CDN in June 2011.

At the moment the site itself is managed by two passionate web-developers from Australia.   Feel free to get in contact with us at anytime.

@ @ Hi guys, I added jquery.SPServices to cdnjs for you: http://t.co/ivxSl2fQ (file link is here: http://t.co/5z7h1sIy)
@ryan_kirkman
Ryan Kirkman

I’ve had suggestions from quite a few people over the last six months or so to get SPServices up on cdnjs so that they could reference it there rather than host it locally. I’ve wanted to do it, but each time I look at the fact that I need to learn how to use git to do it, I’ve lost steam. I really do want to learn how to use git, and I will (Codeplex just made it available as one of the source control options), but I haven’t yet. Ryan saw me tweet about that yesterday to Simon (@binaryjam) and posted the latest version of SPServices on cdnjs for us. Hooray! (But I still need to learn git.) If you’d like to use SPServices v0.7.1a from a CDN, you can do so by referencing it at the URL:

http://cdnjs.cloudflare.com/ajax/libs/jquery.SPServices/0.7.1a/jquery.SPServices-0.7.1a.min.js

I’ll figure out how to get some of the other recent versions up there as well.

<UPDATE date=”2012-03-30″>

Josh McCarty (@joshmcrty) was kind enough to add some of the older versions of SPServices to cndjs as well. Take a look at his pull request to see the list. If you’d like any other versions, please let me know.

</UPDATE>

The second thing came from a guy named Ben Tedder (@bentedder) who has been writing a lot of great posts about SPServices on his blog.

A hand-drawn intro to jQuery SPServices http://t.co/QZgrcxVy
@bentedder
bentedder

I haven’t had the pleasure to meet Ben (his listing on Twitter puts him in Beijing, China) but I’ve appreciated his posts. Today he did something unique, at least for SPServices. Here’s his “Hand-drawn intro to jQuery and SPServices“. I think it’s pretty cool.

When to Choose SPServices vs. the Client Side Object Model (CSOM)

$
0
0

imageMark Rackley (@MrAckley) and I had a Twonversation with Jeff Jones (@SPJeff) about a month ago about when it is good to use SharePoint’s Client Side Object Model (CSOM) over SPServices. You can see the important bits of that conversation in the image to the right. (Yeah, it’s taken us forever to get this post done. I blame Mark.)

In fact, Mark and I often are asked “When should you use SPServices vs. the CSOM?” Both technologies are script-based, and both allow you to talk to SharePoint through its Web Services. However, there are some important differences to consider when you are deciding which to use,

In this post, Mark and I will try to give you some pros and cons for each. Many of these statements are subjective on purpose; it’s the way the two of us view the two technologies and shows some of the considerations we take into account as we make architectural choices for our clients.

Why You Should Be Using SPServices (says Marc)

SPServices is a jQuery library which I wrote and continue to work on, so I have to admit a strong bias. However, I think there are some clear reasons that you should use it in some cases. It’s not the only answer, but it’s a great tool you can use to solve real business problems.

SPServices exposes a wide range of SharePoint’s Web Services in either SharePoint 2007 or 2010, letting you interact with the Webs, Users and Groups, Permissions, UserProfileService, and Workflow Web Services, and more. This interaction is consistent between SharePoint 2007 and 2010, so there’s no relearning when you upgrade. (Yes, Virginia, there are still a lot of organizations out there running some flavor of SharePoint 2007.)

SPServices supports anonymous access to read and write to lists, and it works cross-site and cross-domain by simply specifying the webURL in the Web Service operations where it makes sense to do so. Of course, your authentication model has to allow cross-domain access.

The syntax in SPServices is relatively simple and pretty consistent with the way jQuery and other mainstream scripting libraries work these days. All you have to do is pass the Web Service operation you want to call, along with the required parameters in the options. No fuss, no muss. The SOAP Web Services, upon which SPServices is built, return XML and parsing XML with jQuery is old hat for most Web developers. SPServices’ reliance on the jQuery library ensures great cross-browser consistency as well. Most of the code you write using SPServices is going to work exactly the same way regardless of the browser your users have.

Finally, because I continue to develop SPServices – most frequently based on user input – it’s highly likely that I’ll make a new option or function available to meet your needs. I put out new releases of SPServices regularly (there were five releases in the last year) and aim to keep the library evolving and staying current with newer versions of jQuery. Obviously, keeping bugs to a minimum is an ever-present goal. Oh, and it’s free to use on Codeplex, under the MIT License.

Why you should be using the Client Object Model (says Mark)

Yeah.. yeah.. yeah… SPServices is groovy and all and Marc did a great job with it, but if you are using SharePoint 2010 it should NOT be your first choice when it comes to client side development. Why? I’m so glad you asked!

Unless you need anonymous access or cross site access, SPServices is actually a detriment to your SharePoint sustainability. COM is the only way to go.

Like it or not COM is the future and .asmx web services are the past. You need to learn the current technologies and let the outdated stuff go away. Main stream support for SharePoint 2007 ends in October and vNext is just over the horizon. Microsoft has some pretty smart people and I would not be surprised in the least if they addressed the anonymous access issue in SharePoint 15 as well as some of the other limitations.  So, if you don’t use COM and rely on older technologies you may very well find yourself rewriting a lot of code when you could have been ahead of the game.

Additionally COM uses RESTful Web Services and can return your data as JSON which means better performance and less data being passed over the wire. Performance is a huge issue with JavaScript and jQuery so from this standpoint alone COM is the better choice. COM is also structured much more like .NET and has a nicer “feel” to it for the average .NET developer plus it’s more developer friendly (“ows_Title” anyone?).  Lastly, COM is NOT jQuery based. It is written in ECMAScript (JavaScript to the rest of us) so there are no additional libraries or overhead needed. How’s THAT for compatibility?

I think it’s pretty black and white. SPServices is a great tool that I have used quite effectively, but if you are using SharePoint 2010, want better performance, a better development experience, and a technology that will definitely exist in vNext then you have to use the Client Object Model.

Summing it up…

And because I’m typing this, I get to say that Mark is all wrong. No, that’s absolutely NOT the case, All of Mark’s points are valid, but there isn’t a one-size-fits-all answer to everything. To help you decide which directions to take for your own organization, we’ve compiled this list of pros and cons for each option. Do you have other ideas for pros and cons? If so, please post the here in the comments or on Mark’s post on his blog.

This post also appeared on NothingButSharePoint.com‘s EndUserSharePoint channel on 2012-04-25. Visit the post there to read additional comments.

SPServices

Pros

  • A wide range of SharePoint functionality is exposed with the SOAP Web Services, much of which is not available in CSOM
  • Allows anonymous access (assuming it is enabled for the underlying objects)
  • Works cross-site and cross-domain, assuming that the authentication model you are using allows it
  • Simpler syntax than the CSOM. Simply pass the required parameters to the Web Service operation, e.g., GetListItems
  • Built on top of jQuery, which is very good at ensuring cross-browser compatibility
  • Regularly updated and refined to be compatible with new versions of jQuery and to add new functionality based on user input
  • Works identically in SharePoint 2007 and 2010 (where the same Web Services exist – see chart)

Cons

  • The SOAP Web Services which SPServices wraps is “old” technology which only returns XML
  • Because the SOAP Web Services are older technology, they may not be supported as long as CSOM

CSOM

Pros

  • Provides access to the “modern” RESTFul Web Services which return JSON or XML based upon your need
  • Coding patterns mirror .NET, which may make more sense to .NET developers

Cons

  • No anonymous access
  • No cross-site or cross-domain capabilities
  • Complicated syntax which mirrors .NET coding patterns, which may make less sense to Web developers
  • Have to create your own success and failure methods

Referencing jQuery, jQueryUI, and SPServices from CDNs

$
0
0

OK, I admit it. Now that SPServices is available on a CDN, I’m coming around to thinking that CDNs might be a good idea in some cases. I had been balking at using them primarily from a control standpoint, and I’m still concerned with that aspect. When you host the script and CSS files you are using yourself, you know exactly what you’re going to get. You control the content, the naming conventions, the storage location, the uptime, everything. With CDNs, many of those things are no longer your problem, but you give up some control. I don’t think that CDNs are perfect in every situation, but they can sure be useful.

When I was working with Dan Antion and his team last week, I needed to quickly get something up and running while they were all staring at me, expecting me to perform. (They are the nicest people, but it’s still unnerving to be on the spot to write great code on demand. It seems that I managed to pull it off.) Rather than trying to go out and download jQuery, jQueryUI, and SPServices right then, I decided to quickly toss together a txt file I could easily point to in a Content Editor Web Part (CEWP).

Here’s what I came up with. Google hosts jQuery, jQueryUI, and all of the standard jQueryUI themes, and SPServices is now on cdnjs.

<!-- Reference the jQueryUI theme's stylesheet on the Google CDN. Here we're using the "Start" theme -->
<link  type="text/css" rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/themes/start/jquery-ui.css" />

<!-- Reference jQuery on the Google CDN -->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<!-- Reference jQueryUI on the Google CDN -->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js"></script>
<!-- Reference SPServices on cdnjs (Cloudflare) -->
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery.SPServices/0.7.1a/jquery.SPServices-0.7.1a.min.js"></script>

I didn’t realize it at the time, but this txt file has become a standard part of my toolkit already. I’ve added it to three client environments just since last week. It’s the A #1 fastest way to get something up and running, even if you know you’re going to host the files locally later.

You simply add a CEWP to whatever page you want to work on, and then point the Content Link to wherever you’ve stored the txt file above. I usually use a Document Library in the root site of my Site Collection called ScriptCSS or something like that. You can, of course, just paste the contents of the txt file into your master page if your use of these tools is going to be ubiquitous.


Working with SharePoint People Pickers with jQuery: A New Function Called findPeoplePicker

$
0
0

Notice

2012-09-07 – Note that I’ve added a more robust version of this function into SPServices v0.7.2, which at this writing is in beta but will be released soon. See the docs for SPFindPeoplePicker.

I was working with several People Pickers in a form for a client project last week where I needed to set or get their values at various times in the page lifecycle. These things are pesky little compound controls, I often need to find them in the page, and I get tired of writing new script every time I want to do it. I’ve posted in the past about how to get the value with JavaScript, set the value with JavaScript, set one with jQuery, and more. It seemed high time to just write a little function to give me everything I needed in one go.

Here’s what I came up with:

Important!

UPDATE 2012-04-24 – I made a dumb mistake by using :contains() in the selector for thisRow, which occasionally returned unwanted results. I fixed it with the .filter() function below.
// Find a People Picker in the page
// Returns references to:
//   row - The TR which contains the People Picker (useful if you'd like to hide it at some point)
//   contents - The element which contains the current value
//   currentValue - The current value if it is set
//   checkNames - The Check Names image (in case you'd like to click it at some point)
$.fn.findPeoplePicker = function(options) {

  var opt = $.extend({}, {
    peoplePickerDisplayName: "",	// The displayName of the People Picker on the form
    valueToSet: "",			// The value to set the People Picker to. Should be a string containing each username or groupname separated by semi-colons.
    checkNames: true			// If set to true, the Check Names image will be clicked to resolve the names
  }, options);

  // Find the row containing the People Picker
  var thisRow = $("nobr").filter(function() {
    return $(this).text() == opt.peoplePickerDisplayName;
  }).closest("tr");
  var thisContents = thisRow.find("div[Title='People Picker']");
  var thisCheckNames = thisRow.find("img[Title='Check Names']:first");
  if(opt.valueToSet.length > 0) thisContents.html(opt.valueToSet);
  if(opt.checkNames) thisCheckNames.click();
  var thisCurrentValue = thisContents.text();

  return {row: thisRow, contents: thisContents, currentValue: thisCurrentValue, checkNames: thisCheckNames};
}

This function doesn’t just find the People Picker in the form, it also allows you to set it and, if you choose, click the Check Names image automagically. It also returns a JSON object which contains references to the important elements which make up the People Picker so that you can work with them later. Unfortunately, the only thing I can key on to find the darn things in the page is the <nobr> element which contains the DisplayName of the column. There’s just not anything else in the People Pickers which distingishes them from each other other than the standard comment, like so:

<!--  FieldName="Site Contact"
			 FieldInternalName="Site_x0020_Contact"
			 FieldType="SPFieldUser"
		   -->

Uising that comment has always seemed even less reliable to me than the DisplayName, even though I select for it in SPServices in several places. (If I’m missing something, please let me know.)

Here are a few example calls:

// Set the Site Contact to the current user
siteContactPeoplePicker = $().findPeoplePicker({
  peoplePickerDisplayName: "Site Contact",
  valueToSet: $().SPServices.SPGetCurrentUser()
});
// Find the Stakeholders People Picker in the form for later us
stakeholdersPeoplePicker = $().findPeoplePicker({
  peoplePickerDisplayName: "Stakeholders",
  checkNames: false
});

In the first call, I’m setting the Site Contact to the current user and resolving the name. In the second call, I’m getting references to the important objects for the StakeHolders People Picker so that I can set the value variably later, like so:

// Set the Stakeholders column value
stakeholdersPeoplePicker.contents.html(stakeholderNames);
stakeholdersPeoplePicker.checkNames.click();

I think some variation of this would be helpful to add to SPServices, even though it has nothing to do with the Web Services. Would you use it? What else would you want it to do?

SharePoint Saturday Boston and SharePoint Conference .ORG

$
0
0

I’ve had a wonderful time over the last four days as an attendee and speaker at two great SharePoint events.

image

The first one was SharePoint Saturday Boston, right in my own backyard at Microsoft’s offices in Waltham, MA. Helping Pradeepa Siva, Talbott Crowell (@talbott), and Geoff Varosky (@gvaro) with the organizing a bit certainly gave me a new perspective on the complexity of putting a SharePoint Saturday (or any event) together. All of the things that we as attendees take for granted (the coffee showing up at the right time, good pens for the name tags, trash bags) add up to an staggering array of details to manage.

At SharePoint Saturday Boston, I spoke about Flying in the Cloud: New Ways to Develop in SharePoint. To some degree, it’s the same sort of stuff (DVWPs, jQuery, SPServices, etc.) that I’ve been talking about for years now; moving to the Cloud simply makes it all even more useful. As you know if you attended, I didn’t use many slides (I never do), but here they are if you’d like them. See below for the demo sites.

image

Next was the SharePoint Conference .ORG in Reston, VA, put on by my friends at SusQTech. This is a wonderful conference focused on the public sector primarily, but with plenty of great content for anyone working with SharePoint. SusQTech is a somewhat unusual firm in the they combine world-class design talent with world class SharePoint development and admin talent. There aren’t that many shops that can handle things soup-to-nuts like they can. Plus, they are simply swell people to know.

On Sunday I taught an all day workshop with one of my design heroes, Kyle Schaeffer (@kylschaeffer) on SharePoint UI Essentials. If you haven’t checked out Kyle’s blog before, you definitely should, especially his work on responsive design and the v5 master page. The sold out workshop took the attendees through the gamut of thinking about SharePoint design, from the “What is HTML and CSS?” level to customizing master pages and adding jQuery into the mix to enhance the user experience. Kyle and I had a great time teaching together (let’s do it again soon, Kyle!) and the feedback was really positive.

On Monday, I did a jQuery-focused session called Working Magic with jQuery and SharePoint Web Services in which I showed how you can use jQuery to spice up the user interface and improve the interactions your users have with SharePoint. Of course, using the SOAP Web Services through SPServices and the value-added functions like SPCascadeDropdowns it contains played a role in the demos. As with most of my sessions, there were few slides, but here they are.

I used the same demo sites to talk about all of these topics to some degree, focusing on different bits and pieces within them as the topics shifted. If you’d like to look under the hood on those demos, here are the Middle Tier and Budgets sites saved as WSPs in a ZIP file. They come from Office365, and sometimes that may cause feature mismatches if you try to instantiate them in an on-premises environment. If you have issues, check my post on the problems I’ve had, along with the solutions, and ping me if that doesn’t work.

But Is jQuery Already Loaded?

$
0
0
JQuery
JQuery (Photo credit: Wikipedia)

Many end users are taking advantage of all of the goodness that jQuery provides, whether by adding simple effects like a sliding Quick Launch, more sophisticated form enhancements like SPCascadeDropdowns from SPServices, or even writing their own scripts for more complex solutions. More than ever, the distinction between “end user” and “developer” is blurring. IMO, that’s a good thing, but it also introduces complications, of course.

As one of those end users, you owe it to yourself to talk to your SharePoint team to explain what you are doing and to find out if jQuery is already loaded in the environment. In many cases, it will already be loaded in the master page or a page layout so that it is readily available across the Site Collection. The version that is loaded can also have an impact on how plugins function, making some of them effectively useless if there’s a version mismatch.

I know that in some cases, even finding the person who might know what’s loaded in the master page or what the plans may be is well nigh impossible. In those cases, here’s a trick to find out what’s up.

In a Internet Explorer browser window with the page you want to work with open, hit F12 to open the Developer Tools, and go to the Console. The screenshot below is from IE9, where there is a separate Console tab:

SNAGHTML562e339

If you’re in IE8, the Console is hidden under the Script tab, as below.

SNAGHTML5632086

If you’re in an older version of IE, well, I don’t have a screenshot for you. You may also not have the Developer Tools available, as it was a separate download with IE7 and below.

In Firefox, you’ll need the firebug add-in. If you have it, you can hit F12 to open Firebug. The Console tab is the first one on the left:

SNAGHTML56920f4

Once you’ve gotten to the Console, wherever it is, type the line I show in each of the screenshots above:

jQuery.fn.jquery

Depending on where you are, you’ll then either hit enter or click on the Run button.

Somewhere on the screen, you’ll see a display like this one, which shows that jQuery version 1.7.1 is loaded…

SNAGHTML56b32de

…or you’ll see something like…

SNAGHTML56d0846

…which tells you that jQuery isn’t loaded at all.

At that point, at least you’ll know what you are dealing with. If the version number isn’t what you need (I sometimes still see jQuery 1.3.2 loaded in a master page, which is ancient) then you’ll need to talk to your SharePoint team about updating it.

Tip ‘o the skimmer to Matt Bramer (@ionline247) for the exact syntax…

@ @ type in the console: jQuery.fn.jquery; ~ Give version num and tests whether or not it's loaded.
@iOnline247
ɹǝɯɐɹq ʍǝɥʇʇɐɯ【ツ】

…and @BinaryJam for asking the question in the first place!

something I'd love to see in getting started with jQuery articles ".Go view the source of the page, your devs may have already included it"
@BinaryJam
Binary Jam
Enhanced by Zemanta

Using SPFilterDropdown to Reorder Options in a Dropdown on a SharePoint Form

$
0
0

Many times when you have a dropdown column in your lists, you’d like to show the values sorted in a different order than alphabetically. Sure, you can use a Choice column and order the choices in any way you’d like. However, in the cases where you want the dopdown to be based on a Site Column which is a Lookup into a list, you can’t specify the sort order. I prefer using a Lookup column in almost all cases because it means that an admin (or any user with permission, really) can update the values in a list context rather than a column settings context. We also often end up storing other information about the values in the list, which we can’t do with a Choice column.

Here’s an example. I have a Site Column called Recommendation. It’s a pretty common idea: what’s our view on a particular stock or bond? We may want to recommend to our clients that the stock should be a Strong Buy, Buy, Hold, or Sell. If we add those values to a list as the source for a Lookup column, they will be ordered like this: [Buy, Hold, Sell, Strong Buy]. That’s not how we logically think of things, so it’s not great.

SPServices to the rescue! If we add a column to the source list which contains the sort order we want, we can make things look the way we need them to work. In my list below, I have a column called, logically enough, SortOrder. Note that it contains values which will sort the recommendation options the way we want.

Recommendations Datasheet View

Recommendations Datasheet View

Then, in the forms where I use the Recommendation column, I can add a call to the SPFilterDropdown function which takes care of things for me. No, the function name really doesn’t indicate that it could help with this – I built it to let you filter the options in a dropdown based on a column in the source list – but there’s a little trick you can use. If you specify a condition in your CAMLquery which always evaluates to true and specify a relationshipListSortColumn, the function will sort the values the way you want.

For my example above, I specify SortOrder as the relationshipListSortColumn, and set the CAMLQuery to give me all items where the Title does not equal an empty string. That will return all of the items, they will be sorted by SortOrder, and the dropdown will look just the way we want it to.

Recommendation Dropdown

Recommendation Dropdown

// If the Recommendation column exists, sort it as indicated in the source list
$().SPServices.SPFilterDropdown({
 relationshipWebURL: "/", // The source list for the Recommendation site Column is in the root site
 relationshipList: "Recommendations",
 relationshipListColumn: "Title",
 relationshipListSortColumn: "SortOrder",
 columnName: "Recommendation",
 CAMLQuery: "<Neq><FieldRef Name='Title' /><Value Type='Text'></Value></Neq>", // Get all values by specifying a non-blank Title
 debug: true // Debug mode on while we're developing
});

SPServices v0.7.1 Has Hit 6000 Downloads In Just Three Months

$
0
0

There have been many milestones in the SPServices saga, but this one sort of caught my eye and since I got a screen grab, I figured I’d do a quick post.. Even with over 48,000 total downloads of all of the versions I’ve released, this version seems to have really taken off, hitting 6,000 downloads in three months.

Here’s the screen grab from May 13. It’s sort of poetic that it was three months to the day when it hit 6,000, making it a clean 2,000 downloads per month so far.

image

Viewing all 109 articles
Browse latest View live