Second Life of a Hungarian SharePoint Geek

February 5, 2010

How to change the order of the fields on a SharePoint form using code

Filed under: SharePoint — Tags: — Peter Holpar @ 16:11

When you add a new field to a list, it is automatically placed at the last position of the form. It is not always what you want.

On the user interface you can use the Column ordering link from the list settings page, but there is no direct support in the object model to set the position of a field.

You can find a few examples on the web about using the REORDERFIELDS method:

I found these example a bit overcomplicated and inconsistent, lot of unnecessary tricks with web and list references and IDs, building part of the XML request using XmlTextWriter, other part as string, etc. It is not surprise that lot of comments complain about different type of exceptions when testing the code.

The above posts do not bother too much with the theory of reordering although it would help better understanding of code and finding the source of the error easier.

The SPField class has a property called Reorderable. Reorderable fields are displayed on the Change Field Order page. These fields are available only for reordering but you should include all fields of the list in the request. Reorderable fields come first and non-reorderable fields must follow them. You should refer to the fields using their internal name. Double check the names to be sure you use the correct ones. Naming is not always trivial, for example, the internal name of the Description field in the Tasks list is Body.

Michael Ekegren wrote: ‘The version is very important to remember otherwise you’ll get an error message like” the list have been updated by another use – click back in the browser to refresh your changes” or something like that.’ Well, that is not exact. Based on the documentation and my experience, the owshiddenversion attribute is optional. Of course, if you use that, you must set its value correctly. But if you omit that, you also get an error message, if the list is changed in the meantime.

The following code sample shows how to move a field to the last position.

  1. String fieldReorderable = String.Empty;
  2. String fieldNonReorderable = String.Empty;
  3. String fieldStrFormat = "<Field Name=\"{0}\" />\r\n";
  4. // we move this field to the last position
  5. String fieldNameToLast = "Body";
  6.  
  7. string reorderMethodFormat = @"<?xml version=""1.0"" encoding=""UTF-8""?>  
  8.         <Method ID=""0"">  
  9.         <SetList Scope=""Request"">{0}</SetList>  
  10.         <SetVar Name=""Cmd"">REORDERFIELDS</SetVar>  
  11.         <SetVar Name=""ReorderedFields"">{1}</SetVar>   
  12.         </Method>";
  13.  
  14. foreach (SPField field in list.Fields)
  15. {
  16.     if ((field.Reorderable) && (field.InternalName != fieldNameToLast))
  17.     {
  18.         fieldReorderable += String.Format(fieldStrFormat, field.InternalName);
  19.     }
  20.     else if (!field.Reorderable)
  21.     {
  22.         fieldNonReorderable += String.Format(fieldStrFormat, field.InternalName);
  23.     }
  24. }
  25.  
  26. String fieldMoved = String.Format(fieldStrFormat, fieldNameToLast);
  27. String fields = String.Format("<Fields>{0}{1}{2}</Fields>", fieldReorderable, fieldMoved, fieldNonReorderable);
  28.  
  29. String reorder = String.Format(reorderMethodFormat, list.ID, SPHttpUtility.HtmlEncode(fields));
  30. web.AllowUnsafeUpdates = true;
  31. String res = web.ProcessBatchData(reorder);
  32. web.AllowUnsafeUpdates = false;

The Code attribute of the Result tag in the response message for a REORDERFIELDS request must be zero on success or a negative value on error.

Some typical error you can face when working with this code:

<Result ID="0" Code="-2147467259">
<ErrorText>Cannot complete this action.

Please try again.</ErrorText></Result>

The format of the request is wrong. Be sure you encoded the value set for the ReorderedFields variable.

<Result ID="0" Code="-2130575323">
<ErrorText>Fields have been added or removed since you began this editing session. Please refresh your view and try again.</ErrorText></Result>

There are missing or extra fields in the request. Be sure you used the proper internal names.

<Result ID="0" Code="-2130575305">
<ErrorText>Save Conflict

Your changes conflict with those made concurrently by another user. If you want your changes to be applied, click Back in your Web browser, refresh the page, and resubmit your changes.</ErrorText></Result>

The schema of the target list has been changed in the meantime.

Finally here are a few exceptions and the possible reasons.

SPException when calling ProcessBatchData: “The security validation for this page is invalid. Click Back in your Web browser, refresh the page, and try your operation again." You probably forgot to set the AllowUnsafeUpdates property of the current SPWeb instance to true.

"Exception has been thrown by the target of an invocation.", InnerException: "Object reference not set to an instance of an object." in the SPField variable declaration part of the foreach block. The field is not installed correctly. Try to remove and add again. If you add the field from code, check the code.

ArgumentException when calling ProcessBatchData: "Value does not fall within the expected range." You should use double quotes, not apostrophes in the XML header.

Correct:

<?xml version="1.0" encoding="UTF-8"?>

Wrong:

<?xml version=’1.0′ encoding=’UTF-8′?>

Advertisements

2 Comments »

  1. […] you have read my former posts about custom fields and reordering of list fields you already know what you need to create such field types […]

    Pingback by Multiple column lookup field for SharePoint « Second Life of a Hungarian SharePoint Geek — February 15, 2010 @ 03:23

  2. Thank you so much for posting this, I had found the other articles but there were key things they left out, your explanation is much more comprehensive.

    Comment by James Fuqua — April 20, 2011 @ 18:22


RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Blog at WordPress.com.

%d bloggers like this: