View unpublished pages or draft pages or published pages in SharePoint

Microsoft SharePoint Logo Sometimes it’s necessary to know the status of all the pages before a site is made live. It becomes especially difficult when a team works together on multiple pages and there are number of pages which might have not been published and site owner has to make sure all the pages are published.

We will create a view which can help a site owner to view unpublished pages or draft pages or published pages in SharePoint.

The technique is using the “Version” column to determine the decimal part of the “Version” by subtracting the integer part from the “Version”. So if there is any decimal value in the “Version” then it’s in unpublished or draft state.

Do note that this technique depends upon the “Document Version History” settings being “Create major and minor (draft) versions” for that library.

Document Version History
Document Version History settings

This involves two steps

  1. Add a calculated column which helps to determine the page state using version value.
  2. Create a new view or update an existing view to display the created calculated column.

Create column to know the page status

  1. Create a new column and name it “PageStatus” (We will later rename it to “Page Status”).
  2. Set the type to “Calculated”.
  3. Add the below formula and save the column settings. (Note: The “Version” column will not be available in “Insert Column:” pane so just copy paste the formula.)
=If((Version-INT(Version))<>0,"Draft","Published")
  1. In the library settings, click on the column to edit.
  2. Change the column name to “Page Status” and click “OK” button.
Create a column to show page status.
“Page Status” column creation

Library view to show the page status

We can either create a new view or modify an existing view to show the “Page Status”. For this all that needs to be done is add the “Page Status” column to the view.

Library view to show the “Page Status”

Prevent file download in SharePoint

Microsoft SharePoint Logo

Microsoft SharePoint LogoMicrosoft SharePoint Logo Sometimes in SharePoint there will be a scenario where users shouldn’t download documents, but yet should be able to view the documents. In many of the sites it’s mentioned that this is not possible. But in reality as of March 2020, this is possible.

Generally the permission level “View Only: Can view pages, list items, and documents. Document types with server-side file handlers can be viewed in the browser but not downloaded.” is not available by default. But the site collection feature “SharePoint Server Enterprise Site Collection features” when activated will enable this permissions level.

Note that this will work only for Microsoft Office files like Word, Excel, PowerPoint etc. Still users will be able to download other file type. The reason is SharePoint uses handler for viewing and editing Microsoft Office files which can prevent download.

Perform the following steps to enable the permission level

  1. Launch “Site collection features” under “Site Settings”.
  2. Activate “SharePoint Server Enterprise Site Collection features”.
  3. Go to the library’s settings and launch “Permissions for this document library”.
  4. Enable unique permissions.
  5. Then select the specific “SharePoint group” and click “Edit User Permissions”.
  6. Now you should be able to see the permission level ” View Only: Can view pages, list items, and documents. Document types with server-side file handlers can be viewed in the browser but not downloaded.”
  7. Check that permission and uncheck all other permissions.
  8. Now all the users within that group will only be able to view the document in web-viewer and will not be able to download.

Before applying permission

The “Download” menu is visible. Clicking “Open” will open the file in web viewer.

After applying permissions

The “Download” menu is not visible. Clicking “Open” will open the file in web viewer.

Remove the title banner from SharePoint modern page

Microsoft SharePoint Logo The title banner in the modern pages of SharePoint takes a lot of space.

Even if you try to switch to “Plain” title layout, the title area still will take some space.

To completely remove the space, you can run the following PnP PowerShell command with the ID of the page.

For more about PnP PowerShell, visit this link.

Set-PnPListItem -List SitePages –Identity <id> -Values @{"PageLayoutType"="Home"}

First connect to the site using the following command

Connect-PnPOnline https://tenant.sharepoint.com/sites/site-where-the-page-exists  

Then find out the ID of the page using the following command. This command assumes that the page is located within “SitePage” library.

Get-PnPListItem -List SitePages

Finally set the page’s layout type to “Home” by running the following command.

Set-PnPListItem -List SitePages –Identity <id> -Values @{"PageLayoutType"="Home"}

Now the title area is totally gone.

Get folder and files recursively in SharePoint using REST call

There was a simple requirement I came across for which a page should list all the files and folders in a SharePoint document library.

