Tallan's Technology Blog

Tallan's Top Technologists Share Their Thoughts on Today's Technology Challenges

Add a simple form to a List View in SharePoint

Brian Zebarth

Have you ever wished you could add a button or a simple form to a list view in SharePoint? Client Side Rendering using JSLink makes it easy. Of course you could add some JavaScript in a  Content Editor Web Part but you don’t have the same direct access to the list data and doing that also causes the ribbon to disappear until the user clicks on the List View Web Part which can be confusing for your users. JSLink allows you to add JavaScript to the page without causing this behavior. There are other advantages also, depending on how you choose to implement it.

You can use JSLink in 2 ways. You can edit the List View Web Part on a page and in the Miscellaneous section specify your JavaScript file in the JSLink field or you can do it in a List Definition.  I will be showing the later approach, although the same JavaScript could be used in either approach. The benefit to doing it using the List Definition is that your JavaScript is applied to every instance of the list that you create. In my case I was going to be creating lists programmatically and wanted the custom form to appear on each instance of the list I created.

I am going to assume you have a project with a list definition already, there are plenty of tutorials out there if you need help with this part. My list definition is based on a simple email mailing list with fields for name and email address. Add a new JavaScript file to your project. I was creating a farm solution so I added the SharePoint mapped folder Layouts and added a scripts folder under that for my JavaScript file but you may want to put it somewhere else. For now the JavaScript file can be left empty.

In the Views sections of the schema.xml file of your list definition add a new view. The BaseViewID for this view will likely be “2” but if you are creating multiple views yours may be different. Make sure you add a JSLink tag with the URL of the JavaScript file you just created. It should look something like this.

<View BaseViewID="2"
    Name="BEA96278-356F-4EEC-857B-BA8FF5874761"
    DisplayName="MailingList"
    Type="HTML"
    WebPartZoneID="Main"
    SetupPath="pages\viewpage.aspx"
    Url="Mailinglist.aspx"
    DefaultView="TRUE">
    <ViewFields>
        <FieldRef Name="Email"></FieldRef>
        <FieldRef Name="FirstName" />
        <FieldRef Name="LastName" />
        <FieldRef Name="MailerStatusIcon" />
    </ViewFields>
    <Query />
    <Toolbar Type="Standard" />
    <XslLink>main.xsl</XslLink>
    <JSLink Default="TRUE">/_layouts/15/MassMailerInfrastructure/Scripts/MailListView.js</JSLink>
</View>

Now you can edit your JavaScript file. The code below establishes the context variable that you will use for overriding templates and specifying event handlers. Pay close attention to the BaseViewID and ListTemplateType. Those must match the values from your list definition. There are a few lines I included but commented out. These lines show you the basic syntax to override the list view header, footer and items display. I am not going to go into detail about those but included them so you can see what is possible. You can see also that I am calling a function for the OnPostRender event. This function will create the custom form after the page is rendered.

(function () {
var overrideCtx = {};
overrideCtx.Templates = {};

//BaseViewID and ListTemplateType from List Definition
overrideCtx.BaseViewID = 2;
overrideCtx.ListTemplateType = 1001;

//overrideCtx.Templates.Header = "{Insert Header HTML}";
//overrideCtx.Templates.Item = "{function to generate items}";   //Automatically passes context to function
//overrideCtx.Templates.Footer = "{Insert Footer HTML}";

//OnPostRender event handler
overrideCtx.OnPostRender = postRenderHandler;

SPClientTemplates.TemplateManager.RegisterTemplateOverrides(overrideCtx);
})();

The postRenderHandler function generates the html for the form. In this function you have access to the list context so you can access the list name, site URL and even the list data (although I am not using that for this example). As you can see in the below code I am creating a dropdown for an email template to be used for the mailing, a text field for an email address of someone to notify when the mailing has run and a button to kick it off. I’ll leave implementing the code to populate the drop down and to send the emails to you. I implemented my send email functionality as a WCF service which I called using jQuery Ajax method.

function postRenderHandler(ctx) {
  //mainContent is a standard part of the list view page
  var mainContent = document.getElementById("mainContent");
  var alreadyThere = document.getElementById("emailTemplate");

  // Check if elements already rendered.
  if (!alreadyThere) {
    // Build HTML for the form elements to be added to the list view
    var buttonHtml = "<input type='button' value='Start Mailer' onclick=';sendEmail(\"" + ctx.listName + "\",\"" + ctx.HttpRoot + "\");' style='display:inline-block; margin:10px' />";

    var templateHtml = "<select id='emailTemplate' name='emailTemplate' class='form-control' style='margin:10px;'><option value=''>Select Template</option></select>"
    var notificationHtml = "<label for='notificationEmail' style='margin:5px;'>Completion Notification Email</label><input type='text' id='notificationEmail' name='noticicationEmail' class='form-control' style='margin:10px;' />";

    var headerHtml = "<div class='ms-fullWidth'>" + templateHtml + notificationHtml + buttonHtml + "</div>";

    //Insert html after end of mainContent
    mainContent.insertAdjacentHTML("afterEnd", headerHtml);

    GetTemplates(ctx.HttpRoot);
  }
}

function GetTemplates(siteURL) {
  // Add code to retrieve templates and add options to drop down
}

function sendEmail(listID, siteURL) {
  var templateID = parseInt(document.getElementById("emailTemplate").value);
  var notificationEmail = document.getElementById("notificationEmail").value;

  if (templateID) {
  // Add code call to web service to send email. Pass in listID, templateID and notificationEmail
  }
  else {
  alert("You must select a template.");
  }
}

Once you build and deploy your project and create your list you should be able to see and use your new form. If you followed my example it should look something like this.

screenshot

No comments

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>