SharePoint – Show Item ID on View and Edit Forms using jQuery

While working on a project to customize a SharePoint site for use in managing Scrum, I came across the need to always show the ID of an item on the Edit (EditForm.aspx) and Display forms (DispForm.aspx). The team needed a quick way to identify what backlog user story they were working on as well as an identifier for referring the story to others. To do this, I turned to jQuery and JavaScript.

The approach and high level design is:

  1. Get the ID of the item
  2. Locate the table on the page that is displaying the item’s information
  3. Inset the ID if the item as the first row of the table

This approach assumes that somehow jQuery is already included on these pages.

Getting the item ID

The ID of the item can be retrieved from the URL. The Parameter name is ID and to retrieve it, we use SharePoint’s GetUrlKeyValue() function as such:


var thisItemId = GetUrlKeyValue("ID", false, location.href);

Getting a reference to the item table

This one is a little trickier. The best and most accurate way I have found to do this is to first find a field that is displayed on the page, and then “walk” back to the table. The approach is different depending on whether attempting to get it from the EDIT form or the DISP form. For this example I will use the Title field, which is a standard field on Lists and normally always displayed.


var $titleField = $("[title='Title']").closest('tr'),
    $table = $titleField.closest("table");
if (!$titleField.length){
    $titleField = $("[name='SPBookmark_Title']").closest('tr');
    $table = $titleField.closest("table");
}

Insert the ID in the item table

Now that we have the ID and a reference to to the table, inserting the ID is fairly easy. We first clone one of the rows already in the table, (in this example, the one we used to find the table), and modify it to include the label (ID) and the value for the item ID. Building on top of the code samples above, the following would insert the row into the top of table:


$table.find("tr:first").before(
    $titleField.clone()
        .css("display", "")
        .find("td")
            .eq(0)
                .find("h3")
                    .empty()
                    .append("ID")
                    .end()
                .end()
            .eq(1)
                .empty()
                .append(thisItemId)
                .end()
            .end()
);

The complete solution

I have created the following function that does all of the above in one shot.  I’m now using it in several site lists that I have been asked to customize and will add it to the SPWidgets project in a future version. In order to use it, you must first ensure that jQuery is already loaded since it adds a method to it’s namespace.

You can also get this function from this gist: https://gist.github.com/4520029


;(function($){
    "use strict";

    /**
     * Finds the form displayed on the EDIT and DISP pages and displays
     * the associated ID of the item at the top of that form.
     *
     * @param {Object} [options]
     * @param {String} [options.field="Title"]
     *                      The field to use in finding the table.
     * @param {selector,HTMLElement} [options.field=null]
     *                      The table where the ID
     *                      should be inserted. If defined on input, field input
     *                      param is ignored.
     * @param {String} [options.itemId=itemId]
     *                      The item ID that will be displayed on the table.
     *                      Defaults to the ID parameter in the URL
     * @param {String} [options.idWrapper=''
     *                      The HTML that will be used to wrap the ID when it is
     *                      inserted into the table/page.
     *
     * @return {Object} jQuery
     *
     * @example
     *
     * $().SPAddIdToFormTable();
     * $.SPAddIdToFormTable();
     * $().SPAddIdToFormTable({ field: "Name" });
     *
     */
    $.SPAddIdToFormTable = $.fn.SPAddIdToFormTable = function(options){

        var opt = $.extend({}, {
                field: "Title",
                table: null,
                itemId: GetUrlKeyValue("ID", false, location.href),
                idWrapper: '<div style="font-weight: bold; font-size: 2em;"></div>'
            },
            options);

        if (!opt.field && !opt.table) {

            return;

        }

        if (!opt.table) {

            opt._field = opt.field.toString();
            opt.field = $("[title='" + opt._field + "']").closest('tr');

            if (!opt.field.length){

                opt.field = $("[name='SPBookmark_" + opt._field + "']").closest('tr');

            }

            if (!opt.field.length) {

                try {

                    console.log("$.fn.SPAddIdToFormTable(ERROR) Unable to locate " +
                        opt._field + " on the page!");

                } catch(e) {}

                return;

            }

            opt.table = opt.field.closest("table");

        } else if (!opt.field) {

            opt.field = opt.table.find("tr:first");

        }

        opt.table.find("tr:first").before(
            opt.field.clone()
                .css("display", "")
                .find("td")
                    .eq(0)
                        .find("h3")
                            .empty()
                            .append("ID")
                            .end()
                        .end()
                    .eq(1)
                        .empty()
                        .append(
                            $(opt.idWrapper).wrapInner(opt.itemId)
                        )
                        .end()
                    .end()
        );

        return this;

    };

})(jQuery);

Again, to use this function, just include it in the page after jQuery. To use it, just call $.SPAddIdToFormTable() after the page has completed loading.

Enjoy.

Advertisements

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