Home

Showing posts with label Dynamics Scrips. Show all posts
Showing posts with label Dynamics Scrips. Show all posts

Saturday, September 16, 2017

Set form notifications in dynamics 365

You can display any number of notifications using “setFormNotification” and they will be displayed until they are removed using clearFormNotification. The height of the notification area is limited so each new message will be added to the top. Users can scroll down to view older messages that have not yet been removed.

Syntax
To clear the notifications on the form.
Xrm.Page.ui.clearFormNotification(uniqueId);
To set  the notifications on the form.
Xrm.Page.ui.setFormNotification(message, level, uniqueId);
To set the notifications on the form for a particular field.
Xrm.Page.getControl(fieldname).setNotification(message, uniqueId);
--------------------------------------------------------------------------------------

To set the notifications on the form.
function setFormNotifications() {
    Xrm.Page.ui.setFormNotification("This is an INFORMATION notification.", "INFO","1");
    Xrm.Page.ui.setFormNotification("This is a WARNING notification. ", "WARNING" , "2");
    Xrm.Page.ui.setFormNotification("This is an ERROR notification. ", "ERROR", "3");
    Xrm.Page.getControl("name").setNotification("Message to display", "101")
}

To clear the notifications from field and form.
function clearFormNotifications() {
    // Cleards notifications from the field "name" with unique identifier 101
    Xrm.Page.getControl("name").clearNotification("101");
    // Clears notifications from the form for unique id 1
    Xrm.Page.ui.clearFormNotification("1");
}

Dynamics 365 JavaScript functions

Get the value from a CRM field
 var varMyValue = Xrm.Page.getAttribute(“ fieldName”).getValue() ;

Set the value of a CRM field
Xrm.Page.getAttribute(“ fieldName”).setValue(‘My New Value’);

Hide/Show a tab/section
Xrm.Page.ui.tabs.get(5).setVisible(false);
Xrm.Page.ui.tabs.get(5).setVisible(true);

Hide/Show field
Xrm.Page.ui.controls.get(fieldName).setVisible(false); Xrm.Page.ui.controls.get(fieldName).setVisible(true);

Call the onchange event of a field
 Xrm.Page.getAttribute(“ fieldName”).fireOnChange();

Get the selected value of picklist
Xrm.Page.getAttribute(“ fieldName”).getSelectedOption().text;

Set the requirement level
Xrm.Page.getAttribute(“ fieldName”).setRequiredLevel(“none”);
Xrm.Page.getAttribute(“ fieldName”).setRequiredLevel(“required”);
Xrm.Page.getAttribute(“ fieldName”).setRequiredLevel(“recommended”);

Update a readonly field
Xrm.Page.getAttribute("fieldName").setSubmitMode("always");

Set the focus to a field
Xrm.Page.getControl(“ fieldName”).setFocus(true);

Disable/Enable field
 Xrm.Page.getControl(fieldName).setDisabled(true); Xrm.Page.getControl(fieldName).setDisabled(false);

Stop an on save event
event.returnValue = false;

Return array of strings of users security role GUIDs
Var arrUserRoles = Xrm.Page.context.getUserRoles();

Get record GUID
var recordId = Xrm.Page.data.entity.getId();
var recordIdWithoutCurlyBraces = Xrm.Page.data.entity.getId().substring(1,37);

Get Organization unique name
var OrganizationUniqueName = Xrm.Page.context.getOrgUniqueName();

Gets current user Guid
var userGUID = Xrm.Page.context.getUserId();

Returns the base URL that was used to access the application.
var clientURL = Xrm.Page.context.getClientUrl();

Returns a string current Microsoft Office Outlook theme chosen by the user.
var currentTheme = Xrm.Page.context.getCurrentTheme();

Returns whether Autosave is enabled for the organization.
var isAutoSaveEnnabled = Xrm.Page.context.getIsAutoSaveEnabled();


Returns the Dynamics 365 Language Pack that is user's preferred language.
var userLCID = Xrm.Page.context.getUserLcid();

Returns the name of the current user
var userLCID = Xrm.Page.context.getUserName();

Returns the version number of the Dynamics 365 server
var currentVersion = Xrm.Page.context.getVersion();

Method to close the form.
Xrm.Page.ui.close();

Method to get the form type of the record.
Xrm.Page.ui.getFormType();

Method to refresh the ribbon.

Xrm.Page.ui.refreshRibbon();

Returns the difference between the local time and Coordinated Universal Time (UTC).
var timeDifference = Xrm.Page.context.getTimeZoneOffsetMinutes();
 
Set Form Notifications in Dynamics 365

Thursday, September 14, 2017

Retrieve an entity using Dynamics 365 Web API


The following example retrieves name and revenue properties for the account entity with the Id

Request
GET [Organization URI]/api/data/v8.2/accounts(00000000-0000-0000-0000-000000000001)?$select=name,revenue HTTP/1.1
Accept: application/json
Content-Type: application/json; charset=utf-8
OData-MaxVersion: 4.0
OData-Version: 4.0

Response
HTTP/1.1 200 OK
Content-Type: application/json; odata.metadata=minimal
OData-Version: 4.0

