Me & My SharePoint [FrontEnd]

© Christian Stahl – All about SharePoint branding & customizations

Extending the DVWP with jQuery search, sort and pagination — May 2, 2013

Extending the DVWP with jQuery search, sort and pagination

In this post I’ll show you the quick steps how to extend the Data View Web Part (DVWP) with help of a jQuery plugin named DataTables.
The DVWP can connect to a SharePoint list and you can use it for example to display content in tabular view from a SharePoint list. Let’s say you want to create a news rollup that reads from the pages library with some special styling and condition, the DVWP is one of the options for this task. There’s a lot you can do with only XSLT, HTML and CSS but sometimes you need to add jQuery for some specific functions.

In this example I’ll show how to extend a basic DVWP news rollup with search-as-you type, sort function and pagination.

In order for jQuery DataTables to be able to function correctly, the HTML for the dataview table must be laid out in a well formed manner with the ‘thead’ and ‘tbody’ sections declared. Remember that use filters and limit number of object by server side in the DVWP especially if you’re dealing with large data sets, the datatable.js is there to serve a user friendly presentation layer.

The steps

  1. Create the DVWP
  2. Add the HTML that’s needed for the datatable plugin
  3. Add jQuery and CSS in separate files and reference this from your custom master page

jQuery
What you need for the plugin:

$(document).ready(function() {
$('#example').dataTable({
"oLanguage": {
"sInfo": "_START_ - _END_ of _TOTAL_ pages",
"sSearch": "Search:",
"sZeroRecords": "",
"sInfoEmpty": "No results..",
"sInfoFiltered": "",
"oPaginate": {
"sFirst": "<<",
"sLast": ">>",
"sNext": ">",
"sPrevious": "<"
}},
"sPaginationType": "full_numbers",
"iDisplayLength": 4,
"bLengthChange": false
});
var oTable = $('#example').dataTable();
oTable.fnSort([[0,'desc']]);
});

References
The references in your master page should looks like this:

<SharePoint:CssRegistration name="/Style Library/DVWP/Styles/MSDN.css" After="corev4.css" runat="server"/>
<script type="text/javascript" src="/Style Library/DVWP/Scripts/jquery-1.9.0.min.js"></script>
<script type="text/javascript" src="/Style Library/DVWP/Scripts/DataTables-1.9.4/media/js/jquery.dataTables.js"></script>
<script type="text/javascript" src="/Style Library/DVWP/Scripts/addOns.js"></script>

Download
Download the aspx including the DVWP, jQuery and CSS taken from this example. The news pages in this example have the path /press/nyheter/ and the page library is named Sidor. Change the name and URL in the DVWP as you prefer as well as the select query. Do also download the DataTable plugin here.

I like the DVWP, it’s easy to work with and there’s a lot of ways to extend it, however this plugin works great with REST, librarys such as SPServices or in custom code. You can even use it in a custom format (template) for Content Query Web Part as well, maybe I’ll write a post about how to do this later on.

This technique works great in SharePoint 2007, 2010 and 2013, in foundation or server, online or OnPrem.

/ Christian

How to include a DVWP into a master page in the form of a UserControl — March 29, 2013

How to include a DVWP into a master page in the form of a UserControl

If you the data view web part is one of your tools, you might come across the need to embed a DVWP into a master page. You can do that as long as you make the DVWP reusable all over the site collection if we talking about a DVWP that fetch content from a list at one of the sites in the collection. However, the downside doing that, is that the DVWP will give a lot of extra markup, HTML and XSLT in your master page. Dealing with that makes the master page be a bit harder for further development and for maintain. Optionally you can looking into use a Content Editor in the master page where you link it to a text file containing your DVWP.

However, if you have created a DVWP and just want to include a single reference line link an include file in the master page to the DVWP instead of having the DVWP direct in your master page you can do that with help of Visual Studio. It’s just to create a User Control (UC) and host the DVWP in the UC file and deploy the file to SharePoint file system. When you do that it’s just to include the UC as an include file in the master page.

In the example I’ve created a link list named TopLinkList in the root site of the site collection with one extra column named SortOrder by the type choice where I have set the value 1 up to 5. The idea behind this is to include a set of links from the list in the master page that displays in the header of the pages.

LinkList1

