Showing posts with label JavaScript. Show all posts
Showing posts with label JavaScript. Show all posts

Monday, 28 September 2020

Get User Privilege on a field - Dynamics 365 CE

 Hi Everyone,

Today I got a requirement to check whether the user has access to read the data on the field where field level security has been enabled and do some operations.

We can achieve this using getUserPrivilege() client API.

var fieldPrivileges = formContext.getAttribute("new_fieldsecurityfield").getUserPrivilege();

Result when user doesn't have permission.

Result when user have permission.

Hope this helps.

--
Happy 365'ing
Gopinath.

Thursday, 24 September 2020

Hide Formselector on the Form - Dynamics 365 CE/CRM

 Hi Everyone,

Today I got a requirement to hide FormSelector on the Form as Users would have access to multiple forms but we have to navigate them to right form based on a field value on the record and we shouldn't give an option to change the form to the User. 

My initial thought was it's not possible to hide formselector but one of my colleagues came up with the below piece of the code and it worked like a charm.

Logic is simple, set Visibility of the forms to False.

 var formContext = executionContext.getFormContext();
    formContext.ui.formSelector.items.get().forEach(function (item, index) {
        // hide all the form apart from Opportunity.
        if (item.getLabel() != "Opportunity") {
            item.setVisible(false);
        }
    });

Without above code, we see formselector

With code, we don't see formselector.

Hope this helps.

--
Happy 365'ing
Gopinath

Retrieve Optionset Metadata using JavaScript - Dynamics 365 CE/Microsoft Dynamics CRM

Hi Everyone,

Today I got a requirement to retrieve Optionset Metadata using JavaScript.

Here is the code for the same.

function getOptionSetMetadata(schemaName) {
    var schemaName = "industrycode"; // You can pass this as a parameter to this function and comment this line.
     var optionSetFetch = `<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
        <entity name='stringmap' >
            <attribute name='attributevalue' />
            <attribute name='value' />
            <filter type='and' >
                <condition attribute='attributename' operator='eq' value= '${schemaName}' />
            </filter>
        </entity>
    </fetch>`;
    optionSetFetch = "?fetchXml=" + encodeURIComponent(optionSetFetch);
 
    Xrm.WebApi.retrieveMultipleRecords("stringmap", optionSetFetch).then(
        function success(result) {
            if (result.entities.length > 0) {
                console.log(result.entities);
                for (count = 0; count < result.entities.length; count++) {
                    console.log("Attribute Value : " + result.entities[count].attributevalue);
                    console.log("Value : " + result.entities[count].value);
                }
            }
        },
        function (error) {
            console.log(error.message);
        });
}

Here is the output.

Hope this helps.

--
Happy 365'ing
Gopinath.

Saturday, 19 September 2020

Calculate the Age from Date of Birth in JavaScript

Hi Everyone,

Today I have got an requirement to calculate the Age based on Date of Birth.

Here is the way to get the Age using JavaScript.

function getAge(dateString) {
    // var dateString = '12/02/1988'
    var today = new Date();
    var birthDate = new Date(dateString);
    var age = today.getFullYear() - birthDate.getFullYear();
    var m = today.getMonth() - birthDate.getMonth();
    console.log(today.getMonth())
    console.log(birthDate.getMonth())
    console.log(m);
    // Logically we cannot include the current year if the birthday has not completed in the current year.
    // The below condition checks the same and removes the current year from Age.
    if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
        age--;
    }
    return age;

}

Hope this helps.

--
Happy Coding
Gopinath.

Friday, 14 August 2020

Get InitialValue of a field in JavaScript - in Dynamics 365 CE

Hi Everyone,

Today I was going through Client API from Microsoft Docs and found getInitialValue reference. I haven't used it anytime and explored little bit. 

Many times we get the requirement to compare the field values on the Save with the values that were populated on the load and to achieve this, normally we use declare a global variable in JavaScript and set the variable to the value of the field on the Load event and use it on Save for comparing. We can say good bye to these kind of logics and use getInitialValue() to get the value when the form is opened.

Here is the syntax for the same.

formContext.getAttribute(<attributename>).getInitialValue()

Note: 
1) This method works for only Boolean, OptionSet or MultiSelectOptionSet attributes. 
2) Once the record is saved, getInitialValue holds the latest value whatever that was changed by the user.

