Wednesday, March 22, 2017

Using SharePoint list images in Jquery getListItems

If you use JQuery's getListItems function to return an image from a SharePoint list, you will typically do something like this;


$().SPServices({
     operation: "GetListItems",
      async: false,
      listName: "leadsSelfContent",
      CAMLViewFields: "<ViewFields>

           <FieldRef Name='WebOptimizedImage' />
           ...
      </ViewFields>",
      CAMLQuery: "<Query>

                               ...
                             </Query>",
      completefunc: function (xData, Status) {
         $(xData.responseXML).SPFilterNode("z:row").each(function() {
           var ListItemImage = $(this).attr("ows_WebOptimizedImage");
            ....


This is standard JQuery get list items format.  However, what happens when you want to use that value?  You cannot set an image field directly to this value as it will not work.

Since SharePoint actually returns two values for the image, one being the URL, one being the description, we only want the URL.  So we need to extract it from the result returned from JQuery by using the following:


ListItemImage = $(this).attr("ows_WebOptimized").split(",")[0];


This extracts the URL, which we can then apply to our html field:


$("#PageImage").attr({src : ListItemImage});

Effecting this field in HTML:

<img class="main-picure" src="" id="PageImage"></img>


This works.  However, if we don't have an image in the associated list from SharePoint, then the entire script fails.  Why?  Because this line will throw an error when the field being returned is undefined:


ListItemImage = $(this).attr("ows_WebOptimized").split(",")[0];

So, we first need to test to see if a result has been returned for this field before returning, and capture the undefined value, as follows:

        
           if(typeof(ListItemImage ) === 'undefined')
           {
              ListItemImage  = "Empty";
           }
           else
           {
              ListItemImage  = $(this).attr("ows_WebOptimized").split(",")[0];
           }



Finally we test for the result before setting the html field:

if(ListItemAllLeadersimageField != "Empty")
           {
                 $("#PageImage").attr({src :ListItemImage });
            }



This way, if the field is empty, our script will still run.


The code in its entirety looks like this:




$().SPServices({
     operation: "GetListItems",
      async: false,
      listName: "leadsSelfContent",
      CAMLViewFields: "<ViewFields>

           <FieldRef Name='WebOptimizedImage' />
           ...
      </ViewFields>",
      CAMLQuery: "<Query>

                               ...
                             </Query>",
      completefunc: function (xData, Status) {
         $(xData.responseXML).SPFilterNode("z:row").each(function() {
           var ListItemImage = $(this).attr("ows_WebOptimizedImage");

           if(typeof(ListItemImage ) === 'undefined')
             {
                ListItemImage  = "Empty";
             }
           else
             {
                ListItemImage  = $(this).attr("ows_WebOptimized").split(",")[0];
             }
 
           if(ListItemAllLeadersimageField != "Empty")
             {
               $("#PageImage").attr({src :ListItemImage });
              }



This code will allow you to extract an image from a SharePoint list, test for an empty result, and then extract the URL from that result if not empty to set an html field.

Friday, March 17, 2017

Using SharePoint Picture Library thumbnail and web optimized images in other lists

Introduction



The post previous to this showed how to expose the thumbnail and web optimized images hidden from most users in a SharePoint Picture Library.


You could then use these images however you wish, to provide thumbnail views, use those thumbnails on pages, use the web optimized images wherever you would have used the original larger image, etc...


What if we want to take this to the next level?  What if we want to include these images in other lists so that users can select them, and we automatically have the web optimized and thumbnail versions there as well? 


If you add an image field to a SharePoint list, end users are expected to know how to add an image to a separate list repository, copy the URL of that picture, and paste it into the correct fields:




This process is a bit tougher than simply changing text or selecting an image.  What if we could also simplify the way users update the image?


So our goals here are:


1. Simplify user image selection process.
2. Make available thumbnail and web versions.




An Example



If we have a list that is "company announcements", where, every week, an new announcement and image is added, and this information is displayed as web part on the front page of the site.  This is a very simple implementation of SharePoint functionality, but it does run into two main challenges:


1. End users find the copying and pasting of an image url into an image field a more complex and error prone task.
2. End users sometimes add huge images to SharePoint, not knowing how to optimize them.


Also, if you have a list with image fields, views on that list that expose the field can be awkward and difficult to manage.  Replacing the image fields with the thumbnail versions makes the views appear much more manageable:




If we can simplify the way users select existing images in a list, and expose web optimized and thumbnail versions of those images, we can improve the user experience and leverage the optimized images for our own purposes.


Steps:



1. Create a picture library with the thumbnail and web optimized image paths exposed. This is described in the prior post.  For our purposes, the title field needs to be populated.  The simplest way to do this is make the title field mandatory, so that users adding the picture must add a title.  Or, you can create workflow that copies the picture name to the title whenever a new item is created.  Whichever works best for you.



2. Create a lookup field in your destination list to the picture library.  Include the thumbnail image URL and Web Image URL as returned fields as follows:






3. Create three new fields in your destination list.  They are Thumbnail (type picture), Web Optimized (type picture), and 'Prior Image Thumbnail Name' (type single line of text).


4. Open SharePoint designer and create a new workflow against your destination list. Set this workflow to run automatically whenever an item is created or changed.


5. Create two workflow variables, ThumbNailURL, and WebImageURL, both type string.


6. Create a condition on your workflow to only run if an image is added to the list:





7. Populate the local workflow variables with the lookup values extracted from the source list:







8.  Extract just the URL from the lookup values as they have additional text prepended to the front using the 'Extract Substring from Index of String' action:



9.  We only want to run this workflow if the picture has been updated.  So we test to see if the 'Prior Image Thumbnail Name' has been changed to detect this condition:






10.  Now we set both of the image type path values, and we set the thumbnail name for testing against as in step 9:




11.  The entire workflow should look like this:



Save and publish this workflow.  After ensuring the image exists in the picture library, add the picture using the title lookup on your destination list.  This workflow should autopopulate both the thumbnail and web optimized image fields for your usage.

Conclusion


You can now expose those images for your own usage from the list, such as thumbnails for views, or using in web parts on other pages.

In our company announcement example, we now have a simpler way for users to select an image once they have added it to the picture library (drop down instead of copying and pasting url), and we have the two additional image types generated.  The web optimized version would be used on the company announcement web part on the home page, rather than the image uploaded by the user.  This will not only make the page more efficient, but can take care of styling issues caused by importing huge images.





Wednesday, March 15, 2017

Exposing SharePoint Picture Library Thumbnail and Web Optimized Images

Introduction



The SharePoint picture library has some built in functions that can be very handy for usage in other areas of SharePoint.  Every image that is added to the library gets two versions created that are hidden from the end user.  One is a web optimized jpg image.  The other is a thumbnail image.


SharePoint uses these images for its own purposes, the web optimized images are used in publishing sites, and the thumbnails allow the picture library to have thumbnail based views.  The picture library is a useful tool for managing and exposing pictures.  By extracting the web optimized and thumbnail paths of these images, we can then use those paths for our own purposes where we need either the thumbnail or web optimized version.


This post shows how to pull the "hidden" paths to the images through a workflow and expose them for your own use.




Create a Picture Library



If you haven't created one already, you will need to first start with a SharePoint picture library.  These are available by default on Publishing sites, and on other sites where the "Team Collaboration" list feature is used.




You may have to deactivate and then reactivate this feature to get the picture library to show up.  Use "Site settings" -> "Add an App" and search for the picture library to find the icon below.


Add the picture library to your site.



Add two new fields to the Image Library



We need to fields to hold the image paths within our picture library.  Create two new columns, plain text.  One called WebImageURL.  And one called ThumbnailImageURL.





Create a Workflow to Populate Fields



Now that we have the fields available, we can populate them using a workflow.  Create a new workflow in SharePoint bound to this picture library.


Create a new "Action" step, "Set field in current item".  Choose "ThumbnailImageURL" as the field, and select "Current Item - Thumbnail URL" as the value:




Repeat the step for the web image url, setting field to WebImageURL and value to current item, Web Image URL.  Notice that the built in fields have spaces in their names. We are copying the info in those built in workflow fields over to our own fields to expose them.


One you are done your workflow should look like this:




Set this workflow to run automatically whenever an item is created.


Now, when you add an item to this list, the additional fields you created now expose the paths to the optimized images:



These paths can now be copied and pasted anywhere within SharePoint to use the optimized versions of the images.