Let’s try this out!

  1. Create the TopLinkList list and the extra column as described above and create let’s say three Items in this list
  2. Create a DVWP and the HTML & CSS that reads and display the list items. Don’t forget to make the DVWP available to all sites in the site collection. You can download my example and use it as an starting point for your further development. See the link at the end of the post
  3. Open your developer environment where you got SharePoint and in this example Visual Studio 2010 installed
  4. Open VS 2010 and create a new project by the type ’Empty SharePoint Project’
  5. Give it the name CustomTopLinks and click OK
  6. Select Deploy as a farm solution and click Finish
  7. In the solution explorer, right click at the project and select Add and then New Item
  8. Select User Control
  9. Name it TopLinks.ascx and click the button Add
  10. Copy the code from the DVWP and paste this just below the register tags and save the page
  11. In the solution explorer, right click at the project and select Build
  12. In the solution explorer, right click at the project and select Deploy. Verify that you got no errors
  13. When this is done, open your custom master page with SharePoint Designer
  14. Add the following register tag at the top of the page:
    <%@ Register TagPrefix="CustomTopLinks" TagName="CustomTopLinks" Src="~/_controltemplates/CustomTopLinks/TopLinks.ascx" %>
    
  15. Add the control somewhere in your markup where you like it to appear in the pages:
    <CustomTopLinks:CustomTopLinks id="CustomTopLinks" runat="server"/>
    
  16. Done!

Download the DVWP taken from this example

Take a look at the following image that shows the columns you’ll need

LinkList2

</ Christian>

Comment functionality for news pages – Part II — July 18, 2012

Comment functionality for news pages – Part II

This article is the last one of two describing how to implement comment functionality into the news pages in SharePoint Server 2010. You’ll find Part I here. If you followed the examples in the Part II and have implemented the comment functionality it’s time to create one or more news rollup web part:

  • A web part that display the latest news pages and the number of related comments
  • A web part that display recently commented news pages
  • A web part that display the Display most commented news pages

First step – create a news rollup DVWP

When Lists and libraries are connected with a lookup you have the possibility to join content from both sources into a single Data View Web Part (joined sub view). This is useful if you want to create a news rollup that shows the latest news including the number of comments for each news item. In my examples I use the Page library in the root like the custom list NewsComments. You can use this in a sub site for news if you prefer.
I wanted to strip out HTML from the body text and limited body text by a number of words, so I used the strip HTML and the Count Word templates; a Codeplex project called SPXSLT created by my friend Marc D Anderson.

  • Open SPD and create a new folder direct in the root level and give it the name ’SPD-WebParts’.
  • Create a new ASPX page and give it the name RollupNews.aspx, check it out and open this with SPD.
  • Paste all the content from my file with the same name, you’ll find the download link at the end of this blog post.
  • Save the file and hit F12 for preview.
  • Check in and publish the file.
  • You can save this DVWP to the site gallery or to your disc if you want to implement the web part with the browser.

Next step – create a recently comments DVWP

This web part displays the most recent commented news pages. If the comment is created today, ‘New!’ will be displayed otherwise not.

  • Create a new ASPX page, save into the folder SPD-WebParts and give it the name LatestCommentedNews.aspx, check it out and open it up.
  • Paste all the content from my file with the same name, you’ll find the download link at the end of this blog post.
  • Save the file and hit F12 for preview. Check in and publish the file.
  • You can save this DVWP to the site gallery or to your disc if you want to implement the web part with the browser.

Next step – create a most comments DVWP

This web part display the most commented news pages. In order to group this, I have used the PageID column for the grouping. Furthermore I want to sort the web part by number of Items but of some reason I haven’t yet found the perfect way to accomplish this in XSLT, so I leave this as an open question to you readers! If you found a pure XSLT way for this I’ll update this blog post. In the meantime I’ll go for the jQuery TableSorter plugin. This plug is useful in different scenarios when you need client side sorting with all kind of data and it a works great if you need secondary ‘hidden’ sorting or for example just sorting a table without page refresh. You’ll find the file included in the download, see the link at the end of this blog post.

  • Create a new ASPX page, save it save into the folder SPD-WebParts and give it the name MostCommentedNews.aspx, check it out and open it up.
  • Paste all the content from my file with the same name, you’ll find the download link at the end of this blog post.
  • Save the file and hit F12 for preview. Check in and publish the file.
  • You can save this DVWP to the site gallery or to your disc if you want to implement the web part with the browser.

To activate the sort order, add a reference in your custom master page to the tablesorter file and add the following line of script into an external JS file or into the head section of your master page:

<script type="text/javascript">
$(document).ready(function() {
// Custom sort DVWP news sort by most comments
$('.tablesorter').tablesorter({sortList:[[0,0]] });
});
</script>

Download the files

If you got questions about this or maybe ideas for more functions or web parts related to this, pleas drop a comment.
Download my example files here

