Monday, May 15, 2017

Check if login user exists in a particular SharePoint group or not and create folder in Document Library using REST API using jQuery Ajax in SharePoint

Check if login user exists in a particular SharePoint group or not and create folder in Document Library using REST API using jQuery Ajax in SharePoint.

Step1: Create a SharePoint group as "Developer Site Owners" and go to group settings and make sure "Everyone" radio button select in "Group Settings". Otherwise user will get prompt credential window.

Step2: Open Notepad file and add below code then save as "CheckUserInGroupAndCreateFolder.html". Then upload this file into Site Assets in SharePoint.
<!DOCTYPE html>
<html>
<head>
    <style type="text/css">
        input[id=newFolderName] {
            padding: 12px 20px;
            margin: 8px 0;
            display: inline-block;
            border: 1px solid #ccc;
            border-radius: 4px;
            box-sizing: border-box;
        }
        input[id=createNewFolder] {
            background-color: #4CAF50;
            color: white;
            padding: 14px 20px;
            margin: 8px 0;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }
        input[id=createNewFolder]:hover {
            background-color: #45a049;
        }
        div#mainDiv {
            border-radius: 5px;
            background-color: #f2f2f2;
            padding: 0px;
        }
    </style>
    <!-- <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> -->
    <script type="text/javascript" src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.2.min.js"></script>
    <script type="text/javascript">
        var GroupOwners = "Developer Site Owners";
        var isExistInGroupOwners = false;
        var isFolderCanCreate = false;
        var ParentFolderUrl = null;
        var ParentRootFolderUrl = "/Shared Documents";
        $(document).ready(function () {
            $("#mainDiv").hide();
            isExistInGroup(GroupOwners);
            if (isExistInGroupOwners) { isFolderCanCreate = isExistInGroupOwners; }
            else { isFolderCanCreate = false; }
            if (isFolderCanCreate) { $("#mainDiv").show(); } else { $("#mainDiv").hide(); }
            $.ajaxSetup({ cache: false });
        });
        function isExistInGroup(groupName) {
            $.ajax({
                url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/sitegroups/getByName('" + groupName + "')/Users?$filter=Id eq " + _spPageContextInfo.userId,
                method: "GET",
                headers: { "Accept": "application/json; odata=verbose" },
                async: false,
                cache: false,
                success: function (data) {
                    if (data.d.results.length > 0) {
                        if (groupName.toLowerCase().trim() == GroupOwners.toLowerCase().trim())
                        { isExistInGroupOwners = true; }
                    } else {
                        if (groupName.toLowerCase().trim() == GroupOwners.toLowerCase().trim())
                        { isExistInGroupOwners = false; }
                    }
                },
                error: function () { }
            });
        }
        function funCreateNewFolder() {
            if (isFolderCanCreate) {
                if ($("#newFolderName").val() != null && $("#newFolderName").val().length > 0) {
                    onReadyCallFun($("#newFolderName").val());
                } else { alert("Please enter folder name."); }
            }
        }
        function onReadyCallFun(newFolderName) {
            if (window.location.href.length > 0 && window.location.href.indexOf('RootFolder=') != -1) {
                ParentFolderUrl = window.location.href.split('RootFolder=')[1];
                if (ParentFolderUrl.length > 0 && ParentFolderUrl.indexOf('&') != -1) {
                    ParentFolderUrl = ParentFolderUrl.split('&')[0];
                }
            }
            if (ParentFolderUrl != null) {
                ParentFolderUrl = decodeURIComponent(ParentFolderUrl);
                if (ParentFolderUrl.indexOf('+') != -1) { ParentFolderUrl = ParentFolderUrl.split("+").join(" "); }
                createFolder(ParentFolderUrl, newFolderName);
            }
            else { createFolder(ParentRootFolderUrl, newFolderName); }
        }
        function createFolder(p_FolderUrl, p_newFolderName) {
            var url = null;
            if (p_FolderUrl.toLowerCase().trim().indexOf(_spPageContextInfo.webServerRelativeUrl.toLowerCase().trim()) != -1) {
                url = _spPageContextInfo.webAbsoluteUrl + "/_api/web/getfolderbyserverrelativeurl('" + p_FolderUrl + "')/folders";
            }
            else { url = _spPageContextInfo.webAbsoluteUrl + "/_api/web/getfolderbyserverrelativeurl('" + _spPageContextInfo.webServerRelativeUrl + p_FolderUrl + "')/folders"; }
            jQuery.ajax({
                url: url,
                type: "POST",
                data: JSON.stringify({ '__metadata': { 'type': 'SP.Folder' }, 'ServerRelativeUrl': p_newFolderName }),
                headers: {
                    "X-RequestDigest": $("#__REQUESTDIGEST").val(),
                    "accept": "application/json; odata=verbose",
                    "content-type": "application/json; odata=verbose"
                },
                async: false,
                cache: false,
                success: function (data) { },
                error: function () { }
            });
        }
    </script>
</head>
<body>
    <div id="mainDiv">
        <input type="text" id="newFolderName" name="newFolderName" placeholder="folder name..">
        <input type="submit" id="createNewFolder" value="Create New Folder" onclick="funCreateNewFolder()">
    </div>
</body>
</html>

Step3: Upload this file "CheckUserInGroupAndCreateFolder.html" into Site Assets Library in SharePoint.

Step4:In any .aspx page add "Document Library" list view WebPart and "Content Editor" WebPart.
Edit Content Editor WebPart and refer below script url "/sites/dev/SiteAssets/createfolder/CheckUserInGroupAndCreateFolder.html"

Step5: Test the code.

No comments:

Post a Comment