Tuesday 19 April 2016

Creating HTML controls in SharePoint List Views and calling JavaScript code from their events!

If you ever need to create some HTML controls in a SharePoint List Views and have to associate some action on some events such as open a dialog form on a click of a HTML Button. 



You can use calculated columns. All you have to do is to define your HTML code in a calculated column and if you are adding some funky logic then add your java script file on the page.

Calculated Column formula: ="<DIV><input type='button' id='clickDetails' value='+'  onclick='javascript:popUp("&IdValue&");'/></DIV>"



Don't forget to change "The data type returned from this formula is:" to either Number, currency etc. If you keep it as "Single line of text" then HTML will render as text not as HTML control.


Where popUp function is defined in the included js file as following. You can include this java script on the page using many methods. For an example you can use a script editor web part to do so.

<script type="text/javascript">
function popUp(Id) {            
    var siteCollUrl = _spPageContextInfo.siteAbsoluteUrl;
    var pageUrl = siteCollUrl + '/SitePages/mypage.aspx?Id=' + Id;
    var options = {
        url: pageUrl,
        args: null,
        showMaximized: false,
        width: 1020,
        height: 750,
        title: 'Collect some data',
        dialogReturnValueCallback: function (dialogResult) {
            SP.UI.ModalDialog.RefreshPage(dialogResult);
        }
    };
    SP.SOD.execute('sp.ui.dialog.js', 'SP.UI.ModalDialog.showModalDialog', options);
}
</script>