Hope this helps.

--
Happy 365'ing
Gopinath.

Tuesday, 9 June 2020

Mention height and width in Percentage instead of Pixels - Modal Popups in Dynamics 365 CE - NavigateTo

Hi Everyone,

Today a bug was created by the user saying the popup window is too small and we were using below code to show the HTML Webresource as a popup.

var pageInput = { pageType: "webresource", webresourceName: "WebResourceName" };
        var navigationOptions = {
            target: 2,
            width: 400,
            height: 300,
            position: 1
        };
        Xrm.Navigation.navigateTo(pageInput, navigationOptions).then(
            function success() {
                // Handle dialog closed
            },
            function error() {
                // Handle errors
            }
        );

When we have checked the code was working fine and able to see the window normally. After some checks with the users came to know that User has 19 inches monitor and that has opened doors to fix the issue. We all know that we have to use percentage instead of pixels for height and width and here is the way to use the same in NavigationOptions of NavigateTo function.

Here is the modified code of the same.

var pageInput = { pageType: "webresource", webresourceName: "WebResourceName" };
        var navigationOptions = {
            target: 2,
            //width: 400,
            //height: 300,
            width: { value: 90, unit: "%" },
            height: { value: 90, unit: "%" },
            position: 1
        };
        Xrm.Navigation.navigateTo(pageInput, navigationOptions).then(
            function success() {
                // Handle dialog closed
            },
            function error() {
                // Handle errors
            }

        );

Hope this helps.

--
Happy 365'ing
Gopinath

Thursday, 21 May 2020

Create Email record in Dynamics 365 CE using JavaScript

Hi Everyone,

I know this could be very simple as we are doing this from ages but somehow I couldn't get this piece of code very easily.

Code for creating email record using JavaScript in Dynamics 365 Customer Engagement. Important thing here to understand more on Activity Party Participation Type Mask. Go through Microsoft Docs for more information on the same.

    var activityParties = []
    var Sender = {};
    var Receipent = {};

    var userId = "21EFAD11-353B-4238-93BB-65015F448E8A";

    // From - Participation Type Mask = 1
    Sender["partyid_systemuser@odata.bind"] = "/systemusers(" + userId + ")";
    Sender["participationtypemask"] = 1;
    activityParties.push(Sender);

    // To - Participation Type Mask = 1
    Receipent["partyid_systemuser@odata.bind"] = "/systemusers(" + userId + ")";
    Receipent["participationtypemask"] = 2;
    activityParties.push(Receipent);

    var createEmailRequest = {
        "description": "This email is created using JavaScript Code",
        "regardingobjectid_account@odata.bind": "/accounts(bec28e1e-ab87-ea11-a817-000d3a19245f)",
        "subject": "Email using JavaScript",
        "email_activity_parties": activityParties
    }

    Xrm.WebApi.createRecord('email', createEmailRequest).then(
        function success(Email) {
            console.log("Email has been created");
        },
        function Error(e) {
            console.log(e.message);
        }

    )

Hope this helps.

--
Happy 365'ing
Gopinath

Friday, 6 December 2019

Get/Set Lookup field value using JavaScript in Dynamics CRM/Dynamics 365 CE

Hi Everyone,

Sometimes, it is really good to keep required and repeated code handy. 

Here is the JavaScript code for getting and setting value from CRM/CE Lookupfield.

// Get the Lookup Value.
function getLookupDetails(executionContext) {
    var formContext = executionContext.getFormContext();
    var entityName, entityId, entityLabel, lookupFieldObject;
    lookupFieldObject = formContext.data.entity.attributes.get("parentcontactid");
    if (lookupFieldObject.getValue() != null) {
        entityId = lookupFieldObject.getValue()[0].id.slice(1, -1);
        entityName = lookupFieldObject.getValue()[0].entityType;
        entityLabel = lookupFieldObject.getValue()[0].name;
    }
}

// Set the Lookup Value.
function setLookupField(executionContext) {
    var formContext = executionContext.getFormContext();
    var lookupData = new Array();
    var lookupItem = new Object();
    lookupItem.id = "74a968c5-6505-ea11-a81e-000d3a300ec6";
    lookupItem.name = "Nancy";
    lookupItem.entityType = "contact";
    lookupData[0] = lookupItem;
    formContext.data.entity.attributes.get("parentcontactid").setValue(lookupData);

}