Thanks!
/ C

Comment functionality for news pages – Part I — June 30, 2012

Comment functionality for news pages – Part I

If you want to implement comment functionality into the news pages in SharePoint Server 2010, a no code solution with Data Views and portion of jQuery could be a perfect option for you. Alternative you can use the OOTB Note board web part or even use a blog site to get comment functionality but these options limits you if you need to customize such solution in comparison to data views powered with XSLT, jQuery and CSS.

My concept for this is basically to use two connected lists. In the following example I’ll use the Page library in the root site and a custom list called NewsComments. The NewsComments lists have a lookup column (PageID) that connects the ID column in the Pages library. You can do this at a news sub site as well if you prefer.
I am using a data view form web part for the comment textbox in a page layout that sends the comment text, the current page ID, the page title and the page URL to the NewsComments list. Into this Page layout that serves as a template for the news pages, I have created a DVWP that displays all comments related to the current page. Do get this relation I use a parameter with a server variable and a XSL filter that matches current page name to the column in NewsComments list that stores the page names. I do also use some jQuery to grab and populate information on the page and the list.
When you connecting lists with a lookup it gives you the possibility to join content from both lists in a Data View Web Part (joined subview), this can also be useful if you want to create a news rollup that shows the latest news including the number of comments per news item. I’ll write more about such web parts in the next blog.

First step – create the list and a page layout

  • Create a list in the root site of the site collection by the type of Custom List named NewsComments. Create following columns:

    • A column named PageID by the type Lookup. Select Pages in ’Get information from’ and select ID for ’In this column’. Set it to required and click OK.
    • A column named PageTitle by the type Single Line of Text and click OK.
    • A column named Comments by the type multiple lines of text with 5 rows, specify this as Plain text and click OK.
  • Open SPD and create a new page layout and give it the name ’NewsPages’. Don’t forget to give the file a Title. You can copy an existing page layout. Open the page and add or remove the content fields you like the page to have, you can use just Page Content and Title. Add some additional markup; give the elements class names that the jQuery functions needs. Download my example files down below and copy the markup. In my example I have created a Page layout based on the Article Page layout, if you are using a content type like the Enterprise Wiki you have to add tag prefix in the top of the page layout that match the fields you put on the page.
  • Save and publish the file in _catalogs > masterpage folder at the root site. Make sure that it’s available at the root site as a selectable page layout so you can specify this page layout when you create a new page in the root site.
  • Now use the browser and create some pages at the root site, for example name the first on to test1 and the URL will be /Pages/test1.aspx. Use your new page layout as template.

Next step – create a comment in the list

Open the NewsComments list and create a new item, type the URL name of one of the pages you have created in the tile field, for example test1.aspx. Type the filename of the page in the Title field, select the ID of this page, type the title of the page in the PageTitle column and create a comment. You’ll need to do this just to make sure the comments can be connected.

You have now created the basics and were now move the two DVWPs that will display the comments for the pages and make the comment box available. Download my example files if you get stuck, you can just copy the DVWPs and the jQuery and paste them in your page layout.

Next step – create a Data View Web Part that only display comments related to the current news page.

  • Open SPD and the page layout that you just created with SharePoint Designer. Create a DVWP (display Item Form) that get the information from the NewsComments list. Add this DVWP at the bottom of the page just below the last content field. Use no paging, show all objects and show only the column Comments.
  • Create a new parameter as in the image below. The parameter is required to match the current page’s URL name to what caught up in NewsComments list’s Title field.
  • Change the dsQueryRespoinse/Rows variable. If you have a language other than English don’t forget to change name of Pages. Locate the following line:

    <xsl:variable name="Rows" select="/dsQueryResponse/Rows/Row"/>
    

    change to:

    <xsl:variable name="Rows" select="/dsQueryResponse/Rows/Row[@Title=substring-after($ReferPageURL, 'Pages/')]"/>
    
  • Save the page and verify that only the comments appear per page according to what you entered in the NewsComments list.
  • Clean up the DVWP, och add the some markup for presentation.
  • Verify that everything works so far.

Next step – create a form web part

  • Add a DFWP (New Item Form) below the other data view, that get the information from the NewsComments list.
  • Use only following columns: PageID, PageTitle, Title and Comments

Clean the DFWP and give it some markup. As for the other DVWP, it’s important that you use the appropriate markup when jQuery and CSS makes use of class names.

Next step – create the jQuery you need for the comment box in the page layout

The purpose of the following jQuery is to get the page’s ID populated in the dropdown and to populate the Page’s title and URL into the select fields. I have also included a function that show characters left and set a limit to 140 characters.

