Article
0 comment

this.domElement is your new document object in SPFx web parts development

You are familiar with the JavaScript method like ‘document.getElementByID’. Since HTML5 the Document Object Model has more to offer than return an element by its ID on a document.

Use this.document instead of document

Use this.document instead of document

I case of web part development you should forget that the document object inside and HTML exists instead you should request HTML elements differently.

[Read more]

Article
0 comment

Alternative to innerHTML in SharePoint Framework web parts

When you create a new project without any framework, the default web part content in the code will be added through innerHTML.
Technically there is nothing wrong with this approach, but you might run into a problem when you add more content to the web part afterward using the same method. In this case, the previously added content will be overwritten.


To avoid this behavior, you can use jQuery and the ‘append‘ or ‘prepend‘ methods to add your content. It works well but requires an external library.
Instead of using jQuery, there is a native method in the document object model of HTML available.

[Read more]

Article

SharePoint – Table of Contents jQuery plugin – Now available on GitHub

Today I decided to publish my table of contents script on github. There it will be much easier to handle all the issues and gives the global SharePoint community the possibilities to contribute to my code.

I know from many people that this script is wide spreader throughout various SharePoint installation. I’m looking forward to improve the code in near future. This table of content script has a real long history for me and I published the first version already for SharePoint 2010. It is still one of my most popular posts.

SharePoint - Table fo Contents

 

