Showing posts with label 2013. Show all posts
Showing posts with label 2013. Show all posts

Wednesday, February 18, 2015

Deploying Managed Metadata Fields declaratively in SharePoint - Tips and Tricks

In this article, we will see how we can deploy Managed metadata fields in a declarative way in SharePoint 

A managed metadata column lets you control the information that people can enter into a column. Users select the terms or phrases that they enter in the column from a pre-defined set of managed terms.

The challenge comes when you want to provision your custom managed metadata navigation field in a declarative way, and adding this column to a content type or a list instance without losing all the powerful features that comes along using this field type.

Out of the Box, if you added a managed column to your list SharePoint performs some actions behind the scene:
  1. Creates a hidden note field attached to your column
  2. Attached your list to two event receivers to update the taxonomy hidden list .
  3. Fills in some properties related to the current web and taxonomy list id
  4. Creates a taxonomy search managed  property after a full crawl that could be used as a refiner or even as a category column if you are planning to use the Product Catalog model.
So there are a lot of articles explaining how to deploy Managed Metadata Fields declarative in SharePoint, but they are scattered :) , so I decided to aggregate all the tips and tricks to cover this task.

  • Taxonomy Field  declarative XML, no tricks here :)

<Field ID="{20A3C69E-FFFB-43F4-BBDF-2D22BAF0EB84}"
         Type="TaxonomyFieldType"
         DisplayName="$Resources:myResourceFile,EventType"
         ShowField="Term1033"
         Required="TRUE"
         EnforceUniqueValues="FALSE"
         Group="Custom"
         StaticName="CustomEventType"
         Name="CustomEventType"
         Filterable="TRUE"
         Sortable="TRUE" />


  • SharePoint creates a hidden note field to be field with selected values while filling the taxonomy field, here comes the tricky part, while adding your custom field to the list you MUST add this hidden field along with it, The Display name should follow the following convention 'TaxonomyField_0' and the static name should follow the following convention 'TaxononmyFieldTaxHTField0', without following this conventions SharePoint search will not generate the crawled property for your custom column 'ows_taxId_CustomEventType', and for sure will not create the managed property 'owstaxidKataraEventType' 

<Field ID="{09F37A61-50FE-413E-941F-3BEE2A1B5BF8}"
         Name="CustomEventTypeTaxHTField0"
         StaticName="KataraEventTypeTaxHTField0"
         SourceID="http://schemas.microsoft.com/sharepoint/v3/fields"
         Type="Note"
         DisplayName="CustomEventType_0"
         Group="Katara"
         Hidden="TRUE" />
  • After declaring the schema of both field you should get them connected together, and should attach the created column to a specific Term Set and specific Term to choose from as a source, this could be achived by adding a feature event receiver using the following code snippet.

SPSite site = properties.Feature.Parent as SPSite;
Guid eventFieldId = new Guid("{20A3C69E-FFFB-43F4-BBDF-2D22BAF0EB84}");

if (site.RootWeb.Fields.Contains(eventFieldId))
{
 TaxonomySession session = new TaxonomySession(site);
 if (session.TermStores.Count != 0)
 {
  var termStore = session.TermStores["Managed Metadata Serivce"];
  var group = termStore.Groups["YOUR GROUP NAME"];
  var termSet = group.TermSets["YOUR TERM SET NAME"];

  var eventTypeTerm = termSet.Terms["THE TERM NAME CONTAINING YOUR VALUE"];

  TaxonomyField eventField = site.RootWeb.Fields[eventFieldId] as TaxonomyField;
  
  //Attach the note field to the taxonomy field
  eventField.TextField = new Guid("{09F37A61-50FE-413E-941F-3BEE2A1B5BF8}"); 

  // Connect to MMS
  eventField.SspId = termSet.TermStore.Id;
  eventField.TermSetId = termSet.Id;
  eventField.TargetTemplate = string.Empty;
  eventField.AnchorId = eventTypeTerm.Id;
  eventField.LookupWebId = site.RootWeb.ID;
  
  if (eventField.TypeAsString == "TaxonomyFieldTypeMulti")
   ageGroupField.AllowMultipleValues = true;
   
  eventField.Update();
 }
}
  • In this stage we have our field provisioned and added to our site as a site column, the next step is to add it to a content type, the trick here is we must add two hidden fields 'TaxCatchAll' & 'TaxCatchAllLabel' fields,If it doesn’t, then you won’t get facets showing up correctly in faceted search. Note that not having the TaxCatchAll and TaxCatchAllLabel pair of columns in your list or library or content type can cause that - See more at: http://magenic.com/BlogArchive/CorrectlyProvisioningManagedMetadataTaxonomyF#sthash.hlkj6Xqo.dpuf
  •  so our field references will be like the following 

