Wednesday, August 04, 2010

Using jQuery validation in a sharepoint web part

As we all know, a sharepoint page can only have one <form > tag in it. As anyone who wanted to use jQuery validation knows, the validation script needs to run on a form tag.
So how do I use the validation code in a sharepoint web part?

The answer is to run the script against the form that already exists in the page. For example, I had to write a web part with an email address field, and wanted to help the users by validating the text they entered is a valid email address on the client side (I also validate on the server side - just in case someone is running a browser with no script). This is the "Render" override code that I used:

       txtEmailAddress1.CssClass = "required email";
       base.Render(writer);
       if (SPContext.Current.FormContext.FormMode != Microsoft.SharePoint.WebControls.SPControlMode.Edit)
       {
              writer.Write(@"<script>
$().ready(function() {
    $(""#" + this.Page.Form.ClientID + @""").validate();
});
</script>
");
       }

As you can see, I am adding a css class of type "required email" for the text box, and then telling the form on the page to validate using the jquery validation plug in. This of course assumes you added the references to the jquery scripts to the page...which you may want to do as part of the web part (override oninit, and registerclientscriptblock) or as part of the master page (if you expect a lot of web parts to use it).

As for the "if (SPContext.Current.FormContext.FormMode != Microsoft.SharePoint.WebControls.SPControlMode.Edit)" line - you have to be careful that your validation does not prevent you from editing the page. For example, if you remove that "if", you will not be able to change the properties of any web part on the page without first entering a valid email address in the textbox!

I am speaking at the South East Asia SharePoint Conference!

Are you planning to be in Singapore on October 26-27 this year? You should! the speakers are being announced, and I for one will be there for at least one presentation - how to build web parts for 2010. And no, it is not going to be the regular "open visual studio, choose the web part project" presentation...get ready for big things!
See you there!

Saturday, July 31, 2010

A bit more about custom field types and XSL

The following are the attributes you can use in XSL to identify the field you want to change (or access the value of):

  • Name (example: "First_x0020_Column" - the internal name of the column - not the field type!)
  • Type (example: "Text" - the base type of the field type)
  • FieldType (example: "MyCustomFieldType" - the type name of the custom field)
  • DisplayName (example: "First Column" - the title of the column
  • ID (example: "1b858cea-4306-4cf9-91e8-8bb8674dcdf4" - the GUID for the current column

Applying a XSL stylesheet to a custom field

In the MSDN walkthrough and examples on using XSL to create a custom rendering style for a custom field type, the sample XSL all use the field's name as the reference. This is a bit silly - since it means the users need to create the new fields with the exact same name.

While the option to create a custom rendering based on the field name is welcome and will be very useful (if for example I am deploying a column to a farm and I want it to have a unique rendering template), the articles do not explain how to create a XSL rendering template for a field type - regardless of what the fields created from that type are called.

The solution is simple. Lets say your field type is "MyFieldType", then instead of the following line that uses the title of an instance of the field ("my field type"): <xsl:template match="FieldRef[@Name = 'My Field Type']" mode="Text_body"> use the following line instead, which uses the type name of the field: <xsl:template match="FieldRef[@FieldType = 'MyFieldType']" mode="Text_body">

Monday, July 26, 2010

5 Days SharePoint Development Training - Canberra, 16th August, 2010

Are you in Canberra on the week of the 16th, and is just itching for some sharepoint 2010 developer training? look no further!
I have teamed up with my friends from Synergy to deliver the first ever Synergy SharePoint 2010 Development course. For more details on the content of the course and how to register, head to Dimension Data's web site!

Tuesday, July 13, 2010

New look for the blog

Do you like it? Blogger has some new templates, and I figured its time for a change.

Update: following some comments, I reverted to white background again - and removed the width restriction that pissed me off. Is this better?

Monday, July 05, 2010

"The local device name is already in use" error when using AddFieldAsXml

I had the following exception thrown at me today when trying to add a site column using AddFieldAsXml method: "The local device name is already in use".
The reason was that my XML contained a field ID - which is what the XML for a field is supposed to have when it is used as an element file in a feature, but not when you are adding the field using code. So - beware!

Thursday, July 01, 2010

Read my book on Rough Cuts

Do you want a preview of my upcoming book - the 'SharePoint 2010 How To'? simply go to Safari books online and read away! There is also a purchase option if you like what you see...

Sunday, June 20, 2010

SharePoint Conference Australia Presentation Notes

Thanks to everyone who came to see me and Brian present in the Australian SharePoint Conference last week!.
To answer the question that we got during the demo, the silverlight web part project template can be downloaded from this site: http://code.msdn.microsoft.com/vsixforsp.
Also, to see the code for Brian's twitter map web part, see his blog post on the subject: http://blog.brianfarnhill.com/2010/05/21/twitterbing-maps-web-part-how-i-did-it/.
Finally - for everyone who asked for the slide deck, it is now available from my company's (Extelligent Design) web site: http://www.extelligentdesign.com/in-the-news/sharepointconferenceaustraliapresentationnowavailable where you can also purchase KWizCom products (for australian\new Zealand customers only) or contact me about sharepoint training or consulting.

Tuesday, June 01, 2010

Validating Web Part Properties

Nothing is more annoying than configuring a web part by changing its properties and then hitting ok only to see the web part display an error that a property is invalid - and having to open the properties pane again to fix the problem.
To avoid this, best practice is to validate the data entered in the "set" of the web part property. For example, if I have a web part property that needs a comma delimited array of numbers (for example 1,2,3,4) and I don't want to build a tool part just for that, I can still build a property like this:

public string NumberArray
{
    get{return _numberArray;}
    set{_numberArray=value;}
}
The problem with the code above is that it is not validating that the string entered is indeed an array of numbers. To do that, I could change the code to something more like this:
public string NumberArray
{
    get{return _numberArray;}
    set{
          string [] arr = value.split(',');
          foreach (string item in arr)
          {
             int i;
             if(!int.TryParse(item,out i))
                throw new Exception("The item \""+item+"\" is not a valid number");
          }

_numberArray=value;}
}
This will do what I want - preven the user from closing the web part properties pane before fixing the error in the property, but it will not display the nice informative error to the user. Instead, it will show a generic error "An error has occurred" despite the fact that I specified what the error was when I threw the error!
Why? because to do that the exception must be of type WebPartPageUserException.
So the correct code for validating my sample property would be:
public string NumberArray
{
    get{return _numberArray;}
    set{
          string [] arr = value.split(',');
          foreach (string item in arr)
          {
             int i;
             if(!int.TryParse(item,out i))
                throw new WebPartPageUserException("The item \""+item+"\" is not a valid number");
          }

_numberArray=value;}
}

Now - when the users put an invalid value in my property they will be notified that it is invalid, and which value it was.