-->
Showing posts with label SharePoint. Show all posts

Create Folders and Sub Folders using SharePoint REST web services

We can able to create the SharePoint List/Library Folders using REST web services.

<script type="text/javascript">

function CreateFolder (){
    var url_web;
    var pictureLibrary
    var folder_name;
    var folder_path;
    var mainfolder = ["Baikalit-SKC", "MC-Irkutsk", "Orion", "PM-Auto", "Sot motors", "STS-avtomobili"];
   
    var arr = ["0_Dealer general info", "1_Sales", "2_Aftersales", "3_Network", "4_Finance", "5_Marketing", "6_Training"];
    url_web = _spPageContextInfo.webAbsoluteUrl;
    pictureLibrary = 'Dealer Performance Monitor';
    //folder_name = 'jasonscript';
    for ( var j = 0, M = mainfolder.length; j < M; j++ ) {
        for ( var i = 0, l = arr.length; i < l; i++ ) {
            folder_path = pictureLibrary + '/9_Siberian FD/'+mainfolder[j]+'/' + arr[i];
            jQuery.ajax({
                'url' : url_web + "/_api/Web/Folders/Add('"+ folder_path + "')",
                'type' : 'POST',
                'headers' : {
                    'accept' : 'application/json; odata=verbose',
                    'content-type' : 'application/json; odata=verbose',
                    'X-RequestDigest' : $('#__REQUESTDIGEST').val()
                },
                'success' : function (evt){
                    // folder has been created
                   
                },
                'error' : function (jqXHR, textStatus, errorThrown){
                    // handle the error
                    alert(errorThrown);
                }
            });
        }
    }
    alert("Created Folder");
 }
</script>
<input type="button" Name="Submit" value="Create Sub Folder" onclick="CreateFolder();"></input>
<table border="0" cellpadding="0" width="100%" id='listPermsTable'> </table>

SharePoint error duplicate file ulpoad error

SharePoint file upload / attachment control has a very big issue is " SharePoint List will not allow to attach duplicate files."

If we used custom file upload control we dont have direct way to restrict to upload duplicate files.
we will get the below error message.
"Fail to get the value of the attachments column. A file with same name is already exists".
 

We can handle this error by using JQuery.

// it is the same duplicate check code
        var foundDuplication = false;

        $('#idAttachmentsTable').find('tbody').find('tr').each(function () {
            var existingFileName = $(this).find('.ms-vb').find('a').text();
            // if the existingFileName is empty then the attachment was uploaded in this session
            // that is, it is not saved yet
            if (existingFileName == '') {
                var existingFilePath = $(this).find('.ms-vb').find('span').text();
                existingFileName = existingFilePath.replace(/^.*[\\\/]/, '');
            }

            if (newFileName == existingFileName) {
                foundDuplication = true;
                return false;
            }
        });

        if (foundDuplication) {
            alert("A file with name '" + newFileName + "' is already attached to this item.");
           // $('#attachmentsOnClient').find('input').last().clone(true).remove();
   //$('#attachmentsOnClient').find('input').last().val('');
   var lastupp = $('#attachmentsOnClient').find('input').last();
   //$('#attachmentsOnClient').find('input').last().replaceWith(($('#attachmentsOnClient').find('input').last()).clone(true));
   lastupp.replaceWith((lastupp).clone(true));
   document.getElementById("onetidIOComment").value = "";
   

        }
Here we have only one option to replace the last uploaded control with new one. The internal functionality of the file upload control is, when ever a file is uploaded, SharePoint will hide the existing upload control and will create new upload control to upload another file.
Now we will include all feature step by Step

Step: 1
   
SharePoint Custom file attachment control

Step: 2
 Client Validation for SharePoint file Upload Control

Step: 3
 SharePoint add comments for each attached document



Client Validation for SharePoint file Upload Control


we can set client side validation for SharePoint file upload / attachment control.
we can do validation on
 1. Restricted file types
2.  Max file Size
3. Min File Size


