Friend : I have a hyperlink column in a SharePoint list. When i click on it, the link takes me to a new page. I want it to open in a modal dialog. Is it possible?How do you do it?

Me : Oops, I forgot how I implemented it. Let me check and get back to you.

So, I was faced yet again with this requirement and it took me some time to think how I had done it earlier. It was one those moments in a programmer’s life where you know it is possible, you know you have done it but you’ve simply forgotten how you did it.

After finding out how I had done it, I decided that I better write about it.

The requirement

We have a list with hyperlink column. On clicking the link a page should open in modal dialog.

The Solution & The hurdles

A major hurdle here is that the SharePoint hyperlink column will not allow you to insert JavaScript. And you cannot open the page in a modal dialog without having to write JavaScript.

So, what do we do? JSLink to the rescue

Step 1 :
Create the basic hyper link column and insert some values. You should now have a list that looks like the below screen shot

List View

List View

Step 2 :
Create a JavaScript file as show below and save it as ListViewEditPopUp.js or any other name that you might like.


/*Code to open Modal Dialog*/
function OpenDialog(URL) {
var options = SP.UI.$create_DialogOptions();
options.url = URL;
options.autoSize = true;
options.width = auto;
options.height = auto;
options.dialogReturnValueCallback=RefreshOnDialogClose;
options.title = " "
SP.UI.ModalDialog.showModalDialog(options);
}

(function(){
var ctx = {};
ctx.Templates = {};
ctx.Templates.Fields = {
"ModifyDetails":{"View":insHyperLink /*Modify the column value*/ }
};
SPClientTemplates.TemplateManager.RegisterTemplateOverrides(ctx);
})();

function insHyperLink(ctx){
var currentItem = ctx.CurrentItem["ModifyDetails"];
if(currentItem!=="")
return "<a href=\"javascript:OpenDialog('"+currentItem+"')\">Edit</a>"; /*Surround function with code that will allow us to open the link in a modal dialog*/
}

 

Step 3 :
Edit the list view webpart. Go to the webpart properties section and locate the Miscellaneus tab. Insert the link to your JavaScript file created in step 2

List View WebPart Properties

List View WebPart Properties

I have used the link

~site/_catalogs/masterpage/ListViewEditPopUp.js

as I had saved it at this location. You can use any other location you prefer, just make sure the list view webpart can reach the file.

Save all your changes and test. The link should now open in a modal dialog.