<FieldRef ID="{20A3C69E-FFFB-43F4-BBDF-2D22BAF0EB84}" DisplayName="$Resources:FILENAME_Columns,EventType;" Required="TRUE" Name="CustomEventType" Filterable="TRUE" Sortable="TRUE" />
<FieldRef ID="{09F37A61-50FE-413E-941F-3BEE2A1B5BF8}" DisplayName="CustomEventType_0" Hidden="TRUE" Name="CustomEventTypeTaxHTField0" />
<FieldRef ID="{f3b0adf9-c1a2-4b02-920d-943fba4b3611}" DisplayName="Taxonomy Catch All Column" Required="FALSE" Hidden="TRUE" Name="TaxCatchAll" Sealed="TRUE" Sortable="FALSE" />
<FieldRef ID="{8f6b6dd8-9357-4019-8172-966fcd502ed2}" DisplayName="Taxonomy Catch All Column1" Required="FALSE" Hidden="TRUE" Name="TaxCatchAllLabel" ReadOnly="TRUE" Sealed="TRUE" Sortable="FALSE" />
  •  Now we come to the next trick, referencing those columns to a list template in the schema.xml file , the trick here is to declare the TaxHiddenList  'TaxCatchAll' & 'TaxCatchAllLabel' correctly to the the list schema, those fields are a lookup columns so they need the information list (source), following is the definetion, NOTE the List attribute. 

<Field Type="LookupMulti" DisplayName="Taxonomy Catch All Column" StaticName="TaxCatchAll" Name="TaxCatchAll" ID="{f3b0adf9-c1a2-4b02-920d-943fba4b3611}" ShowInViewForms="FALSE" List="Lists/TaxonomyHiddenList" Required="FALSE" Hidden="TRUE" CanToggleHidden="TRUE" ShowField="CatchAllData" SourceID="{1e46f7fe-3764-40b5-abd1-1746c716214b}" Mult="TRUE" Sortable="FALSE" AllowDeletion="TRUE" Sealed="TRUE" Version="2" />
<Field Type="LookupMulti" DisplayName="Taxonomy Catch All Column1" StaticName="TaxCatchAllLabel" Name="TaxCatchAllLabel" ID="{8f6b6dd8-9357-4019-8172-966fcd502ed2}" ShowInViewForms="FALSE" List="Lists/TaxonomyHiddenList" Required="FALSE" Hidden="TRUE" CanToggleHidden="TRUE" ShowField="CatchAllDataLabel" FieldRef="{F3B0ADF9-C1A2-4b02-920D-943FBA4B3611}" SourceID="{1e46f7fe-3764-40b5-abd1-1746c716214b}" ReadOnly="TRUE" Mult="TRUE" Sortable="FALSE" AllowDeletion="TRUE" Sealed="TRUE" Version="2" />

  • Finally, we need to attache the "TaxonomyItemSynchronousAddedEventReceiver" & "TaxonomyItemUpdatingEventReceiver" to update all the hidden fields.