<script type="text/javascript">
// Limit characters
function limitChars(textid, limit, infodiv){
var text = $('#'+textid).val();    
var textlength = text.length;
if(textlength > limit) {
$('#' + infodiv).html(''+limit+' limit reached');
$('#'+textid).val(text.substr(0,limit));
return false;
}
else {
$('#' + infodiv).html(''+ (limit - textlength) +' characters left');
return true;
}}
$(function(){
$(".FormFieldNewsComments > span > textarea[title='Comments']").keyup(function(){
limitChars(".FormFieldNewsComments > span > textarea[title='Comments']", 140, "LimitInfo");
})
});
	
$(document).ready(function() {
var loc = window.location.href.substr(window.location.href.lastIndexOf("/")+1); // Get the page filename
var PageTitle = $('.PageTitleDiv').html(); // Get the page title
$(".FormFieldNewsTitle > span > input[title='Title']").val(loc); // insert page filename in a CSS hidden formfield
$(".FormFieldPageTitle > span > input[title='PageTitle']").val(PageTitle);	// insert pages title in a CSS hidden formfield
var HiddenInput = $("input[title='PageID']").attr("optHid"); // Lagrar ID till attributet optHid
$("select[title='PageID']").val(_spPageContextInfo.pageItemId); // If less than 20 items i Pages bibl, lägger in ID nr som en selected i DD
$("input[title='PageID']").val(_spPageContextInfo.pageItemId);  // If 20 or more items in Pages lib
$("input[id='" + HiddenInput +"']").attr("value",(_spPageContextInfo.pageItemId)) // Set ID as selected if 20 or more items in Pages lib
});
</script>

Next step – add a few more functions

I added a few additional functions in this example which I think may be helpful and that is the ability to remove own comments and to show number of comments for the page. If you download my example files, this is already included in the DVWPs.

Show the number of comments

<xsl:if test="count($Rows) = 0">No comments yet..</xsl:if>
<xsl:if test="count($Rows) = 1"><xsl:value-of select="$dvt_RowCount" /> Comment</xsl:if>
<xsl:if test="count($Rows) &gt;= 2"><xsl:value-of select="$dvt_RowCount" /> Comments</xsl:if>

Add the following parameter to your XSL style sheet

<xsl:param name="UserID" />

Create these parameter for the rowview template

<xsl:param name="KeyField">ID</xsl:param>
<xsl:param name="KeyValue" select="ddwrt:EscapeDelims(string(@ID))"/>
<xsl:param name="Mode">view</xsl:param>

Match the author to the logged in user

<xsl:if test="@Author.title = $UserID">
<a href="javascript: {ddwrt:GenFireServerEvent(concat('__cancel;__delete={',$KeyField,'=',$KeyValue,'};__commit'))}">DELETE</a>
</xsl:if>

If you want to create a link to the comment list that only administrators should see you can use the DDWRT:IfHasRights() function with an appropriate value

<xsl:if test="ddwrt:IfHasRights(33554432)"><a href="/Lists/NewsComments/AllItems.aspx"><img src="/Style Library/Branding/Images/EditIcon.gif" alt="" /></a></xsl:if>

Next step – branding

The functions for this are now completed and it’s time to give this some visual awesomeness! Download my example files where you find CSS and an image that should get you going.

More to do

There are a lot of things to keep in mind to get this up and I hope you can take this as a base for your own solution and find inspiration. There are many ways to extend this and maybe I’ll publish this to Codeplex for the support and possibilities to further extensions. Maybe it could be an idea to integrate this function with my friend Marc D Anderson’s SPservices SocialDataServices

Download the files

Download my example files here

Part II

In the next blog I’ll show you how to create a news rollup out of this, a joined DVWP that displays the latest news and the number of related comments.

Create a Microblog for SharePoint 2010 — February 11, 2012

Create a Microblog for SharePoint 2010

This post is about how to create a Microblog with SharePoint Designer 2010 and the use of DVWPs, CSS and jQuery. A Microblog can be used for quick communication with team members in short sentences at the Intranet. This example works just like a SharePoint blog site, posts and comments are stored in separate lists that are linked by a lookup and team members can add posts and anyone can reply to posts. This Microblog is a basic no code solution and if you are looking for more advanced social features like hash tagging, direct messages, document uploading or integration of my site you should check out tools like NewsGator or Yammer among more. If you are looking for a basic comment function, maybe the OTB web part Note board could be an option. But let’s look into how you can use the DWVP for a Microblog.