function CustomUpload() {

    var newFilePath = $('#attachmentsOnClient').find('input').last().val();   
    var newFileName = TrimWhiteSpaces(newFilePath).replace(/^.*[\\\/]/, '');
 var restrictype = ".ade|\\.adp|\\.asa|\\.ashx|\\.asmx|\\.asp|\\.bas|\\.bat|\\.cdx|\\.cer|\\.chm|\\.class|\\.cmd|\\.com|\\.config|\\.cnt|\\.cpl|\\.crt|\\.csh|\\.der|\\.dll|\\.exe|\\.fxp|\\.gadget|\\.grp|\\.hlp|\\.hpj|\\.hta|\\.htr|\\.htw|\\.ida|\\.idc|\\.idq|\\.ins|\\.isp|\\.its|\\.jse|\\.json|\\.ksh|\\.lnk|\\.mad|\\.maf|\\.mag|\\.mam|\\.maq|\\.mar|\\.mas|\\.mat|\\.mau|\\.mav|\\.maw|\\.mcf|\\.mda|\\.mdb|\\.mde|\\.mdt|\\.mdw|\\.mdz|\\.ms-one-stub|\\.msc|\\.msh|\\.msh1|\\.msh1xml|\\.msh2|\\.msh2xml|\\.mshxml|\\.msi|\\.msp|\\.mst|\\.ops|\\.pcd|\\.pif|\\.pl|\\.prf|\\.prg|\\.printer|\\.ps1|\\.ps1xml|\\.ps2|\\.ps2xml|\\.psc1|\\.psc2|\\.pst|\\.reg|\\.rem|\\.scf|\\.scr|\\.sct|\\.shb|\\.shs|\\.shtm|\\.shtml|\\.soap|\\.stm|\\.svc|\\.url|\\.vb|\\.vbe|\\.vbs|\\.vsix|\\.ws|\\.wsc|\\.wsf|\\.wsh|\\.xamlx";
    var maxFileNameLength = 128; 
 var maxFileSize = 250;
 //var extension = newFileName.replace(/^.*\./, '');
  var myFSO = new ActiveXObject("Scripting.FileSystemObject");
  var thefile = myFSO.getFile(newFilePath);
  var filesize = Math.round((thefile.size/1048576),2);
    
   
 
    var match = (new RegExp('[~#%\&{}+\|]|\\.\\.|^\\.|\\.$')).test(newFileName);
  var filetypes = (new RegExp(restrictype)).test(newFileName);
  
    if (match) {
        alert("Ivalid file name. The name of the attached file contains invalid characters.");
    }
    else if (newFileName.length > maxFileNameLength) {
        alert("Ivalid file name. The name of the attached file is too long.");
    }
  else if (newFileName.length <= 0) {
        alert("Please select a file");
    }
 else if(filetypes) {
  alert("Ivalid file type. The attached file type is restricted by SharePoint.");
   return false;
 } 
 else if(filesize > maxFileSize) {
  alert("The attached file size exceeds size limit of 250MB.");
   return false;
   
 } 
} 
Now we will include all feature step by Step

Step: 1
   
SharePoint Custom file attachment control

Step: 2
 Stop Showing duplicate file upload Error

Step: 3
 SharePoint add comments for each attached document



Get Current Loggedin User SharePoint Group Names using JQuery




To get the current user logged in SharePoint group name.
If you trying to iterate all the SharePoint groups the user may get access denied error.
Note: CSOM doesn't have impersonation facelity.

Here we can get only the specific group and find to get the logged user name


ExecuteOrDelayUntilScriptLoaded(IsCurrentUserHasContribPerms, 'SP.js');
function IsCurrentUserHasContribPerms() 
{
    IsCurrentUserMemberOfGroup("Members", function (isCurrentUserInGroup) 
    {
        if(isCurrentUserInGroup)
        {
            // The current user is in the [Members] group!
        }
    });
   

}

function IsCurrentUserMemberOfGroup(groupName, OnComplete) 
{

    var currentContext = new SP.ClientContext.get_current();
    var currentWeb = currentContext.get_web();

    var currentUser = currentContext.get_web().get_currentUser();
    currentContext.load(currentUser);

    var allGroups = currentWeb.get_siteGroups();
    currentContext.load(allGroups);

    var group = allGroups.getByName(groupName);
    currentContext.load(group);

    var groupUsers = group.get_users();
    currentContext.load(groupUsers);

    currentContext.executeQueryAsync(OnSuccess,OnFailure);

    function OnSuccess(sender, args) {
        var userInGroup = false;
        var groupUserEnumerator = groupUsers.getEnumerator();

        var OwnergroupUserEnumerator = OwnergroupUsers.getEnumerator();
   var statusval= $("select[title='ApprovalStatus'] option:selected").val();
        while (OwnergroupUserEnumerator.moveNext()) {
            var OwnergroupUser = OwnergroupUserEnumerator.get_current();
            if (OwnergroupUser.get_id() == currentUser.get_id()) {
                userInGroup = true;
               
                break;
            }
        }



        OnComplete(userInGroup);
    }

    function OnFailure(sender, args) {
        OnComplete(false);
    }    
}

