Me & My SharePoint [FrontEnd]

© Christian Stahl – All about SharePoint branding & customizations

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

Validate a SharePoint list column with regular expression — February 6, 2011

Validate a SharePoint list column with regular expression

Column validations is in SharePoint 2010 a feature for lists, this is great when you need to validate a column like compare if a number is between some interval or if an end date is later than a start date.

Regular expression is not available out of the box as a feature in SharePoint 2010 column validation so how can we do this? If it´s about a smaller implementation like just one list form then jQuery would be the alternative. What about the third-party market? Take a look at Bamboos product called Bamboo validate column. If you need regular expression as an inbuilt feature in all lists in you environment, this product is definitely something to looking into.

How to use regular expression for validation with jQuery then? Let´s first take a look at the jQuery plugin called jQuery.Validate and how we can use this in SharePoint. This plugin offers a lot of options for customizations. JQuery validate has been around since early 2006 and is written by Jörn Zaefferer, lead developer of the jQuery UI team and it.

In following steps we will link our friend the Content Editor Web Part (CEWP) to a jQuery script stored in a document library at the same site. This apporach could be done by refering the master page, the page layout or as a packed web part if you prefer to.

<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.4.4.js"></script>
<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery.validate/1.7/jquery.validate.min.js"></script>

<script type="text/javascript"> 
$(document).ready(function() { 

$("#aspnetForm").validate({ 
submitHandler: function(form) { 
}}); 

$.validator.addMethod(
      "regex",
      function(value, element, regexp) {
          var check = false;
          var re = new RegExp(regexp);
          return this.optional(element) || re.test(value);
      },""
);

// VALIDATE TITLE
$("input[title='Title']").rules("add",{ 
 required: true,
 regex:"^[A-Za-z0-9- _]{1,100}$",
 messages: { 
 regex: "<br />One or more special charachters.." 
}
});

// BLUR -  Set focus after alert
$("input[title='Title']").blur(function() { 
if (!$("input[title='Title']").valid()) { 
this.focus(); 
} 
}); 

// SAVE - Cannot save if regex rules adds
$("input[value='Save']").focus(function(){ 
if (!$("input[title='Title']").valid()) { 
alert("You cannot save this Item.."); 
$("input[title='Title']").focus(); 
} 
});

}); 
</script> 

Let’s start:

  1. Copy the script above and save it to a text file (.TXT)
  2. Add this text file to Share Documents in the same site as the list. You can create a new document library if you like to this script separate. Copy the shortcut to this file.
  3. Create a custom list named Validate
  4. Create a column named Email with the type ‘single line of text’
  5. Go to the Validate Lists New Form page. Click the List tab in the ribbon and select Default New Form.
  6. Click Add a Web Part. Select Media and Content to the left and select Content Editor. Click Add.
  7. Click at the arrow to the right of the web part and select Edit Web Part. Paste or type the link to the text file you uploaded in step 2. Set the link to be relative like, e.g. /RegEx/Shared%20Documents/ValidateWebPart.txt
  8. Type a title in the Content Editor Web Part and select ‘none’ for the chrome type to and set the web part to be hidden. Click OK.

More things you can do

This example refers to latest jQuery, if you already call the jQuery from the master page make sure to not call it twice. If you are going to set this in production, make sure to use the same approach for the edit form page.

You can do a lot more with this plugin; let´s try to use some other validation methods like URL and Email validation. If you followed this example you created the column named Email, let´s validate this column so we can be sure that the user type a valid Email address here.

Just add this section in the same pattern as the script above. Paste this between validate title section and the blur section. You can add Email to the blur and save as well.

// VALIDATE EMAIL
$("input[title='Email']").rules("add",{ 
 email:true,
 messages: { 
 email: "<br />Not a valid Email address.." 
}
});

Check out this page for more information about validation and regular expression

About the validation plugin
http://docs.jquery.com/Plugins/Validation
Bamboo column validator
http://store.bamboosolutions.com/pc-149-1-bamboo-validator-column.aspx
8 Regular Expression you should know
http://net.tutsplus.com/tutorials/other/8-regular-expressions-you-should-know/