Let’s try it out

  • Open the browser and create two custom lists in the root site of your Site Collection
    • Name it ListPosts
    • Name it ListComments
  • ListPosts
    • Create a column:
    • Name: Content – Multi lines of text with three lines for editing and plain text type.
    • Go to list settings, click the Created By column and change the presentation for this field to Name (with picture).
    • Add a new Item in the list with a title and a comment.
  • ListComments
    • Create two columns:
    • Name: PostsID – type Lookup. Get information from ListPosts in the ID column. Do not allow multiple values.
    • Name:  Comments – Multi lines of text with three lines for editing and plain text type.
    • Go to list settings, click the Created By column and change the presentation for this field to Name (with picture).
    • If you don’t use English language, rename the the (Title) column to Title, another way is just to set this column as optional if you prefer.
    • Add a new Item in the list with a title and a comment. Type a title, select PostID according to the ID from the ListPosts item you added and add a comment.

Create a Linked Data Source for the posts and comments lists

  • Open the root site with SPD and click at site objects in the left navigation at click Data Sources. Click at Linked Data Source in the ribbon. Give it the name MicroBlog in the General tab and click at configure Linked Source in the Source tab.
  • Select ListPosts and ListComments and add them to the right pane. If you can’t see the list you have to update SPD. Click at the next button and select Join and click at Finish and OK.
  • Open the root site with SPD and create a new folder named SPD-WebParts
  • Create a new ASPX page called MicroBlog and save it in the folder you created, open the page with SPD. IF you download my pages and will copy and paste you don’t need to do more now, but if you want to set this up by your self you can attach the page to your custom master page. Check it out, click at the Style tab in the ribbon, the button Attach and attach it as a custom master page. In the design view, click at the right arrow for the PlaceHolderMain place holder and click at create custom content.
  • Create a new ASPX page called MicroBlogForm and save it in the same folder as Microblog.aspx. Repeat the steps as you just did for the MicroBlog.aspx.

Create two ASPX pages

In the next step it’s time to create two DVWPs for MicroBlog.aspx, the first is for inserting posts and the second is for displaying current posts and their comments. If you want to build this by yourself you can just add a Display Item Form DVWP and use the Linked Sources and then insert field from the Comments as a Joined sub view. You will also have to create a New Item Form DVWP for the second page meant for inserting comments.

If I would describe all the steps from now including styling and jQuery this blog would be too long and for this reason I have prepared this so it’s just to download the pages and do some copy and paste. If you export or upload the DVWPs as web parts the CSS and the jQuery will not follow the web part. so cut the CSS from the MicroBlogForm page and paste this into an external CSS file. The same goes for the jQuery stuff in both pages, cut the scripts and paste them into the head section of your custom master or into an external JS file.

Read more about Linked data sources at the Microsoft Office SPD pages.

Insert the Dataviews into the ASPX pages

MicroBlog.txt

  • Open this page and copy the content into MicroBlog.aspx and save the page

MicroBlogForm.txt

  • Open this page and copy the content into MicroBlogForm.aspx and save the page

CSS

Copy this CSS into your custom CSS file