{
"@odata.context": "[Organization URI]/api/data/v8.2/$metadata#accounts(name,revenue)/$entity",
"@odata.etag": "W/\"502186\"",
"name": "A. Datum Corporation (sample)",
"revenue": 10000,
"accountid": "00000000-0000-0000-0000-000000000001",
"_transactioncurrencyid_value":"b2a6b689-9a39-e611-80d2-00155db44581"
}
------------------------------------------------------------------------------------------------------
function GetRecord() {
   
    var entityName = "accounts", etag;
    var clientURL = Xrm.Page.context.getClientUrl();
    var req = new XMLHttpRequest();

    req.open("GET", encodeURI(clientURL + "/api/data/v8.2/" + entityName + "(00000000-0E99-E711-8127-000000000001)?$select=name,revenue", false));
    req.setRequestHeader("Accept", "application/json");
    req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
    req.setRequestHeader("OData-MaxVersion", "4.0");
    req.setRequestHeader("OData-Version", "4.0");

    req.onreadystatechange = function () {       
        if (this.readyState === 4 /* complete */) {
            req.onreadystatechange = null;
            if (this.status === 200) {
                var result = JSON.parse(this.response);               
            }
            else {
                var error = JSON.parse(this.response).error;
                alert(error.message);
            }
        }
    };

    req.send();
  

}

Apply optimistic concurrency on update Dynamics Web Api

You can use optimistic concurrency to detect whether an entity has been modified since it was last retrieved. If the entity you intend to update or delete has changed on the server since you retrieved it, you may not want to complete the update or delete operation. By applying the pattern shown here you can detect this situation, retrieve the most recent version of the entity, and apply any necessary criteria to re-evaluate whether to try the operation again.

Request
PATCH [Organization URI]/api/data/v8.2/accounts(00000000-0000-0000-0000-000000000001) HTTP/1.1
If-Match: W/"470867"
Accept: application/json
OData-MaxVersion: 4.0
OData-Version: 4.0

{"name":"Updated Account Name"}

Response
HTTP/1.1 412 Precondition Failed
Content-Type: application/json; odata.metadata=minimal
OData-Version: 4.0

{
  "error":{
    "code":"","message":"The version of the existing record doesn't match the RowVersion property provided.",
    "innererror":{
      "message":"The version of the existing record doesn't match the RowVersion property provided.",
      "type":"System.ServiceModel.FaultException`1[[Microsoft.Xrm.Sdk.OrganizationServiceFault, Microsoft.Xrm.Sdk, Version=8.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35]]",
"stacktrace":"  <stack trace details omitted for brevity>
    }
  }
}

------------------------------------------------------------------------------------------------------
The following update request for an account with accountid of 00000000-0E99-E711-8127-000000000001 fails because the ETag value sent with the If-Match header is different from the current value. If the value had matched means the data which is retrieved is not edited and you have the latest data, a 204 (No Content) status is expected.

function updateLatestData() { // Using optimistic concurrency
  
    var entityName = "accounts";
    var clientURL = Xrm.Page.context.getClientUrl();
    var req = new XMLHttpRequest();
  
    req.open("PATCH", encodeURI(clientURL + "/api/data/v8.2/" + entityName + "(00000000-0E99-E711-8127-000000000001)", true));
    req.setRequestHeader("Accept", "application/json");
    req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
    req.setRequestHeader("OData-MaxVersion", "4.0");
    req.setRequestHeader("OData-Version", "4.0");
    req.setRequestHeader("If-Match", "W/\"470867\"");

    req.onreadystatechange = function () {
        if (this.readyState === 4 /* complete */) {
            req.onreadystatechange = null;
            if (this.status === 204) {
                alert("Record updated");
            }
            else {
                var error = JSON.parse(this.response).error;
                alert(error.message);
            }
        }
    };

    req.send(JSON.stringify(
        {
            name: "Sample Account updated"           
        }));

}

Wednesday, September 13, 2017

Create Entity using Web API in Dynamics 365

Creating an account record with name "sample account" using web api's
https://msdn.microsoft.com/en-us/library/gg328090.aspx
// Request 
POST [Organization URI]/api/data/v8.2/accounts HTTP/1.1
Content-Type: application/json; charset=utf-8
OData-MaxVersion: 4.0
OData-Version: 4.0
Accept: application/json
{
    "name": "Sample Account",  
}
// Response
HTTP/1.1 204 No Content
OData-Version: 4.0
OData-EntityId: [Organization URI]/api/data/v8.2/accounts(GUID)
---------------------------------------------------------------------------------------------------
function createEntity() {
    var entityName = "accounts";// Entity Name
    var clientURL = Xrm.Page.context.getClientUrl();// To get CRM client URl 
    var req = new XMLHttpRequest(); //Creating New HTTP request

    req.open("POST", encodeURI(clientURL + "/api/data/v8.2/" + entityName, true));

    req.setRequestHeader("Accept", "application/json");
    req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
    req.setRequestHeader("OData-MaxVersion", "4.0");
    req.setRequestHeader("OData-Version", "4.0");

    req.onreadystatechange = function () {
        if (this.readyState == 4 /* complete */) {
            req.onreadystatechange = null;
            if (this.status == 204) {/* Status 204 denotes success */
                alert("account created from api");
            }
            else {
                var error = JSON.parse(this.response).error;
                alert(error.message);
            }
        }
    };

    req.send(JSON.stringify(// json object to be created
        {
            name: "sample account"
        }));

}

Tuesday, December 8, 2015

Set Lookup Value using Javascripts in CRM

function set_LookupValue(fieldName, id, name, entityType) {

        if (fieldName != null && id != null) {
            var lookupValue = new Array();
            lookupValue[0] = new Object();
            lookupValue[0].id = id;
            lookupValue[0].name = name;
            lookupValue[0].entityType = entityType;
            Xrm.Page.getAttribute(fieldName).setValue(lookupValue);
        }

    }

Convert subgrid to Comments