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.

Folder Navigation for List View WebPart in SharePoint 2013 and SharePoint Online

Folder Navigation for List View WebPart in SharePoint 2013 and SharePoint Online.
Step 1: Create a notepad file and save as "FolderNavigation.html" and below code to this file.
<!DOCTYPE html>
<html>
<head>
    <style type="text/css">
        .ms-WPHeader .breadcrumbs {
            display: block;
            font-style: italic;
        }
        .ms-WPHeader .breadcrumbs, .ms-WPHeader .breadcrumbs a {
            font-size: 0.8em;
            color: #D1D1D1;
        }
    </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">
        _spBodyOnLoadFunctionNames.push("doBreadCrumbs");//execute after DOM loaded
        function doBreadCrumbs() {
            var rootStr = getUrlParam('RootFolder');
            if (rootStr != '') {
                //For SharePoint online: '.ms-webpart-titleText a'
                //For SharPoint 2013: '.ms-WPTitle a'
                var webpartHeaders = document.querySelectorAll('.ms-webpart-titleText a');
                for (var i = 0; i < webpartHeaders.length; i++) {
                    var webpartHeader = webpartHeaders[i];
                    var link = decodeURIComponent(webpartHeader.getAttribute('href'));
                    if (rootStr.indexOf(link) != -1) {
                        var path = rootStr.replace(link, '');
                        var basepath = rootStr.replace(path, '');
                        var breadcrumb = '<span class="breadcrumb">';
                        breadcrumb += '<a href="' + location.pathname + '">  Home</a>';
                        var folders = path.split('/');
                        for (var i = 1; i < folders.length; i++) {
                            var currentfolder = folders[i];
                            basepath += "/" + currentfolder;
                            var folderlink = decodeURIComponent(window.location.search).replace('RootFolder=' + decodeURIComponent(rootStr), 'RootFolder=' + decodeURIComponent(basepath));
                            breadcrumb += ' &gt; <a href="' + folderlink + '">' + currentfolder + '</a>';
                        }
                        breadcrumb += '</span>';
                        webpartHeader.parentNode.innerHTML += breadcrumb;
                    }
                }
            }
        }
        function getUrlParam(name) {
            name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
            var regexS = "[\\?&]" + name + "=([^&#]*)";
            var regex = new RegExp(regexS);
            var results = regex.exec(window.location.search);
            if (results == null) return "";
            else return decodeURIComponent(results[1].replace(/\+/g, " "));
        }
    </script>
</head>
<body>
</body>
</html>
Step 2: Upload this "FolderNavigation.html" file into "Site Assets" Library.
Step 3: Add "Document Library" List WebPart in a page and make sure Chrome type should be any one of these.
1. Default
2. Title and border
3. Title only
Step 4:  Add Content Editor WebPart, Edit Content Editor WebPart and provide Content Link as "/sites/dev/SiteAssets/foldernavigation/foldernavigation.html"
Content Editor WebPart Chrome Type: None.
Step 5:

Featured Post

Mention a Channel or Team – Power Automate

Mention a Channel or Team – Power Automate graph.microsoft.com/v1.0/teams/{teamId}/channels/{channelId}/messages Channel: ---------- {   ...

Popular posts