/* --- MicroBlog --- */
.PostBodyWrapper {width:100%;}
.PostWrapper {margin-left:5px}
.PostSeparator {border-bottom:1px #f1f1f1 solid; border-top:1px #fff solid; margin:5px 5px 5px 5px}
.PostImg {float:left; width:50px; height:50px; padding-right:10px}
.PostContentWrapper {background-color: #fff; height:50px;}
.PostEditor {font-weight:bold; color: #0072bc}
.PostContent {}
.PostLink {}
.PostComment {}
.PostCreatePost {padding:10px}
.FormFieldMicroBlogWrapper {margin-left:5px; width:100%; }
.FormFieldMicroBlog > span > textarea {
background-color: transparent; width:95%;
border:1px solid #ccc;        
overflow:hidden; overflow-y: hidden; overflow-x: hidden;   
font-size:14px; color:#999;
font-family:Arial, Helvetica, sans-serif;
padding:10px 20px 0px 10px;
margin-right:20px
}
.PostBtn {padding-right:3px; float:left}
.PostBtn Input {
width: auto;
padding: 5px 10px 5px 10px;
background: #617798;
border: 0;
font-size:13px;
color: #fff;
cursor: pointer!important;
float:right
}
.CommentWrapper {margin-left:60px; margin-right:5px; background-color: #f7f7f7; padding:10px; border-bottom:1px #fff solid}
.CommentImg {width:50px; float:left;}
.CommentContentWrapper {}
.CommentEditor {font-weight:bold; float:left}
.CommentEnd {margin-left:60px; margin-right:5px; border-top:1px #ccc solid; border-bottom:1px #fff solid; margin-bottom:20px}
.CommentContent {}
.CommentLink {}
.CommentNoComment {border-bottom:1px #fff solid; border-top:1px #fff solid; margin:0px 0px 15px 0px}
/* --- End MicroBlog --- */

Jquery

Copy this jQuery into your custom master or into a referenced JS file

$(document).ready(function() {
$(function() {
// Remove autofocus
$("textarea[title='Content']").blur();
// Set defaulttext
var defaultText = 'What are you working on?';
$("textarea[title='Content']")  
// Handle blur effect  
.val(defaultText)
.focus(function() {
if ( this.value == defaultText ) this.value = ''
})
.blur(function() {
if ( !$.trim( this.value ) ) this.value = defaultText
});});
});

Image Paths

If you not have activated the user profiles and my site, you have to change the image path in the MicroBlog file. You can create an image library in the root site and store the user images there if you want. Just name the images same as the Users ID. The path can looks like:

<img src=”/RootImages/{@Author.id}.jpg” alt=”” width=”50″ height=”50″ />

Ready to test

Finally it’s time to try this out, open your browser and to to the MicroBlog page

Behind the scenes

Some notes if you needs to change something

  • You have to reference the latest jQuery file in your custom master page
  • Save the two web parts into the web part gallery, or export them as files and you can use them at any page in the site collection, not only at the root site.
  • I have set a RowLimit variable to 5 In MicroBlog.aspx, change this as you prefer.
  • I changed the variable that Joins the list to get rid of the unwanted characters
    <xsl:variable name=”Rows” select=”../../../ListComments/Rows/Row[substring-before(@PostsID., ‘;#’) = normalize-space($dvt_ParentRow/@ID)]”/>
  • The link ‘Reply’ sends the current posts ID as a query string over to the next page (the dialogue). I have used a bit jQuery go get this ID from the URL in order to prepopulate a hidden drop down (the lookup column), and as you may know if there are 20 or more items in a list and you use lookup to this list, the select drop down will be converted to an input drop down and this needs to be solved as well.
  • In the dialog I used a SharePoint:SaveButton as I think is an easy way to close a dialog when click the save button.

The jQuery used in the MicroBlogForm that sets the Post ID into the hidden dropdown.

$(document).ready(function() {
var loc = window.location.href.substr(window.location.href.lastIndexOf("/")).replace('/MicroBlogForm.aspx?CID=', '').replace('&IsDlg=1', ''); 
var HiddenInput = $("input[title='PostsID']").attr("optHid");$("select[title='PostsID']").val(loc);	
$("input[title='PostsID']").val(loc);	
$("input[id='" + HiddenInput +"']").attr("value",(loc))
$('input[title="Title"]').val(loc); 
$(".FormFieldShow > span > textarea").focus(); 
});

More to do

If someone’s profile picture should be broken or missing, you can use jQuery to replace a broken image with an shadow image:

$(window).bind('load', function() { 
$('img.resizeme').each(function() { 
    if((typeof this.naturalWidth != "undefined" && 
        this.naturalWidth == 0 )  
        || this.readyState == 'uninitialized' ) { 
        $(this).attr('src', '/_layouts/images/O14_person_placeHolder_32.png'); 
    } 
}); 
})

Enjoy, and drop a comment if you have something to ask
/ Christian

How to customize a grouped view in the Data View web part — September 18, 2011

How to customize a grouped view in the Data View web part

How about to use a Data View Web Part (DWWP) to display a grouped view of news pages by year and month? Let’s improve the findability and give the users a simply way to browse the news pages in a news archive page. This technique could be useful for any kind of item in a list; you could for example do the same to display documents from a library or items in an announcement list.

Some things we need to do:

  • Create two calculate columns that will serve us when the items is created or published; this is an easy way to create the grouping.
  • Create a click function (expand / collapse) for the whole row, for the year and month in the group header.
  • Show number of items for each month
  • Sort the month by their actual numbers but display the month by their names

Let’s start!

  • Open and the site that containing the news pages with SharePoint Designer 2010, in the example it’s a news site based on the publishing site template in SharePoint 2010 server.
  • Add two new calculated columns to the Pages library. You can do this in SharePoint Designer or by the browser. Name the first calculated column to ArticleYear with data type Single line of text. Us the formula: =TEXT([Article Date],”YYYY”) name the next calculated column ArticleMonth with data type Single line of text. Us the formula: =TEXT([Article Date],”MM”). In this example I use a column called Article Date and I use this column in the actual page layout for the news pages. Be sure to include this column in your page layout and set dates to the news pages in the library. If you don’t want to use this column you can use the inbuilt column Created instead. If you’re using another language on the site than english, you may have to written the formulas a bit different, for example if you use the Swedish language you have to use ; instead of a comma character.
  • Create a new aspx page with SharePoint Designer and open this page, save this somewhere in the site. Place the cursor inside the form tag and click Insert in the ribbon. Click at Display Item Form button and select Pages.
  • Before you’ll get into the code view, do the settings for the DVWP you’ll need with help of the ribbon buttons. Set the paging, filter, sort and grouping like this:
    • Paging eq display All Items
    • Add / Remove columns. Display this columns: Title, Article date, ArticleYear and ArticleMonth
    • Filter eq article date Not Null
    • Sort order eq Article Date desc
    • Group ArticleYear by asc, show group header and make it collapse
    • Group ArticleMonth by asc, show group header and make it collapse

At this point you’ll have the basic stuff needed to get going with the UI customizations. Now you it’s your turn to do the branding and start work on functionality. If you want to see my specific example, you can download the aspx page, the CSS and the image (see the bottom of this blog post) where you’ll see the HTML structure, how to set onclick at rows, how you todisplay month names how to count a nodeset to display numer of news items per each month. In this page you’ll also how you can display month names. When you done, you can save the web part as to a file and upload this to the news site and put in a news archive page.

A quick view of things you can do more

Display month names

<xsl:choose>
 <xsl:when test="$fieldvalue='01'">January</xsl:when>
 ---
 <xsl:when test="$fieldvalue='12'">December</xsl:when>
 <xsl:otherwise></xsl:otherwise>
</xsl:choose>

Get number of items (news) per each month:

<xsl:value-of select="count($nodeset)"/>

Onclick event for the rows

<tr class="YearRow" id="group{$groupid}" style="display:{$displaystyle}" onclick="javascript:ExpGroupBy(this);return false;">

If you consider to use divs instead of tables, keep in mind that the ExpGroupBy function that lives in the Core.js needs to be overridden to match you structure.

If you like to have this grouped DVWP connected to a a list instead of a Page library, no problems! The only thing that will be different is the link to the actual item, try rewrite the link like this:

<a href="{@FileDirRef}/DispForm.aspx?ID={@ID}"><xsl:value-of select="@Title" /></a>

One thing more, if you want to use this as an archive for news pages and don’t want to display the current year you can change the Rows varible to this:

<xsl:variable name="Rows" select="/dsQueryResponse/Rows/Row[not(contains(@ArticleStartDate,substring(ddwrt:TodayIso(),1,4)))]"/>

Download the files here

/ Christian

Display random Items with the Data View Web Part — February 14, 2011

Display random Items with the Data View Web Part

This article describes how to create a Data View Web Part in SharePoint 2010 that displays a list item randomly with auto refresh. It will also cover up how to make the DVWP reusable over the site collection. This web part could be used as a Quote of the day, Tip of the day or randolmly display pictures from a libray.

In order to try this you will create a list with some items, a page, and a DVWP that you are going to modify a bit. You can also download this web part as it is.

Create the list, a column and some quotes

  • Use the browser and create a Custom List named Quote in the root site of the site collection.
  • Click at List Settings and the Title column. Rename this to Author and click OK.
  • Click at Create Column and type the name Quote. Click OK.
  • Go to the list and add at least four items in the list.

Create a page and the Data Form Web Part

  1. Open SharePoint Designer 2010 and open the root site (home). Click at the File tab, add Item, more pages. Select ASPX and click at the create button. Type QuoteWebPart and click OK twice.
  2. Select the Design View and select the Insert tab in the ribbon. Click at Display Item Form. Select the Quote list.
  3. In the option tab:

    1. Select Paging and then select Display All Items.
    2. Select Refresh Interval and set this to 15 Seconds.
    3. Select Add/Remove Columns. Remove the unwanted columns and add Quote and Author. Click OK.
    4. Select the Quote and the Author cells. In the Table tab in the ribbon, select Delete and Delete Cells.
  4. Use the code view
    1. Move the @Title after the @Quote. Remove the empty TR and use a DIV to wrap the quote and the title field like the images below. Later on you can replace all the table tags in the data view with markup as you prefer.

      Before

      After
    2. Add a a random variable and replace the for-each that render the rows with a random variable and a for-each that select this variable. Search for $Rows.
      Replace:

      <xsl:for-each select="$Rows">
      

      with

      <xsl:for-each select="$Rows[position()=$Random]">
      <xsl:call-template name="dvt_1.rowview" />
      

      The body template should look like this:

      <xsl:template name="dvt_1.body">
      <xsl:param name="Rows"/>
      <xsl:variable name="Random" select="ddwrt:Random(1,count($Rows))" /> 
      <xsl:for-each select="$Rows[position()=$Random]">
      <xsl:call-template name="dvt_1.rowview" />
      </xsl:for-each>
      </xsl:template>
      

Save the page and click at the preview browser button on top of the ribbon to make sure everything works ok. In the following section we will make this web part ready for production.

Apply branding to the Web Part and delete parameters that we don’t need

  1. Put the CSS inline just below the <XSL> tag. To put the CSS classes inline is just for make this example a bit more easy. I would recommend you to put this three classes in a custom CSS.
  2. <style type="text/css">
    #quote { 
    font-family: Arial, Helvetica, sans-serif; font-size: 13px; 
    line-height: 18px; color: #373737; 
    background-color:#fbffec;
    background:url("/Style Library/MiscStyles/quote-mark.png");
    background-position:6px 6px;
    background-repeat:no-repeat ;
    height:80px;
    padding-left: 65px; 
    padding-top:10px;
    border: 1px solid #edffaf;
    }
    #quoteText {
    text-align: left; 
    font-family: Georgia, Times, serif;
    width: 300px; 
    margin-bottom:10px;
    }
    #quoteAuthor {
    padding-left:10px;
    font-style: normal; text-align: left; 
    text-transform: uppercase; font-size: 10px; font-weight: bold; 
    letter-spacing: 1px; font-family: Arial, Helvetica, sans-serif; 	
    }
    </style>
    
  3. Create a Quote image in the size of 48×44 px and download the image here to your folder for images, in this example /Style Library/MiscStyles/quote-mark.png
  4. Delete the insert, update and delete parameters in the Data View. We only need the SelectParameter.

Make the Web Part be ready to be reused in the site collection.

At this point you have to modify some of the XSLT in order to use the web part in sub sites. You don’t need to this if you only want to use this web part at a page in a folder at the top site and don’t upload the web part to the gallery.

  1. It is three parts in the XSLT you have to modify:
  2. DataFormWebPart : Set the Viewflag to zero
  3. SelectParameters: Change the Parameter and add one more
  4. ParameterBindings: Change the value and name

______________________________________________________
<WebPartPages:DataFormWebPart runat="server" IsIncluded="True" AsyncRefresh="True" FrameType="None" NoDefaultStyle="TRUE"  Title="Quote" 
PageType="PAGE_NORMALVIEW" ListName="{2E43057F-5A51-41D2-B250-051D41DF2652}" Default="FALSE" DisplayName="Quote" __markuptype="vsattributemarkup" 
__WebPartId="{D7B96070-41A4-485E-A9ED-7DDDFF56C3F7}" id="g_d7b96070_41a4_485e_a9ed_7dddff56c3f7" autorefresh="true" autorefreshinterval="15" 
ViewFlag="0" >
______________________________________________________
<DataSources>
	<SharePoint:SPDataSource runat="server" DataSourceMode="List" UseInternalName="true" UseServerDataFormat="true" selectcommand="&lt;View&gt;&lt;/View&gt;" id="Quote4">
		<SelectParameters>
			<WebPartPages:DataFormParameter Name="ListName" ParameterKey="ListName" PropertyName="ParameterValues" DefaultValue="Quote"/>
			<WebPartPages:DataFormParameter Name="WebURL"   ParameterKey="WebURL"   PropertyName="ParameterValues" DefaultValue="/"  />
		</SelectParameters>
	</SharePoint:SPDataSource>
</DataSources>
______________________________________________________
<ParameterBindings>
	<ParameterBinding Name="ListName" Location="None" DefaultValue="Quote"/>
	<ParameterBinding Name="dvt_apos" Location="Postback;Connection"/>
</ParameterBindings>

  1. Save the page and switch to the design mode. Click at the Web Part, click at the Web Part tab in the ribbon and click at To Site Gallery. Type a name and a description and hit OK.
  2. Go to a page in the site collection to verify that everything works as expected.


Download the web part

You can download the web part here and try this out. This version does not use a background image. To get this working in your environment you have to create a custom list at the root site named Quote. Rename the Title column to Author and create a new column named Quote.

You can also download the DVWP as text file, if you need this a bit more readable.

Drop a comment if you have questions.
/ Christian