Let me share some statistics with you:

  • SharePoint 2010 – [Enhance Wiki Page Layout by adding a navigational Table of Contents](https://n8d.at/enhance-wiki-page-layout-by-adding-a-navgational-table-of-contents/)
    Page Views: 32,016
  • Office 365 / SharePoint 2013 – [Revised: Table of Contents for SharePoint Wiki Pages
    ](https://n8d.at/revised-table-of-contents-for-wiki-pages/)
    Page Views: 8,002
  • Office 365 / SharePoint 2013 -[How to use: Table of Content – jQuery Plugin](https://n8d.at/how-to-use-table-of-content-jquery-plugin/)
    Page Views: 2,289

From now on if you have issues or feature request simply publish them on github. If you like to contribute to this project you are also gladly welcome.

Table of Contents on GitHub

Article

How to use: Table of Content – jQuery Plugin

After I’ve published the revised version of my table of contents script I got many request on “How to use” it. You asked for it and here it is the guide how to embed the script. I won’t provide a full featured step by step guide here. Instead, I will provide a small package of a page layout and a guide how to script embed directly. To make this work you need to have an Enterprise Wiki or Publishing page. The first part covers how to add a page layout containing the table of contents script. The second method shows how to add the script using code embedding. You also need to download the following file TableOfContents-PageLayoutPack that contains all the required files.

[Read more]

Article

Revised: Table of Contents for SharePoint Wiki Pages

It’s more then two years ago when I first wrote a table of contents script to enhance wiki pages in SharePoint. Time to release a new version and this time it’s a jQuery plugin. This new version will work potentially work with all versions of SharePoint and Office 365. I just have tested it in SharePoint 2013 and Office 365.
Now I also included support to for all levels of headlines (<h1> – <h6>).
This is possible because a found a good old part in the jQuery Documentation

Table Of Contents - Live in Action

Table Of Contents – Live in Action

[Read more]

Article
6 comments

Safer request form fields in list forms using JQuery

Mark Anderson published today an article on his blog concerning an issue that currently exists in Office 365 and is called “Office 365 Update Changes ‘Display Name’ on Required Fields”. In this article he described that the rendering of fields recently have been changed in Office 365. I will take a look what can be done to solve this probably.

The cause of the problem

The title attribute of list fields have been widely use to customise forms in SharePoint using JavaScript, JQuery or SPServices. I used this attribute sometimes too do address fields by the display name. But somehow I always had a bad feeling about this. Why? Well, the ID attribute of the field is the only real unique identifier in the form. The downside using the ID is that you need to have some information about the field to generate the ID. But I will explain this later.
What the update recently in Office 365 did was to change the rendering of the field. Previously it look like this:

<select id="Region_59566f6f-1c3b-4efb-9b7b-6dbc35fe3b0a_$LookupField" title="Region">

Now it has changed to this:

<select id="Region_59566f6f-1c3b-4efb-9b7b-6dbc35fe3b0a_$LookupField" title="Region Required Field">

As you see now the title has additional parts such as required or field. This means that you haven’t in this attribute the display name of the field alone and you will fail if you query by title.

Safer approach to request fields

As mentioned before the ID property is the only one that is unique in the whole page. The ID is formatted in the following form:
Field name + ”_” + Guid of the field + ”_$” + Type of the field.
As seen in the previous section the ID looks like this:
Region_59566f6f-1c3b-4efb-9b7b-6dbc35fe3b0a_$LookupField
So if you like to be absolutely sure and like to generate this ID by yourself you need to do a request to the list and read the fields. The you will be able to find the name by the display name, the id and the type. This will make some lines of code that you can reuse in your projects. I haven’t seen any ready made code yet but I’m sure it can be found somewhere over the internet. (If you have would be great to post that in the comments)
I looked into this problem and what I found was that SharePoint does that job for you and stores it on the form in the JavaScript variable “WPQ2FormCtx”.

Console output of WPQ2FormCtx Object

Console output of WPQ2FormCtx Object

This context is somehow new in SharePoint 2013 and Office 365 This somehow represents the so called form context with a lot of information. Also included in this variable is the list schema which we can use without loading any additional information from the list.
So what I did is that I created a small javascript object that loads the information and allow me to generate the id of the field. The tricky part i currently not have implemented is the type part because this is a little bit tricky and the value changes with the different configurations of the fields. I hope that the following code give you an example how this works.

<script>
/* Handles the field of the form */
var fieldDefinitions = {
  Fieldname: [], // Stores all the display names of the field
  Fields: [], // Stores the complete field configuration
  // This function formats the list schema for easier acces
  ParseSchema: function(formContext){
  		var schema = formContext.ListSchema;
    	for(var field in schema)
    	{
			this.Fieldname.push(schema[field].Title);
    		this.Fields.push(schema[field]);
    	}
  },
  // Genereate the Fieldname and Field Guid Part
  GetIdByTitle: function(title){
	var index = this.Fieldname.indexOf(title);
	var currentProp = this.Fields[index];
	console.log(currentProp);
	// return the beginnng of the ID in the format 
	// FieldName (encoded) + "_" + Guid of Field
	return currentProp.Name + "_" + currentProp.Id; 
  }
};

$(document).ready(
    function () {
		// Reformats the form context   	
		fieldDefinitions.ParseSchema(WPQ2FormCtx);
		// returns the calulated ID of the field
		var fieldID = fieldDefinitions.GetIdByTitle("Region Field");
		// Wildcard request to the field 
		// sets the value of the Region Field
		$("input[id^="+fieldID+"]").val("Works");
    }
)
</script>

To this script the last part needs to be added to be 100% sure. Think about the fill in option for example this will start with the same id but I’m sure there will be added a special type.

Field after update via JS

Field after update via JS

As you see the value was written to the form

A Look to the future

I will never use the title field again. I write this now 100 times to keep it in mind. But not here in this blog post. In future I will reuse my little helper object for a simple reason. If Microsoft changes the format of the ID attribute I only need to change it at a central location instead of search and replace all my jQuery / JavaScript code.
Convenience is not everything better go an extra mile to be safe.

Article
4 comments

Remote form customization: Passing data to a modal dialog – Part 1

Let’s jump right into the topic how it is possible to pass data to a modal dialog. On first sight it looks like a complex task but after you read this article you will get an overview how it works. In this simple scenario I use a HTML Form web part with a text box and a hyperlink. The value then should be passed to the new form dialog of a custom list called “Cars”.

Opening the modal dialog

In general there are two ways to open a modal dialog.  The asynchronous and the synchronous way to open a modal dialog, but here I use the synchronous way to keep the code simple.

The setup for this scenario is simple. First I created a custom list named “Cars” and this list has nothing more than the default title field. After that I added a new HTML Form Web Part to the landing page of my demo site. Then I added a simple form to the web part. It consists of a textbox with the id “newcar” and a hyperlink with the id “create” to create a new entry. This form also loads JQuery from the CDN and the custom script that is needed to pass the value of the input field to the modal dialog.

html form web part

HTML Form web part that should pass the values to the modal dialog

The code of the form looks like this:

<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<div>
    <b>
    Car:
    </b>
    <input type="text" id="newcar" value="" />
    <a href="/sites/demo/Lists/Cars/NewForm.aspx" id="create">
        Create
    </a>
</div>

 

First the click event on the hyperlink needs to be registered to open a modal dialog. Then the data from the textbox needs to be passed to the title field of the modal dialog.

var childDialog = null;

$(document).ready(function(){

    // register event handler to open the modal dialog
    $("#create").on("click", OpenNewFormInDialog);

});

var OpenNewFormInDialog = function(e){
    // Disabling the default hyperlink behavior
    e.preventDefault();

    // Get the form url from the link
    var formUrl = $(this).attr("href");

    // Setting the option of the modal dialog   
    var options = {
        title: "New Car",
        url: formUrl
    };

    // Open the new dialog
    SP.UI.ModalDialog.showModalDialog(options);

}

So far so good this all no rocket science but how do we get the data to the form? Therefor a little trick is needed. The function “SP.UI.ModalDialog.get_childDialog()” will return the last loaded modal dialog. The modal dialog object returned by this function has a special property named $c_0. Once the dialog has been loaded it contains the content of the modal dialog. All that needs to be done is to recheck this property during the loading of the dialog. This can be accomplished with a simple recursive call that pauses for 100 milliseconds, in my case, and check the property again. If this is set then the loading has been completed.

...

    // Open the new dialog
    SP.UI.ModalDialog.showModalDialog(options);

    // Get the child dialog
    childDialog = SP.UI.ModalDialog.get_childDialog();

    // Check the loading state
    CheckDialogState();

}

var CheckDialogState = function(){

    // check if dialog is fully loaded
    if (childDialog.$c_0 != undefined || childDialog.$c_0 != null) 
    {
        // get title value from textbox
        var titleValue = $("#newcar").val();

        // load document from modal dialog into a jquery object;
        var dialogContent = $(childDialog.$c_0);

        // find title field in dialog by it's title value
        var titleInputField = dialogContent.find("[title=Title]");

        // setting the title field
        titleInputField.val(titleValue);

    }
    else 
    {
        // Wait for 100ms and then check again
        window.setTimeout("CheckDialogState();", 100);
    }

}
...

After the content has been loaded all that needs to be done is to parse the property to a JQuery object. Once it is accessible in JQuery the value of the form web part input field can be added to the title field of the new form. The result can be seen in the following screenshot.

modal dialog after the values have been passed

Modal dialog after the values have been passed to the modal dialog

Further user experience enhancement

A nice additional feature when data will be passed to a modal dialog is to tell the user to check the values. This can be done using the page status bar for example. The problem here is that the status bar cannot be enabled with the SharePoint function SP.UI.Status.addStatus.

Previously we already loaded the content to a JQuery object, so we can do further manipulation of the output of the modal dialog. SharePoint renders on default a placeholder for that page status with the id “#pageStatusBar”. The code to show the page status looks like this:

...
        // add message to page status bar and toggle the display to be shown
        dialogContent.find("#pageStatusBar").html("<strong>Please check the value</strong>")
        dialogContent.find("#pageStatusBar").toggleClass("s4-status-s2").css("display", "block");

        // resize the modal dialog.
        childDialog.autoSize();
...

At the end I forced the modal dialog to resize itself to avoid possible scrollbars.

Modal dialog with page status

Modal dialog with page status

If you have any suggestions or question please feel free to provide some feedback. As always you can download the html form web part in the link below.

Download the web part: Modal dialog part 1

Please make sure to change the path of the new form

Article
14 comments

Use Syntax Highlighter in SharePoint Rich Text Editor

Love it or hate it, but the rich text editor can be really powerful if you know how to customize. In this article I show you how the well-known SyntaxHighlighter script by Alex Gorbatchev can be added to a wiki page in SharePoint. The idea for this came from a discussion I had with Marc D. Anderson about the Microsoft SharePoint Blog template and how hard it is to format source code in SharePoint in a beautiful way. Well nearly every WordPress blog that provides source code in the posts has a plugin that adds the SyntaxHighlighter to the design. Well here is my integration to SharePoint that consists of the following three components:

  • Wiki Page Layout
  • Rich Text Editor Style
  • Script to embed the SyntaxHighlighter

The wiki page layout

First of all I created a specific wiki page layout to add the functionality of the SyntaxHighlighter. In this page layout I added references to a couple of scripts the SyntaxHighlighter need. I added those inside the content control with the id “PlaceHolderAdditionalPageHead”. This will render the script links to the head section of the master page.

<asp:Content ContentPlaceHolderId="PlaceHolderAdditionalPageHead" runat="server">
	<SharePoint:CssRegistration name="<% $SPUrl:~sitecollection/Style Library/~language/Core Styles/page-layouts-21.css %>" runat="server"/>

	<!-- Basic Style Definition -->
    <SharePoint:CssRegistration name="<% $SPUrl:~sitecollection/Style Library/SyntaxHighlighter/styles/shCoreDefault.css %>" runat="server"/>
    <SharePoint:CssRegistration name="<% $SPUrl:~sitecollection/Style Library/SyntaxHighlighter/SPIntegration/spSyntaxHighlighter.css %>" runat="server"/>

    <!-- Syntax Highlighter and SharePoint Integration -->
	<script type="text/javascript" src="/Style Library/SyntaxHighlighter/scripts/shCore.js"></script>
	<script type="text/javascript" src="/Style Library/SyntaxHighlighter/scripts/shBrushJScript.js"></script>
    <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.2.min.js"></script>
    <script type="text/javascript" src="/Style Library/SyntaxHighlighter/SPIntegration/spSyntaxHighlighter.js"></script>

	<PublishingWebControls:EditModePanel runat="server" id="editmodestyles">
		<!-- Styles for edit mode only-->
		<SharePoint:CssRegistration name="<% $SPUrl:~sitecollection/Style Library/~language/Core Styles/edit-mode-21.css %>"
			After="<% $SPUrl:~sitecollection/Style Library/~language/Core Styles/page-layouts-21.css %>" runat="server"/>
	</PublishingWebControls:EditModePanel>
</asp:Content>

Beside the SyntaxHighlighter I added one style sheet file for the integration to the rich text editor named spSyntaxHighlighter.css and a JavaScript I named spSyntaxHighlighter.js which will be used to render the source code in a proper way and uses JQuery.

Rich Text Editor Styles

To add a format block for the source code I defined for each language a specific rich text editor style. The format block using markup styles looks like this.

pre.ms-rteElement-CodeHTML{
    -ms-name: "Codebox HTML";
    border: 1px black solid;
}

What this markup style definition does is to add the <pre> tag to the content of the wiki page. For each language that should be supported I created an own markup style needs. This is required because it tells the SyntaxHighlighter script how to render the source code properly.

Script to embed the SyntaxHighlighter

As mentioned before I decided to use JQuery to execute the syntax highlighter script. Well the base task of my script is to look for the code blocks defined by the markup styles and then reformat those blocks. For an html code block the output of the rich text editor needs to be converted from:

<pre class="pre.ms-rteElement-CodeHTML">
       <p>Example paragrah in syntaxHighlighter</p>
</pre>

to this

<pre class="brush: js;">
       <p>Example paragrah in syntaxHighlighter</p>
</pre>

The script below will manage this transformation:

$(document).ready(function () {

    $("pre.ms-rteElement-CodeHTML").each(function () {
        addSyntaxStyle($(this), "brush: js");
    });

    SyntaxHighlighter.all();

})

var addSyntaxStyle = function (code, brush) {

    code.removeAttr("class");

    /*** Fixing IE stuff ***/
    var trimedCode = code.html().replace(/<br>/g, "\r\n");
    trimedCode = trimedCode.replace(/<br \/>/g, "\r\n");
    trimedCode = trimedCode.replace(/<BR \/>/g, "\r\n");
    trimedCode = trimedCode.replace(/<BR>/g, "\r\n");
    trimedCode = trimedCode.replace(/<BR\/>/g, "\r\n");
    trimedCode = trimedCode.replace(/<br\/>/g, "\r\n");

    code.html(trimedCode);
    code.replaceWith("<pre class='" + brush + "'>" + trimedCode + "</pre>");

}

For Internet Explorer I need to break the rendering of the source code inside the pre tag. The internet explorer adds additional breaks to the code. Therefore all html breaks needs to be removed and replaced “\r\n”. If those <br> tag won’t be managed the code will be messed up and the result would be only a single line of code instead of a good looking code block.

SyntaxhHghlighter integrated in SharePoint

Final code integrated in SharePoint

Usage

Sometimes it can be a little bit tricky to handle the rich text editor in the right way. For code embedding the best result can be achieved if the style block will be defined in the first step and later the code will be added by using the SharePoint functionality “Paste as plain text”. I recorded a simple video to show you how this works.

At the end you should get the following result.

Finally you can download this sandbox solution from Codeplex “n8d.SyntaxHighlighter”.

My integration of the SyntaxHighlighter supports currently the following languages:

  • VB, C#
  • HTML, XML, XHTML
  • JavaScript
  • SQL
  • PowerShell