<Receiver>
  <Name>TaxonomyItemSynchronousAddedEventReceiver</Name>
  <Type>ItemAdding</Type>
  <Assembly>Microsoft.SharePoint.Taxonomy, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c</Assembly>
  <Class>Microsoft.SharePoint.Taxonomy.TaxonomyItemEventReceiver</Class>
  <SequenceNumber>10000</SequenceNumber>
</Receiver>
<Receiver>
  <Name>TaxonomyItemUpdatingEventReceiver</Name>
  <Type>ItemUpdating</Type>
  <Assembly>Microsoft.SharePoint.Taxonomy, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c</Assembly>
  <Class>Microsoft.SharePoint.Taxonomy.TaxonomyItemEventReceiver</Class>
  <SequenceNumber>10000</SequenceNumber>
</Receiver>

Now you are all set to enjoy many many features and ideas that this colum type offers :)

Thursday, September 25, 2014

Using Knockout and CSOM (Client Side Object Model) for pages libraries and binding the output in a jcarousel Slider - The full Example

KnockoutJS is a fantastic library when you are looking for a drop-in enhancement that brings in client side data-binding and applies the Model-View-View-Model design pattern to your websites.
Knockout works with a ViewModel that can either be a JS object or a JS function. Either ways, your ViewModel is your data source. Using Knockout, you can bind DOM elements to your model using a declarative syntax. Knockout also provides Templating (for repetitive structures in a web page) and dependency tracking using ko.observableArray. With dependency tracking, if a property is changed, it will automatically notify the UI. The UI reflects these changes and can also change the value to automatically update the source object again.
Using REST APIs and CSOM in your SharePoint implementations nowadays is a must for the rise of using SharePoint apps and SharePoint online, the glory of Server Side Object Model is fading and the technology now is going towards the  client side operations.

In this article we will discuss a simple feature - Getting SharePoint List Item form Page Library using CSOM - Then we will bind the returned results to a predefined HTML DOM elements to have those results in jcarousel slider.



  1. Get Page List Items  using CSOM
If you want to get pages (List Items) from SharePoint using Client Side scripts you have two approaches, CSOM or using REST APIs, In our case we will use CSOM as when I tried calling REST API for my pages library including the Roll up Image Field "http://server/en/News/_api/web/Lists/getbytitle('Pages')/items?$select=Id,Title,FileRef,PublishingRollupImage" , I had the following error:


Anyway to select the Pages Items we will use the below method "SelectNewsPages" I've commented the code inline with the explanation for each line :

Add the following Script links:


1
2
    <script type="text/javascript" src="//ajax.aspnetcdn.com/ajax/4.0/1/MicrosoftAjax.js"></script>
    <script type="text/javascript" src="/_layouts/15/sp.runtime.js"></script>

Select News Pages JS:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
function SelectNewsPages() {
    //Get pages library sub web 
    var WebUrl = _spPageContextInfo.webAbsoluteUrl + "/News";
    //Load Context according to news sub site
    var context = new SP.ClientContext(WebUrl);
    var NewsWeb = context.get_web();
    //Get Pages Library (List)
    var PagesList = NewsWeb.get_lists().getByTitle('Pages');

    //Build the selection query
    //in this example we select a specific content type, Ordered By Article date desc and row limited to 5 Items

    var NewsContentTypeId = '0x010100C568DB52D9D0A14D9B2FDCC96666E9F2007948130EC3DB064584E219954237AF3900242457EFB8B24247815D688C526CD44D00C2CE4371BE4442CB9AE069A5FDF4163A';
    var query = new SP.CamlQuery();
    query.set_viewXml("<View><Query><Where><BeginsWith><FieldRef Name='ContentTypeId' /><Value Type='ContentTypeId'>" + NewsContentTypeId + "</Value></BeginsWith></Where><OrderBy><FieldRef Name='ArticleStartDate' Ascending='FALSE' /></OrderBy></Query><RowLimit>5</RowLimit></View>");

    //Get List Items
    var collListItem = PagesList.getItems(query);
    //Include the view fields
    context.load(collListItem, 'Include(FileRef,Title,RoutingRuleDescription,ArticleStartDate,PublishingRollupImage,ContentType)');

    //Execute your Query Async, and define the success and failure handlers
    context.executeQueryAsync(
        Function.createDelegate(this, function () {
            //DO Some Logic for Success
        }),
        Function.createDelegate(this, function () {
            alert(args.get_message());
        }));
}