I came up with a solution using ODATA call. Following is the REST call I made to get the list of all folder and files.

/_api/web/Lists/GetByTitle(‘Documents’)/Items?$select=FileLeafRef,FileRef&$orderby=FileRef asc

Following is the code which quickly prints them out in a table. Just add this code to a script editor web-part.
Please make sure the URL is updated based on your site URL.

<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript">
    $.ajax({
        url: "<site url>/_api/web/Lists/GetByTitle('Documents')/Items?$select=FileLeafRef,FileRef&$orderby=FileRef asc",
        type: "GET",
        headers: {
            "Accept": "application/json;odata=verbose"
        },
        success: function (data, textStatus, xhr)
        {
            $.each(data.d.results, function (index, item)
            {
                // alert("The items in list are : " + item.FileRef);
                $("#table1 tbody").append("<tr><td>" + item.FileRef + "</td></tr>");
            })
        },
        error: function r(xhr, textStatus, errorThrown)
        {
            alert("error:" + JSON.stringify(xhr));
        }
    });
</script>

<table id="table1">
    <tbody></tbody>
</table>

Sharepoint disable drag and drop

In some scenarios we might need to disabled drag and drop in SharePoint sites.

The following code works when we need to disable a page with one document view.

Add the html code in content editor web part where the document view is there.

<style type="text/css">
    /*-- Hide Drag & Drop --*/    
    caption.ms-dragDropAttract {
        caption-side: bottom;
        display: none !important;
    }
</style>

<script type="text/javascript">
    /*-- Stop Drag & Drop --*/
    ExecuteOrDelayUntilScriptLoaded(function() {
        g_uploadType = DragDropMode.NOTSUPPORTED;
        SPDragDropManager.DragDropMode = DragDropMode.NOTSUPPORTED;
        SPDragDropManager.DargDropMode.style.display = "none";
    }, "DragDrop.js");
</script>

For pages with multiple document libraries when you want to target a specific library prepend the id of the web part div and an underscore e.g. WebPartWPQ4_

#WebPartWPQ4_ms-dnd-dropbox{ display: none !important; }

Source: https://sharepoint.stackexchange.com/questions/82805/how-can-i-disable-the-document-library-drag-and-drop-function

Open SharePoint Office documents in modal dialog

Sometimes we need Microsoft Office documents to be opened in dialogs instead of SharePoint’s default behavior which is opening the document in the same window or tab.

The following code helps in implementing this.

Note: This code only works for office documents. For pdf documents look at the previous article.

<!-- Put this code below the list view web part -->
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js">
</script>
<script type="text/javascript">
    $hrefVal = $("a[onclick*='return DispEx'][target!='_blank']").attr("href");
    $siteUrl = _spPageContextInfo.webServerRelativeUrl;

    $("a[onclick*='return DispEx'][target!='_blank']")
        .removeAttr("onclick")
        .attr("href", "javascript:OpenDocumentInDialogue(\"" + $siteUrl + "/_layouts/WopiFrame.aspx?action=default&sourcedoc=" + $hrefVal + "\")");

    function OpenDocumentInDialogue(href) {
        var o;
        $("body").append("<div id='docTemp' style='min-height:600px;min-width:800px;height:100%;overflow:hidden'><object data='" + href + "' width='100%' height='100%'></object></div>");
        o = {};
        o.html = $("#docTemp")[0];
        o.showMaximized = true;
        o.title = href.substring(href.lastIndexOf("/") + 1);
        o.dialogReturnValueCallback = OpenDocumentinDlgCallback;
        SP.UI.ModalDialog.showModalDialog(o);
    }

    function OpenDocumentinDlgCallback() {
        // do something here when the dialog closes
    }
</script>

 

Open SharePoint PDF documents in modal dialog

Sometimes we need PDF documents to be opened in dialogs instead of SharePoint’s default behavior which is opening the document in the same window or tab.

The following code helps in implementing this.

Note: This code only works for PDF documents. For office documents look at the next article.

