Pages

August 29, 2013

How to make a mandatory file attachment in list forms


Objective:
Enforce the user to upload a mandatory file attachment whenever he/she creates/edits a SharePoint list item. This can serve as a part of validation process.
 
Analysis:

First, let’s see how attachments are added to the form.
When you attach files in list forms, the attachments part will appear as a row for each file item:



When hitting F12 in IE, you will notice that files are fitted inside spans in the attachments table:

Solution:

The idea is to override the PreSaveAction() method and iterate through span elements inside the attachments table to check if each item meets our rule for required file. The SharePoint list item will not be save until the PreSaveAction() returns true value indicating there is at least one attachment matching the required criteria.

For example: we want the file to include the phrase "RequiredFormName", with ".docx" as file extension.

In your NewForm.aspx or EditForm.aspx, add a CEWP amd insert the following code into it:
<script>

function strEndsWith(str, suffix) {
return str.match(suffix+"$")==suffix;
}

function PreSaveAction() {
var attachment = document.getElementById("idAttachmentsTable");
var linkname;
var phrase1 = "RequiredFormName";
var phrase2 = ".docx";


// no attachment files
if (attachment == null || attachment.rows.length == 0)
{
document.getElementById("idAttachmentsRow").style.display = 'none';
alert("No attachments found. Please attach the required file.");
return false;
}

else
{
// searching in current uploaded and selected files
var Links= document.getElementById('idAttachmentsTable').getElementsByTagName('span');
for (var i = 0, l = Links.length; i < l; i++)
{
                                linkname = Links[i].textContent || Links[i].innerText;

                                linkname = linkname.toLowerCase();

                                phrase1 = phrase1.toLowerCase();

phrase2 = phrase2.toLowerCase();

if (linkname.indexOf(phrase1) != -1 && strEndsWith(linkname, phrase2))
{
                                                // required attachment found
return true;
}
}

// required attachment is not available
alert("Please attach the required file.");
return false;
}
}
</script>


You can replace the highlighted portions 1 & 2 strings with your custom file name & extension respectively.

Have a nice day!

No comments:

Post a Comment