Now lets under stand the Knockout view model, Simply in our model we will define:

 - The Object that we will bind ( If you are using REST APIs the data already is in JSON format so no need to define your own structure )
 - The observable array that will contain all objects to be bind
 - The get method that will fill the array

First download the following files and add the following references: 


1
2
<script type="text/javascript" src="/_layouts/15/myScripts/knockout-3.2.0.js"></script>
<script type="text/javascript" src="/_layouts/15/myScripts/ko.sp-1.0.min.Ex.js"></script>


REST API Example:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
function EmployeeModal() {
    var self = this;
    //Data array holding objects to be bind
    self.Employees = ko.observableArray([]);

    //Get method
    $.getJSON(_spPageContextInfo.webAbsoluteUrl + "/_vti_bin/listdata.svc/Employees?$expand=Skills,ModifiedBy",
                 function (data) {
                     if (data.d.results) {
                         self.Employees(ko.toJS(data.d.results));
                     }
                 }
           );
}
$(document).ready(function () {
    ko.applyBindings(new EmployeeModal());
});

For our example using CSOM :

Add following in the header


1
2
3
4
5
6
7
8
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="/_layouts/15/myScripts/jcarousel.basic.css" />
<script src="/_layouts/15/myScripts/jcarousel.basic.js" type="text/javascript"></script>
<script src="/_layouts/15/myScripts/jquery.jcarousel.min.js" type="text/javascript"></script>
<script type="text/javascript" src="//ajax.aspnetcdn.com/ajax/4.0/1/MicrosoftAjax.js"></script>
<script type="text/javascript" src="/_layouts/15/sp.runtime.js"></script>
<script type="text/javascript" src="/_layouts/15/myScripts/knockout-3.2.0.js"></script>
<script type="text/javascript" src="/_layouts/15/myScripts/ko.sp-1.0.min.Ex.js"></script>

Following the HTML DOM to be bind

- Item Template Definition in the header


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
    <%--Set the ID of the item template to be linked in the main foreach binder--%>
    <script type="text/html" id="NewsItem">
        <li>
            <a data-bind="attr: { href: Url, title: Title }">
                <img data-bind="attr: { src: Image, alt: Title }" width='900' height='395' />
            </a>
            <h3 data-bind="text: Title"></h3>
            <p data-bind="text: Summary"></p>
        </li>
    </script>

- Main Carousel container 


1
2
3
4
5
6
7
8
 <div class="jcarousel-wrapper">
        <div class="jcarousel">
            <%--The binder will itterate using foreach in the KO observable array 'sliderAllAnnouncments' , Binding the objects using the predefined item template--%>
            <ul class="jcarousel-ul" data-bind="template: { name: 'NewsItem', foreach: sliderAllAnnouncments }" />
        </div>
        <a href="#" class="jcarousel-control-prev bg-arrow-left"></a>
        <a href="#" class="jcarousel-control-next bg-arrow-right"></a>
    </div>

The Knockout View Model using CSOM - FULL CODE INCLUDING PREVIOUS SNIPPET :


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
//Load a loading image till the items are acquired 
$(window).load(function () {
    if ($(".jcarousel-ul").html() != null) {
        $(".jcarousel-ul").html("<CENTER><div class='loader' style='position:absolute;left:50%; top:50%;'><CENTER><img src='/_layouts/15/EQNewsScripts//ajax-loader.gif' /></CENTER></div></CENTER>");
        $(".loader").show();
        //Delay the calling till the sp.js is loaded
        SP.SOD.executeFunc('sp.js', 'SP.ClientContext', LoadNews)
    }
})