<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
    $("a[href$='.pdf']").each(function() {
        $(this).removeAttr("onclick").attr("href", "javascript:OpenDocumentInDialogue(\"" + this.href + "\")");
    });

    function OpenDocumentInDialogue(href) {
        var o;
        $("body").append("<div id='docTemp' style='min-height:600px;min-width:800px;height:100%;overflow:hidden'><object data='" + href + "' width='100%' height='100%' type='application/pdf' ></object></div>");
        o = {};
        o.html = $("#docTemp")[0];
        o.showMaximized = true;
        o.title = href.substring(href.lastIndexOf("/") + 1);
        o.dialogReturnValueCallback = OpenDocumentInDialogueCallback;
        SP.UI.ModalDialog.showModalDialog(o);
    }

    function OpenDocumentInDialogueCallback() {
        // Do something here when the dialog closes
    }
</script>

 

Displaying SharePoint’s “Please wait…” or “Working on it…” dialog box

The following code helps in displaying the “Working on it…” dialog box available in SharePoint 2013 or SharePoint Online.

Before you being the background operation, call the function “RequestStarted“. Once the background operation has been completed, call the function “RequestEnded“.

function RequestEnded(sender, args) {
    try {
        waitDialog.close();
        waitDialog = null;
    } catch (ex) {}
};

function RequestStarted(sender, args) {
    var waitDialog;
    ExecuteOrDelayUntilScriptLoaded(ShowWaitDialog, "sp.js");
};

function ShowWaitDialog() {
    try {
        if (waitDialog == null) {
            waitDialog = SP.UI.ModalDialog.showWaitScreenWithNoClose('Processing...', 'Please wait while request is in progress...', 120, 440);
        }
    } catch (ex) {}
};

Source: Sharepoint Stackexchange

Change new item text in SharePoint

The following script changes the “new item” link button in SharePoint view form to whatever we desire.

Add either of the script to content editor web part.

Plain JavaScript version: (This code assumes that there is only one “new item” text in the entire page.)

<script>
    document.addEventListener("DOMContentLoaded",
        function () {
            ExecuteOrDelayUntilScriptLoaded(function () {
                var ReRenderListView_old = ReRenderListView
                ReRenderListView = function (b, l, e) {
                    ReRenderListView_old(b, l, e)
                    changeText()
                }
            }, "inplview.js")
            changeText()
        }
    );

    function changeText() {
        var element = document.querySelector('#idHomePageNewItem span:nth-child(2)')
        element ? (element.innerHTML = "Add item") : null
    }

</script>

jQuery version: (This code can replace any number of “new item” text)

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>

<script>
    $(document).ready(function () {

        var spans = document.getElementsByTagName("span");
        for (var i = 0; i < spans.length; i++) {
            if (spans[i].innerHTML == "new item") {
                spans[i].innerHTML = "add item";
                break;
            }
        }

    });

</script>

Source: sharepoint.stackexchange.com

Hide SharePoint list column

Sometimes we need to hide specific SharePoint columns in a list view webpart. The following code will help with that.
Make sure this code is placed in a JS file and referenced using JSLink webpart property.
Just replace the HideColumn function’s array parameters [“Title”, “Created By”] with necessary column’s display names.

(function () {
    var overrideCurrentContext = {};
    overrideCurrentContext.Templates = {};
    overrideCurrentContext.OnPostRender = PostRenderer;
    SPClientTemplates.TemplateManager.RegisterTemplateOverrides(overrideCurrentContext);
})();

function PostRenderer(ctx) {
    HideColumn(["Title", "Created By"],true);
}

function HideColumn(columns, hideOnlyHeader) {
    columns.forEach(function(columnName) {
        headerParentFirstNode = document.querySelectorAll("[displayname='" + columnName + "']")[0];
        if (headerParentFirstNode != undefined) {
            var header = headerParentFirstNode.parentNode;
            header.style.display = "none";
            if (!hideOnlyHeader) {
                var index = [].slice.call(header.parentNode.children).indexOf(header) + 1;
                for (var i = 0, cells = document.querySelectorAll("td:nth-child(" + index + ")"); i < cells.length; i++) {
                    cells[i].style.display = "none";
                }
            }
        }
    });
}