SharePoint CSOM Validate People Picker fields

Get SharePoint People Picker Value using Java Script


var PickerPerson = getPickerInputElement("ff13"); // Here ff13 is your people picker control ID

function getPickerInputElement(identifier) {
var tags = document.getElementsByTagName('DIV');
for (var i=0; i < tags.length; i++) {
var tempString = tags[i].id;
if ((tempString.indexOf(identifier) > 0) && (tempString.indexOf('UserField_upLevelDiv') > 0))        {
var innerSpans = tags[i].getElementsByTagName("SPAN");
for(var j=0; j < innerSpans.length; j++) {
if(innerSpans[j].id == 'content') {
return innerSpans[j].innerHTML;
}
}
}
}
return null;
}

Validate and compare the people picker values..

<script type="text/javascript">

function PreSaveAction(){

var OwnerVal = getPickerInputElement("ff4");
var ManagerVal = getPickerInputElement("ff5");
if(OwnerVal == ManagerVal){
alert("Please enter different names.");
return false;
}
else{
return true;
}
}

function getPickerInputElement(identifier) {
var tags = document.getElementsByTagName('DIV');
for (var i=0; i < tags.length; i++) {
var tempString = tags[i].id;
if ((tempString.indexOf(identifier) > 0) && (tempString.indexOf('UserField_upLevelDiv') > 0)){
var innerSpans = tags[i].getElementsByTagName("SPAN");
for(var j=0; j < innerSpans.length; j++) {
if(innerSpans[j].id == 'content') {
return innerSpans[j].innerHTML;
}
}
}
}
return null;
}

</script>

SharePoint Client Object Model using JQuery and SPServices


Add, Select, Update and Delete List items using JQuery.

JQuery using  SPServices:

<script src="/_LAYOUTS/MyJS/jquery-1.6.1.min.js" type="text/javascript"></script>
<script src="/_LAYOUTS/MyJS/jquery.SPServices-2014.01.min.js" type="text/javascript">

</script><script language="javascript" type="text/javascript">

$(document).ready(function() {
    $("#createitem").click(function() {

var valtitle = $("#txtTitle").val();
var valcol = $("#txtcol123").val();

CreateNewItem(valtitle, valcol);
               

    });

$("#updateItem").click(function() {

var valtitle = $("#txtTitle").val();
var valcol = $("#txtcol123").val();
                var itemID = $("#txtID").val();

                UpdateItem(itemID, valtitle, valcol);

    });

$("#getItem").click(function() {

var itemID = $("#txtID").val();

                GetSingleItem(itemID);

    });

});

Create New List Item:


function CreateNewItem(valtitle, valcol) {
    $().SPServices({
        operation: "UpdateListItems",
        async: false,
        batchCmd: "New",
        listName: "list123",
        valuepairs: [["Title", valtitle], ["_x0063_ol123", valcol]],
        completefunc: function(xData, Status) {
          alert("Item Created!");
        }
    });
}

Update List Item:

function UpdateItem(itemID, valtitle, valcol)

    {
        $().SPServices({
            operation: "UpdateListItems",
            async: false,
            listName: "list123",
            ID: itemID,
            valuepairs: [["Title", valtitle], ["_x0063_ol123", valcol]],
            completefunc: function(xData, status){
               alert("Item Created!");
               }
        });
    }

Get List Item:

function GetSingleItem(itemID)

    {
        $().SPServices({
            operation: 'GetListItems',
        async: false,
        //debug: true,
        listName: 'list123',
        CAMLViewFields: '<ViewFields><FieldRef Name="Title" /><FieldRef Name="_x0063_ol123" /></ViewFields>',
        CAMLQuery: '<Query><Where><Eq><FieldRef Name="ID"/><Value Type="Counter">' + itemID + '</Value></Eq></Where></Query>',
        completefunc: function(xData, Status) {

            $(xData.responseXML).SPFilterNode("z:row").each(function() {
                $("#txtTitle").val($(this).attr("ows_Title"));
                $("#txtcol123").val($(this).attr("ows_col123"));
            });
        }        });
    }
</script>

HTML :

ID:<br/>
<input name="txtID" id="txtID" type="text"/> <br/>
Title:<br/>
<input name="txtTitle" id="txtTitle" type="text"/> <br/>
Col 123:<br/>
<input name="txtcol123" id="txtcol123" type="text"/> <br/>
<input id="createitem" type="button" value="Create Item"/>
<input id="updateItem" type="button" value="Update Item"/>
<input id="getItem" type="button" value="Get Single Item"/>