//Intialize the view model and apply bindings
function LoadNews() {
    var VM = new viewModel();
    VM.sliderRetrieveAnnouncments();
    ko.applyBindings(VM);
}

function viewModel() {
    var self = this;

    // Definition for the bind object
    self.sliderAnnouncement = function (Url, Title, Image, Summary, Date) {
        this.Url = Url;
        this.Title = Title;
        this.Image = Image;
        this.Summary = Summary;
        this.Date = Date;
    }

    // Definition for Array holding objects to be binded
    self.sliderAllAnnouncments = ko.observableArray([]);

    //Get Items using CSOM
    self.sliderRetrieveAnnouncments = function () {
        var WebUrl = _spPageContextInfo.webAbsoluteUrl + "/News";
        var context = new SP.ClientContext(WebUrl);
        var NewsWeb = context.get_web();
        var PagesList = NewsWeb.get_lists().getByTitle('Pages');
        var query = new SP.CamlQuery();
        query.set_viewXml("<View><Query><Where><BeginsWith><FieldRef Name='ContentTypeId' /><Value Type='ContentTypeId'>0x010100C568DB52D9D0A14D9B2FDCC96666E9F2007948130EC3DB064584E219954237AF3900242457EFB8B24247815D688C526CD44D00C2CE4371BE4442CB9AE069A5FDF4163A</Value></BeginsWith></Where><OrderBy><FieldRef Name='ArticleStartDate' Ascending='FALSE' /></OrderBy></Query><RowLimit>5</RowLimit></View>");
        var collListItem = PagesList.getItems(query);
        context.load(collListItem, 'Include(FileRef,Title,RoutingRuleDescription,ArticleStartDate,PublishingRollupImage,ContentType)');
        context.executeQueryAsync(
            Function.createDelegate(this, function () {

                //The data loaded successfully, So hide the loader section and begin pushing data
                $(".loader").hide();
                $(".jcarousel-ul").empty();

                var listItemEnumerator = collListItem.getEnumerator();
                var length = collListItem.get_count();
                if (length > 0) {
                    //Fetch the returned data and wrap to the observable array
                    while (listItemEnumerator.moveNext()) {
                        var oListItem = listItemEnumerator.get_current();

                        if (oListItem.get_item('PublishingRollupImage') != null) {
                            var URL = oListItem.get_item('FileRef');
                            var pageTitle = oListItem.get_item('Title');
                            var pageSummary = oListItem.get_item('RoutingRuleDescription');
                            var pageDate = oListItem.get_item('ArticleStartDate');

                            var pageImage = '';
                            pageImage = oListItem.get_item('PublishingRollupImage');
                            pageImage = pageImage.substr(pageImage.indexOf('src="') + 5, pageImage.length);
                            pageImage = pageImage.substr(0, pageImage.indexOf('"'));

                            //Push the new data to the data observable array 
                            self.sliderAllAnnouncments.push(new self.sliderAnnouncement(URL, pageTitle, pageImage, pageSummary, pageDate));
                        }
                    }


                    //Data are binded to the HTML DOM, Rejester the <ul> tag for jcarousel
                    $('.jcarousel')
                            .jcarousel({
                                wrap: 'circular'
                            })
                            .jcarouselAutoscroll({
                                interval: 3000,
                                target: '+=1',
                                autostart: true
                            })
                    ;
                }
            }),
            Function.createDelegate(this, function () {
                $(".loader").hide();
                alert(args.get_message());
            }));
    }
}

Here is the final result :

Happy SharePointing hope this article helps you.

Thursday, April 24, 2014

Enable or disable custom ribbon button in SharePoint 2013 based on List Item Property [ Field Value ]

You would come to some scenarios in SharePoint where you want to create a ribbon custom action to perform some custom tasks to meet your business needs.

