SharePoint on the Client : Tip #1 - Field Map

Why

Working with server side code in SharePoint is becoming a thing of the past. More and more often clients ask to implement features using JavaScript only. Transitioning from c# to JavaScript can be daunting. This is my first post addressing some common problems.

Javascript: Getting out-of-the-box fields

A basic problem when customizing SharePoint forms is to find and manipulate fields. This is specially true when you do not have access to the server side markup. Default fields have a generic ID that may change over time therefore we need an alternative way of identifying input controls.

Preamble

In this scenario we need to hide the title field in an edit form.

SharePoint Form Field rendering is a topic onto itself, which I'll cover in depth in another post. I'll skip all the other parts and focus on one of templates that SharePoint uses to render a field: CompositeField template

The CompositeField rendering template is in charge of printing the html markup on the page.

Title field edit section

Title Field Edit Section

Editing these templates or creating your own is one of the way to control field rendering. Let's take a look under the hood.

Server Side Markup

HTML (Title field markup on Edit mode)

The markup is an excerpt form a Task Edit form. Notice how the ids of the controls are named in the usual asp.net container model. Needless to say these are dynamic and not guaranteed.

Field Map function

Finding the input control

Let's focus on the control itself. Notice that the input control has several attributes that can help us to target it.

Approach #1

The title attribute takes the value of the display name of the field (in this case 'Title'). Depending on whether the display name changes over time this might be a good selector.

jQuery Selector:

$('input[title="Title"])
      
Approach #2

Relying on the display name is a weak assumption.

By now you must have seen the comment section both in the template and html. This section includes the name and internal name of the field. The internal name will not change over time and should make a good selector.

The sample below will return a section in the form that contains the internal name of your field and therefore the input control, description and label that make up the data entry section.


Refactor and Ship

The function below will create a map of all the field sections in the form. It returns an array of sections that can be referenced by internal name.

FieldMap Function Usage
var myMap = fieldMap();

$('input',myMap['Title']).hide();
        

Resources & Credits

  1. Original Field Map by Alexander Bautz
  2. jQuery Selectors
  3. SharePoint Rendering Templates

comments powered by Disqus

Categories

Under Construction

About Me

Martin here. I'm a developer by choice. Focused in SharePoint & JavaScript.

  • Follow me on Twitter