Hope this helps.

--
Happy 365'ing
Gopinath

Thursday, 18 August 2016

Get an item from JSON/Filter JSON

Hi,

Today I was working on JavaScript and I had a requirement to get one item from JSON object.
Here is the sample code for filtering.

var vJsonArr = [];
vJsonArr.push({ name: "k1", value: "abc" });
vJsonArr.push({ name: "k2", value: "def" });
vJsonArr.push({ name: "k3", value: "ghi" });
var vfound = vJsonArr.filter(function (item) { return item.name === 'k1'; });

Hope this helps.
--
Happy Coding

Gopinath

Tuesday, 26 January 2016

Disable all fields on a Web form (ASP.net, HTML forms)

Hi,
 
Today we got a requirement to disable all the fields on the ASP.net form based on some conditions.
 
This can be easily done using JavaScript. Here is the code for it.

var inputs = document.getElementsByTagName("input");
for (var i = 0; i < inputs.length; i++) {
     // For applying background color and color.
     // inputs[i].style.backgroundColor = "#9fd4fe";
     // inputs[i].style.color = "black";
     inputs[i].disabled = true;
}
var selects = document.getElementsByTagName("select");
for (var i = 0; i < selects.length; i++) {
     selects[i].disabled = true;
}
var textareas = document.getElementsByTagName("textarea");
for (var i = 0; i < textareas.length; i++) {
     textareas[i].disabled = true;
}
var buttons = document.getElementsByTagName("button");
for (var i = 0; i < buttons.length; i++) {
     buttons[i].disabled = true;
}
var links = document.getElementsByTagName('a');
for (var i = 0; i < links.length; i++) {
     links[i].disabled = true;
}

Hope this helps.
 
--
Happy Coding

Gopinath

Sunday, 15 November 2015

Allow only numbers in a text box

Hi,

In most of web applications, we get requirement to allow only number in a textbox.

Here is the JavaScript for it, just call this method onKeyPressv Event.

<HTML>
   <HEAD>
   <SCRIPT language=Javascript>
      <!--
       function isNumberPressed(evt) {
           var charCode = (evt.which) ? evt.which : event.keyCode
           if (charCode > 31 && (charCode < 48 || charCode > 57))
               return false;
           return true;
       }
      //-->
   </SCRIPT>
   </HEAD>
   <BODY>
      <INPUT id="txtChar" onkeypress="return isNumberPressed(event)" type="text" name="txtChar">
   </BODY>
</HTML>
 
Hope this helps.

--
Happy Coding
Gopinath

Sunday, 8 November 2015

How to check Array contains an Item in JavaScript?

Hi,
 
Here is the JavaScript  code to check Array contains an item in JavaScript.
 
var vArrValues = ["1", "2", "3", "4"];

// Check Array Contains Values
Array.prototype.contains = function (element) {
     return this.indexOf(element) > -1;
};

function CheckArrayContaintsValue(vValue) {
    if (vArrValues.contains(vValue)) {
            return true;
    }
    else {
       return false;
     }
}

CheckArrayContaintsValue("1"); // Returns True
CheckArrayContaintsValue("5"); // Returns False
 
Hope this helps.
 
--
Happy Coding.
Gopinath

Thursday, 5 November 2015

Retrieve Option Set text from CRM 2011/2013/2015 in JavaScript

Hi,
 
Today I got a requirement to write JavaScript code to get text of the option set value and perform some business validations.
 
Its really pretty simple to get the option set text from the particular entity and attribute.
 
We just need to add SDK.Metadata.js reference. This can found under (SDK\SampleCode\JS\SOAPForJScript\SOAPForJScript\Scripts) and use the below code.

function GetOptionSetText(EntityLogicalName, AttributeLogicalName) {
    SDK.Metadata.RetrieveAttribute(EntityLogicalName, AttributeLogicalName, "00000000-0000-0000-0000-000000000000", true,
       function (result) {
            for (var i = 0; i < result.OptionSet.Options.length; i++) {
                var text = result.OptionSet.Options[i].Label.LocalizedLabels[0].Label;
                var value = result.OptionSet.Options[i].Value;
            }
        },
        function (error) { }
    );
}

Hope this helps.

--
Happy CRM'ing
Gopinath