Tuesday, January 18, 2011

Publishing HtmlEditor on a Custom Application Page

As promised, I thought I would give you a quick tutorial on how to add an HtmlEditor to a custom application page in SharePoint 2010.

As a quick overview, we had a need for streamlining our content creation process. We use standard HTML blocks to perform custom XSLT transformation before posting the content to our customer facing website, and needed a structured method for storing and transforming the data. Initially, we used Reusable Content Blocks to store the base HTML, and then used some CSS to highlight the editable regions. Unfortunately, the process became very difficult to manage, and required us to train our content editors in html best practices, which was extremely inefficient.

To streamline the process, we created a custom HTML editor and gave the users simple menus to click which would allow them to enter just the content which we would then wrap with our predefined content blocks. The menu's allow a user to click a specific block type, key in the content, and click the save button to view the preview article before saving. Here are a few screen captures to illustrate:
Content Editor Menus

Content Editor Dialog

As you can see in the above images, we created a menu to allow for editing and adding of content blocks. When an option is clicked, a Dialog Window opens containing 1 or 2 rich html editors depending on the block type. We chose to go with the standard Publishing HtmlEditor control because our users liked the ribbon options for easily formatting text and inserting links. I have seen other similar implementations that use the Telerik RadEditor or another third-party editor for adding HTML content.

The Nuts and Bolts

The HtmlEditor can be found in the Microsoft.SharePoint.Publishing.WebControls namespace, and is intended to work specifically with publishing pages. The class is sealed, so creating a new editor from the base class is impossible. After a little bit of tweaking though, it really wasn't difficult to get the editor working on our custom application page.

I first created a new SharePoint Empty Project in VS 2010, and added a new Application Page to the /_layouts folder. I like to keep my custom pages organized, so I created a folder under Layouts called "Editor". To use the HtmlEditor, you will need to add references to the following DLL's in your project:

Microsoft.SharePoint.Publishing.dll - located in \14\ISAPI\
Microsoft.Web.CommanUI.dll - located in \14\ISAPI\

I then modified opened my ApplicationPage.aspx file and made the following modifications:

I removed the reference to the aspx.cs page, which is added by default, and changed the MasterPageFile to use v4.master instead of ~/masterurl/default.master. The reason for the different master page is that we have some heavy customization for our default branding, and I didn't want this to carry over to our application page.

I then added the following references:

These references ensure that you can add the HtmlEditor to the page, and that the Ribbon controls will load.

Next, in the PlaceHolderMain section I added a reference to the editor:

<Publishing:HtmlEditor ID="htmlEditor" runat="server" />

By default, the reference to the editor was not added to the designer.cs file, so you will need to manually add it if you want to interact with it in your aspx.cs file. 

In the aspx.cs file, you will need to add these two using statements:

using Microsoft.SharePoint.Publishing;
using Microsoft.SharePoint.Publishing.WebControls;

To fully configure the editor for use, you will need to override the OnInit() function. Here is the code I used:

        protected override void OnInit(EventArgs e)
            SPRibbon ribbon = SPRibbon.GetCurrent(this.Page);
            if (ribbon != null)

            htmlEditor.Field = new RichHtmlField();
            htmlEditor.Field.ControlMode = SPControlMode.Edit;
            htmlEditor.Field.EnableViewState = true;
            htmlEditor.Field.AllowReusableContent = false;
            htmlEditor.Field.MinimumEditHeight = "200px";


            btnSave.Click += new EventHandler(btnSave_Click);


As you can see, I also trim the Wiki controls from the Ribbon. I don't have a need for the Layout and Check out functions. I then create a new RichHtmlField() which stores the contents of the HtmlEditor. Notice that I set the field ControlMode to edit, and modify a few additional parameters to hide options from the ribbon. The final step is to add the RichHtmlField control to the page. Adding the field to the page causes the page to render the associated Ribbon Contextual Tabs. Without it, you would only see a text area for entering content, but the Ribbon would never display.

To get the rest of the editor wired up required some javascript to handle the population of the editor control, and a few hidden fields for storing parameters from the parent page such as editor type and control id. We have up to 8 editable sections for a standard article, so the id of the parent content area was necessary to maintain the position of our content blocks. I also perform an initial post back of the page via javascript in order to validate the variables and throw an error message is one of the required values is missing. 

To post the content back to the parent page, I use a button click event, and the following code to write the information back to the parent:

string close = "<script src="\"/_layouts/jquery/jquery-1.4.2.min.js\"" type="\"text/javascript\"">
<div id="\"content\"">
" + Html + "</div>
<script type="\"text/javascript\"">
var obj = new Object(); obj.content = $('#content').html(); obj.id = "
+ hdControlId.Value + "; window.frameElement.commonModalDialogClose(obj, 1);


This essentially clears the context of the page and returns a modalDialogClose() command with my returned values.