Creating a custom action in SharePoint 2013 is not different than SharePoint 2010, and there are a lot of articles explaining how to create a custom action.

Examples:

  1. SharePoint 2010 Custom Ribbon Button
What about disabling this button when a specific condition is true, The most common example you will find is disabling the ribbon button while more than on list item is selected.
  1. CommandUIHandler Element
  2. Enable or disable custom ribbon button in SharePoint 2010
But what about disabling the custom action based on a field value in the currently selected list item, For example in the Check-in & Check-out buttons in the ribbon is disabled/Enabled based on the Document [Item] Status.

Ok, Then how would you apply the same idea based on your own custom field.

Here comes the magic of using CSOM and ECMA scripts to communicate asynchronously with current list, Getting the current list item fields, then deciding based on the field value if you will Enable/Disable the button.

In the Custom action elements.xml definition you will find a section with the following tag "CommandUIHandler", This tag has "EnabledScript" attribute, Where you can right javascript to return true if enabled, False if the button is disabled.

First you need to check if only one item is selected:


function singleStatusEnable() {
    try{
        var selecteditems = SP.ListOperation.Selection.getSelectedItems();
        var ci = CountDictionary(selecteditems);

        if (ci == 1) {
            return CheckStatus(selecteditems);
        }
        else {
            return false;
        }
    }
    catch (ex) {
        alert('Error occurred: ' + ex.message);
        return false;
    }
}


Then we will have the following plan, We will create a global window variable of array type, To maintain the values of the EnabledScript.

We will use the array index as the ItemID and the value will be either true or false, Why we will do this ?? Simply to not have to check the Item Field value each type the user check/uncheck the item, as each time the item is checked or unchecked the method "RefreshCommandUI()" is called which re-validates all the ribbon buttons to decide wither to enable or disable them according to current selected Item.

If the global window variable is not defined we will initialize it - This will happen only with first selected item - Then we will check if the current item ID already exists in our array if yes we will return the value if not we will check the value asynchronously, after we get the response back from the server we will call the "RefreshCommandUI()" method to re-validate the ribbon buttons


function CheckStatus(selectedItems) {
    //Get Current Context
    var clientContext = SP.ClientContext.get_current();
    //Get Current List
    var currentList = clientContext.get_web().get_lists().getById(SP.ListOperation.Selection.getSelectedList());
    //Get Selected List Item
    var ItemId = selectedItems[0].id;

    //Check if the window global array variable was initialized or not 
    if(window.FolderStatusValue === undefined) {
        window.FolderStatusValue = new Array();
    }
    
    //Check if the current selected ID was previously saved if not Get the Item status and refresh the UI
    if (window.FolderStatusValue[ItemId] === undefined) {
        singleItem = currentList.getItemById(ItemId);
        clientContext.load(singleItem);
        clientContext.executeQueryAsync(Function.createDelegate(this, OnSucceeded), Function.createDelegate(this, OnFailed));
        return false;
    }
    
    //Return the saved value
    return window.FolderStatusValue[ItemId];
}

//When the Async request is completed save the Item value in the array and re-call RefreshCom//mandUI() method
function OnSucceeded() {
    
    var selecteditems = SP.ListOperation.Selection.getSelectedItems();
    var ItemId = selecteditems[0].id;

    var ItemStatus = singleItem.get_item('YOUR-CUSTOM-COLUMN-STATIC-NAME');
    
    
    if (ItemStatus) {
        window.FolderStatusValue[ItemId] = true; //Enable Ribbon button
        RefreshCommandUI();
    }
    else {
        window.FolderStatusValue[ItemId] = false; //Disable Ribbon button
    }
}


function OnFailed(sender, args) {
    alert('Error occurred: ' + args.get_message());
    return false;
}


Here is the full XML definition for the Custom Action  :


