For a while now I've been meaning to write a blog post about the SharePoint Image field. For those who don't know, without publishing turned on, the only way to add an image to an item in SharePoint is by using the Image field. However the name can be a bit misconceiving for someone who hasn't used it before... because it really just holds the url to an image and displays the image when in a SharePoint view. My gripe with the Image field isn't with how it renders an image but why SharePoint didn't provide a way to search for an image to add to an item like they did for the "Publishing Image Field". The only way to connect an image to an item without publishing is to find the URL of an item and past it into the Image URL field. Well what happens if the image isn't in SharePoint yet and you want to upload an image and add it to a library at the same time? Well, that is exactly what you have to do. You must go to the Image library and add your image and then traverse back to the list item for which you wanted to add link that image. Well I have come up with a solution to this scenario.
Using JSLink, Jquery and the OOB Upload form we can provide a means of uploading an image file and automatically linking it to the current item we are working on. Consider the following JS file that is running on your default NewForm.aspx.
Within the $(document).ready function, I have bound a click a click event to the text field on the NewForm for the current item. This ensures that when a use clicks on the SharePoint image field, the JQuery event will fire and load a modal dialog. If you look at the last parameter in openInDialog() you will see that I have a reference to "../_layouts/15/Upload.aspx." This is the default upload form for SharePoint.
The openInDialog() function has a delegate function called "CloseDialogCallback" which is the event that will fire when the user saves or closes the dialog. You'll see I have two parameters for this function "dialogResult" and "returnValue". The first will give us the action the user took from the dialog box and the second parameter is going to give us information relative to the Upload.aspx form. Once we get the information relative to the new image file, we just set the text field with the URL of that new image.
To piece this together. A user will click on the text field and the JQuery event will fire a modal dialog that loads the default Upload.aspx page in SharePoint as shown below.
Once the user selects the Image, presses "Ok" and completes the Upload process... the CloseDialogCallback will fire and you'll have a returnValue with all the properties of the new image.
We then build an absolute url to the image and set the URL of the Image field using JQuery. Voila! Now, we have a seamless and linear process of uploading images and attaching them to current items we are viewing without ever leaving the form!