Hopefully this post will save you some time in trying to get the SharePoint HTML Editor to display on an application page. If you have any questions, feel free to drop me a line.

Friday, January 14, 2011

Javascript Auto-Populate Complex Fields

It's been awhile since my last post, but I've been hard at work rolling out new functionality to our portal. Recently, I've been creating several dialog actions in SharePoint 2010 to enable users to perform various functions. The new SharePoint dialog framework is a fantastic addition to the product, but you may hit a few road blocks when trying to perform tasks that should be fairly straight forward, like pre-populating a dialog with parameters from a parent window. Hopefully this post will help you stay sane.

One of the primary features of our portal is that it acts as a Knowledge Base for our Customer Care Agents. We are constantly striving to keep our content up-to-date, but with over 4000 knowledge base articles, it takes more than just 1 or 2 sets of eyes to keep that content updated. In an attempt to streamline the update process, we decided to add a feedback mechanism to allow users to submit suggestions or requests. The best method for storing and reporting on this information, in my opinion, was to create a custom list to store requests. Using a SharePoint list allows us to easily track requests, maintain an SLA for updating content, and generating notifications and tasks based on these items.

In v1 of the content feedback system left much to be desired. We only captured a simple url, and submitting feedback used an ajax and custom modal form to push the data to the list. Unfortunately, we were only capturing the url, which didn't offer us the ability to categorize and assign the feedback.

In v2 we wanted to use a more out-of-the-box approach, and auto-populate various fields to allow us to assign the request to a specific content owner or group based on Taxonomy fields and User Fields on the parent knowledge base article. Easy, right?

Unfortunately, many of the SharePoint JS library are undocumented. The Client OM offers some nice functionality, but in regards to modifying any of the advanced field types (Taxonomy Field, Rich Text Editor, User Field), there just isn't much out there. Yours truly decided that "no mountain is too high" and tackled pre-populating these field types anyway. After hours of sifting through thousands of lines of js, here are my findings. Hopefully they save you more time than it took me to discover them.

Taxonomy Field Values - how to set them via javascript

The Taxonomy Field proved to be the most difficult to auto-populate via javascript. The Taxonomy Field allows a user to paste values into the editable region of the field, but a web service call is required to validate the terms and populate the Taxonomy Field hidden storage with the correct Term Label and Guid.

I first needed to locate the script that loads the Taxonomy Field Control. The script can be found in the /14/TEMPLATE/LAYOUTS/ folder, and is called ScriptForWebTaggingUI.js. Step 1 complete, and the rest is butter, right? Unfortunately, ScriptForWebTaggingUI.js is minified, and there isn't a nice clean debug.js file to accompany it. Time to start digging. After a few painstaking hours, I stumbled across the appropriate method for updating the Taxonomy Field after populating the values.

Here are the steps I took

1. Created a hidden field on the parent display form using the following code:

<xsl:element name="input">
  <xsl:attribute name="type">hiddenxsl:attribute>
   <xsl:attribute name="id">hdArticleServicesxsl:attribute>
   <xsl:attribute name="value">
     <xsl:value-of select="@Services"/>

2. Next I the function to open the list form for my feedback list, and put a button on the form to call the function:

<script type="text/javascript">
        function OpenArticleFeedbackDialog() {
            var options = SP.UI.$create_DialogOptions();

            options.url = "/AboutC3/Lists/Article Feedback/NewForm_User.aspx";
            options.title = "Submit Article Feedback";
            options.width = 630;
            options.height = 500;
            options.args = {
                title: $('#hdArticleTitle').val(),
                category: $('#hdArticleSupportCategory').val(),
                services: $('#hdArticleServices').val(),
                attached: $('#hdArticleAttachedServices').val(),
                owner: $('#hdArticleOwner').val(),
                backup: $('#hdArticleOwnerBackup').val(),
                id: $('#hdArticleId').val(),
                url: location.href

        options.dialogReturnValueCallback = Function.createDelegate(null, CloseArticleFeedbackDialogCallback);

    function CloseArticleFeedbackDialogCallback(result, target) {
        if (result) {
            alert("Thank you for your feedback.");

As you can see, it's a standard showModalDialog call, but notice the options.args object. I'm using jQuery to grab the hidden field values and send them to the child window. 

3. Next, I created a function on the newform.aspx file to grab the variables and populate the fields on the form. I added this function to the "PlaceHolderAdditionalPageHead" place holder on the newform.aspx page.

<script type="text/javascript">
        function _setArticleValues() {
            var args = SP.UI.ModalDialog.get_childDialog().get_args();

            $.each(args, function (i, n) {
                switch (i) {

                    case "title":
                        $("input[title='Feedback Title']").val(n);

                    case "category":
                        var c = _parseTaxValue(n);

                    case "services":

                    case "attached":
                        _setTaxFieldValues('ctl00_ctl21_g_09d208ae_a4f5_4702_a96a_c661d67d2c11_ff151_ctl00_ctl02editableRegion'); break;

                    case "owner":

                    case "backup":

                    case "id":
                        $("input[title='Content Id']").val(n);

                    case "url":
                        $("input[title='Feedback URL']").val(_parseUrlValue(n));

        function _setTaxFieldValues(id) {
            var obj = new Microsoft.SharePoint.Taxonomy.ControlObject(document.getElementById(id).parentNode.parentNode.parentNode);

        function _parseUserValue(user) {
            var $h = $(user),
img = $h.find("img.ms-imnImg"),
output = "";

            if (img) {
                output = img.attr('sip');

            return output;

        function _parseTaxValue(input) {
            var s = input.split(";"),
output = "";

            if (s.length > 0) {
                for (var i = 0; i < s.length; i++) {
                    var t = s[i].split(":");
                    output += t[t.length - 1].replace('&', '&') + ";";

            return output;

        function _parseUrlValue(input) {
            var output = "",
s = input.split("&");
            if (s.length > 0) {
                output = s[0];

            return output;

        ExecuteOrDelayUntilScriptLoaded(_setArticleValues, "scriptforwebtaggingui.js")

As you can see, I'm performing quite a few functions to normalize the data which I will get into shortly. 

The primary script is called _setArticleValues, and I use the SharePoint ExecuteOrDelayUntilScriptLoaded function to wait for the taxonomy field js to load. ExecuteOrDelayUntilScriptLoaded is an extremely valuable function when attempting to update complex field values from javascript because in many cases the field controls don't exist until the initial script is complete.

4. I first added the fields to the form, and did a simple html source view to grab the dynamic id's of the controls. The next step was to grab the html of the taxonomy field by writing the js generated html to a div tag on the form. This is where I discovered that the editable region of the Taxonomy Field is just the ID of the parent div + "editableRegion". Setting the HTML of the editable region is easy enough using jQuery, but unlike the Rich Text Editor, the Taxonomy Field doesn't post it's editable region contents to a hidden storage field before submitting the form (I will go into the RTE functionality in depth next). This is where I got stuck and decided to torture myself by sifting through SharePoint JS, and how I discovered this function:


Unfortunately, this is part of the taxonomy control object, so you have to create an object before calling this function like so:

var obj = new Microsoft.SharePoint.Taxonomy.ControlObject(document.getElementById(id).parentNode.parentNode.parentNode);

This was the magic function to fix all of my pain. Once I ran this function, the taxonomy field values were automatically saved to the list item, and peace was restored to the galaxy. I can go into much more detail, but would rather get to the next field type.

Rich Text Editor - Setting Field Values

The above code doesn't really demonstrate how to pre-populate a rich text field, but another project of mine required a modal dialog html editor. Painful yes, but quite rewarding once it was complete. I will go into the details of creating an application page with the Microsoft.SharePoint.Publishing.WebControls.HtmlEditor in my next blog post, but for now I will show you how to auto-populate it with html.

1. Much like the Taxonomy Field, you need to find the ID of the control. In an application page, this can be done dynamically using the reference, but in a list form you will have to grab the id from the rendered source. 

2. Once you have the ID, it's really a piece of cake to set the field value using jQuery or Javascript. This is the code I used for my application page:


As you can see, the _hiddenDisplay field is the only field you need to set. Once this field is set, the contents are rendered accordingly. One item to note, when passing the argument to your child dialog, do not use the SP.Utilities.HttpUtility.htmlEncode function, as there is no decode function in the js.

User Field Values

The SharePoint user field is almost identical to the Rich Text Editor field, but requires a little bit of finessing to get the correct value. When an data form web part renders the xsl version of the User Field, quite a bit of html is injected to display the hyperlink and user presence image. That's where this function comes in:

function _parseUserValue(user) {
    var $h = $(user),
img = $h.find("img.ms-imnImg"),
output = "";
    if (img) {
        output = img.attr('sip');

    return output;}

As you can see, I simply convert the user field value to a jQuery object, and then run some simple html functions against it to grab the appropriate attribute that holds the email address of the user. I then set the User Field editable region with the email address value like so:


Fairly self-explanatory, but you still have to determine the ID of the rendered User Field, and the appropriate div where the editable region is located.


Auto-populating complex field types via javascript can be a real bitch. Determining what field types you are populating is the first step; you then need to determine what order the SharePoint scripts are loaded so you can execute your functions after the final script control has been loaded on the page. I hope this post helps save you some time, and keeps you sane. As always, feel free to drop me a note if this post helped, or if you have any additional questions. And please excuse the poor grammar and sentence structure; I spent most of last night working on this, and wanted to get it up here before I forgot my steps.