<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <CustomAction Id="8d2b47c5-9e1a-4ff2-9a90-071632a0e9db.ShareFolderExternal"
                RegistrationType="ContentType"
                RegistrationId="0x0120001D4A61CCFCF04620B4F487A48EABBD52"
                Location="CommandUI.Ribbon"
                Rights="AddListItems,DeleteListItems,EditListItems">
    <CommandUIExtension>
      <CommandUIDefinitions>
        <CommandUIDefinition
         Location="Ribbon.Documents.Share.Controls._children">
          <Button
           Id="8d2b47c5-9e1a-4ff2-9a90-071632a0e9db.ShareFolderExternal.Button"
           Command="ShareFolderExternally"
           Image16by16="/_layouts/15/images/Share16x16.png"
           Image32by32="/_layouts/15/images/Share32x32.png"
           LabelText="$Resources:DocumentSharing,ShareFolderCA;"
           TemplateAlias="o1"
           Sequence="11" />
        </CommandUIDefinition>
      </CommandUIDefinitions>
      <CommandUIHandlers>
        <CommandUIHandler   Command="ShareFolderExternally"
                            CommandAction="Javascript:
                                            function Operation(dialogResult, returnValue)
                                            {
                                              SP.UI.Notify.addNotification('Successfully Done!');

                                              SP.UI.ModalDialog.RefreshPage(SP.UI.DialogResult.OK);
                                            }
                
                                            var webURL = _spPageContextInfo.webServerRelativeUrl;
                                            var selecteditems = SP.ListOperation.Selection.getSelectedItems();
                                            
                                            var ItemId = selecteditems[0].id;
                                            
                                            var options = {
                                                            url: webURL + '/_layouts/15/Progress.aspx?FolderId=' + ItemId + '&amp;ListId={ListId}',
                                                            title: 'Share Folder Externally',
                                                            allowMaximize: false,
                                                            showClose: true,
                                                            width: 400,
                                                            height: 100,
                                                            dialogReturnValueCallback: Operation
                                                          };
                                            SP.UI.ModalDialog.showModalDialog(options);"
                              EnabledScript="javascript:
                              
var singleItem;

function singleStatusEnable() {
    try{
        var selecteditems = SP.ListOperation.Selection.getSelectedItems();
        var ci = CountDictionary(selecteditems);

        if (ci == 1) {
            return CheckStatus(selecteditems);
        }
        else {
            return false;
        }
    }
    catch (ex) {
        alert('Error occurred: ' + ex.message);
        return false;
    }
}

function CheckStatus(selectedItems) {
    var clientContext = SP.ClientContext.get_current();
    var currentList = clientContext.get_web().get_lists().getById(SP.ListOperation.Selection.getSelectedList());

    var ItemId = selectedItems[0].id;

    if(window.FolderStatusValue === undefined) {
        window.FolderStatusValue = new Array();
    }
    
    if (window.FolderStatusValue[ItemId] === undefined) {
        singleItem = currentList.getItemById(ItemId);
        clientContext.load(singleItem);
        clientContext.executeQueryAsync(Function.createDelegate(this, OnSucceeded), Function.createDelegate(this, OnFailed));
        return false;
    }
    return window.FolderStatusValue[ItemId];
}

function OnSucceeded() {
    
    var selecteditems = SP.ListOperation.Selection.getSelectedItems();
    var ItemId = selecteditems[0].id;

    var ItemStatus = singleItem.get_item('YOUR-CUSTOM-COLUMN-STATIC-NAME');
    
    
    if (ItemStatus) {
        window.FolderStatusValue[ItemId] = true;
        RefreshCommandUI();
    }
    else {
        window.FolderStatusValue[ItemId] = false;
    }
}


function OnFailed(sender, args) {
    alert('Error occurred: ' + args.get_message());
    return false;
}

singleStatusEnable();
" />
      </CommandUIHandlers>
    </CommandUIExtension>
  </CustomAction>
</Elements>


Hope you find this article useful, Happy SharePointing :)