Pages

Tuesday 28 January 2014

Enable/Disable a Ribbon button based on a Security Role



The Below snippet code is used for Enabling/Disabling the Ribbon button Based on security Role. In my Scenario, if a user has "System Administrator" type of Security-Role then a button is Enabled.



Save the below code in a webresource.
-------------------->>
function UserHasRole(Nameofrole) {

    var serverUrl = Xrm.Page.context.getServerUrl();
    var oDataEndpointUrl = serverUrl + "/XRMServices/2011/OrganizationData.svc/";
    oDataEndpointUrl += "RoleSet?$top=1&$filter=Name eq '" + Nameofrole + "'";
    var service = GetRequestObject();
    if (service != null) {
        service.open("GET", oDataEndpointUrl, false);
        service.setRequestHeader("X-Requested-Width", "XMLHttpRequest");
        service.setRequestHeader("Accept", "application/json, text/javascript, */*");
        service.send(null);
        var requestResults = eval('(' + service.responseText + ')').d;
        if (requestResults != null && requestResults.results.length == 1) {
            var role = requestResults.results[0];
            var id = role.RoleId;
            var currentUserRoles = Xrm.Page.context.getUserRoles();
            for (var i = 0; i < currentUserRoles.length; i++) {
                var userRole = currentUserRoles[i];
                if (GuidsAreEqual(userRole, id)) {
                    return true;
                }
            }
        }
    }

    return false;
}

function GetRequestObject() {
    if (window.XMLHttpRequest) {
        return new window.XMLHttpRequest;
    }
    else {
        try {
            return new ActiveXObject("MSXML2.XMLHTTP.3.0");
        }
        catch (ex) {
            return null;
        }
    }
}
function GuidsAreEqual(guid1, guid2) {
    var isEqual = false;
    if (guid1 == null || guid2 == null) {
        isEqual = false;
    }
    else {
        isEqual = guid1.replace(/[{}]/g, "").toLowerCase() == guid2.replace(/[{}]/g, "").toLowerCase();
    }

    return isEqual;
}

function callMain() {

    if (UserHasRole("System Administrator")) {                 //passing the security role to another function
        return true;
    }
    else {
        return false;
    }

}


Now Open the Visual Ribbon Editor and select the button which can be on HomePage/Sub-Grid/Form.
In Enable Rules click on "New" to add a rule for the display of a button. In New select "Custom Rule" and add the JScript webresource URL and mention the function name.
The Below Screen shot shows it.


In the above snippet "callMain" is a name of main function.

Sunday 26 January 2014

Retrive Single Record Data using OData

In order to retrieve data of a record  using OData. Let us take a scenario in which I have a  A,B and Test entities, A entity form has lookup of B entity and Test entity has lookup of both A and B entity. So I have created some records in B entity and A entity. Now In my Test Entity form when I select a Lookup of A, The lookup in B must Automatically selected. Since A entity form has lookup of B entity, i.e, In A-record form, B-record is selected in lookup.


So the above snippet code can be used on change event of a A-lookup.


function customentity_onchange() {

debugger;
    var lookupObject = Xrm.Page.getAttribute("schema-name-of-Alookup").getValue();
    var z=lookupObject[0].id; // Guid of lookup
    alert(z);
    if (z != null) {
        var entityA="A-entitynameSet";  //A-entity name with "Set" attached to it for Odata Query.
        var field = "B-lookup_feild_name_in_A-Entity";   //lookup feild name in A entity.
        var a = GetAdata(z,entityA,field);
        if(a!=null)           
        {
        //alert(a[0]["B-lookup_feild_name_in_A-Entity"].Name);
        var lookupData = new Array();
        var lookupItem = new Object();
        lookupItem.id=a[0]["B-lookup_feild_name_in_A-Entity"].Id;
        alert(lookupItem.id);
        lookupItem.name = a[0]["B-lookup_feild_name_in_A-Entity"].Name;
        alert(lookupItem.name);
        lookupItem.entityType ="b-Entity_name";
        alert(lookupItem.entityType);
        lookupData[0] = lookupItem;
        Xrm.Page.getAttribute("schemaname_of_b_lookup_in_TestEntity").setValue(lookupData);
        //Xrm.Page.getAttribute("hrm_b").setValue(a);
        }
        }
    }
function GetAdata(z,entityA,field) {
    var serverUrl = Xrm.Page.context.getServerUrl();
    var oDataUri = serverUrl + "/XRMServices/2011/OrganizationData.svc/"+entityA+"(guid'" + z + "')?$select="+field;
    var jSonArray = new Array();
    $.ajax({
        type: "GET",
        contentType: "application/json; charset=utf-8",
        datatype: "json",
        url: oDataUri,
        async: false,
        beforeSend: function (XMLHttpRequest) {
            //Specifying this header ensures that the results will be returned as JSON.           
            XMLHttpRequest.setRequestHeader("Accept", "application/json");
            //alert(hai);
        },
        success: function (data, textStatus, XmlHttpRequest) {
            if (data && data.d != null) {
                jSonArray.push(data.d);
            }
        },
        error: function (XmlHttpRequest, textStatus, errorThrown) {
        alert("Status: " + textStatus + "; ErrorThrown: " + errorThrown);
            //alert("Error :  has occured during retrieval of the A details");
    }
    });

    return jSonArray;
}

Set Multi-Select Lookup in CRM 2011

Basically MSD CRM 2011 does not contains Multi-Select Lookup . So to set Multi-Select Lookup in CRM we need to go for coding. The below Snippet is essential for Multi-Select Lookup. If we place the below code in "On-Load" event of  a form then the lookup will be a Multi-Select Lookup.

function  load()
{
document.getElementById("lookup Schema Name").setAttribute("lookupstyle", "multi");
}

The above syntax makes the Lookup Feild as Multi-Select. suppose if we replace "multi" by "single" in the above code, then the lookup will be normal lookup.

The above is not enough, it is just use to select mutiple records in lookup. but we want to retrive those selected record details. I am taking a scenario in which I am Slelcting multiple records from a lookup and Placing those selected record details in one multiline-textfeild and again retrieving those field in the same lookup.
So this snippet consists of two functions for On-Load and On-Save.



Code for On-Load
------->>
function  load()
{
document.getElementById("lookup schema name").setAttribute("lookupstyle", "multi");
if(Xrm.Page.ui.getFormType()!=1)
{
var data=new Array();
// I created a one multiline text box to save the lookup values.
// set the multiline textbox visible equal to false.
var store=Xrm.Page.getAttribute("schema name of multiple text feild").getValue();
if(store!=null)
data=store.split(";");
// To get the "Target record type" Go to your form Customization ---> double click on your lookup--->Details--->Edit--->Here you can see "Target Record Type"
var typename = "Target Record Type";   //its mandatory to mention type name
 var arr= new Array();
 var  i=0;
var   j=0;
for(i=0;i<((data.length-1)/2);i++)
{
arr[i] = new Object();
arr[i].name = data[j];
arr[i].id= data[j+1];
arr[i].typename= typename ;
j++;
j=j+1;
}
crmForm.all["lookup schema name"].DataValue = arr;
}
}




Code for On-Save
On Saving, the selected records from lookup are stored in a MultiLine text-box with GUID.. so that it can be used while retrieving the record details.
-------->>
function save() {

var value = crmForm.all["lookup schema name"].DataValue;
var s;
var temp = "";

for (s = 0; s < value.length; s++) {
var temp2 = "";
temp2 = value[s].name+";"+value[s].id+";";
temp = temp+""+temp2;
}
Xrm.Page.getAttribute("schema name of multiple text feild").setValue(temp);
Xrm.Page.getAttribute("lookup schema name").setValue(null);
document.getElementById("lookup schema name").setAttribute("lookupstyle", "single");
}

Tuesday 14 January 2014

How to insert Image/Graphics in CRM Mail Templates

To insert Graphics/Image in CRM Mail Template we have to follow the following steps:

1) Open the Image using Internet Explorer or any browser.
2) Right Click on that particular Image and Click 'Copy'.
3) Now go to Email Template and place your cursor where need your image and type (Ctrl+V).
4)Now you can get the image where ever you want...

Monday 13 January 2014

JScript for Text Validations in CRM 2011

JScript for Text Validations in CRM 2011


The above Snippet code can be used for validation of text field in CRM 2011.


function textValidation(context)
{
var text =context.getEventSource().getValue();
var re=new RegExp("[^a-zA-Z ]");    /// here after a-zA-Z " "is included to show that all that it must also include
// the "Space" in between letters, we can include 0-9 to accept numbers also
if(re.test(text))
{
alert("Alphabets only");
}

}

JScript to Check the condition between two dates dates

JScript to Check the condition between two dates dates


The above Snippet code can be used to get compare the two dates in CRM 2011.


function date()
{
var t=new Date(); //getting current date
var d = t.getDate();
var m = t.getMonth()+1;   //January months starts with 0
var y=t.getFullYear();
var date=Xrm.Page.getAttribute("hrm_dateofbirth").getValue();  //getting date from a field
var dd=date.getDate();
var mm = date.getMonth();
var yy = date.getYear();

if(date > t) //checking condition for date difference i.e give date must not exceed current date
alert("Invalid Date")
}

Monday 6 January 2014

Create a record using JavaScript

Create a record using JavaScript


The below snippet code can be used to create a record by java Script. we nedd to add Json2 and jquery1.4.1.min files to webresource which we can get from SDK.

function RecordCreate() {
if(Xrm.Page.getAttribute('new_name') != null)   //checking whether the attribute is null or not
{
var name = Xrm.Page.getAttribute('new_name').getValue();
}
if(Xrm.Page.getAttribute('new_mainphone') != null)
{
var mainphone = Xrm.Page.getAttribute('new_mainphone').getValue();
}
    var context = Xrm.Page.context;
    var serverUrl = context.getServerUrl();
    var ODATA_ENDPOINT = "/XRMServices/2011/OrganizationData.svc";
    var CRMObject = new Object();
    /////////////////////////////////////////////////////////////
    // Specify the ODATA entity collection
    var ODATA_EntityCollection = "/AccountSet";           //Entity_NameSet--- type of record to be created
    /////////////////////////////////////////////////////////////
    // Define attribute values for the CRM object you want created
    CRMObject.Name = name;                        //"Name" is Schema Name of a field in my account entity
    CRMObject.Telephone1 = mainphone;      //"Telephone1" is Schema Name of a field in my account entity
      CRMObject.Address1_Name=name;
  
    //Parse the entity object into JSON
    var jsonEntity = window.JSON.stringify(CRMObject);
    //Asynchronous AJAX function to Create a CRM record using OData
    $.ajax({ type: "POST",
        contentType: "application/json; charset=utf-8",
        datatype: "json",
        url: serverUrl + ODATA_ENDPOINT + ODATA_EntityCollection,
        data: jsonEntity,
        beforeSend: function (XMLHttpRequest) {
            //Specifying this header ensures that the results will be returned as JSON.
            XMLHttpRequest.setRequestHeader("Accept", "application/json");
        },
        success: function (data, textStatus, XmlHttpRequest) {
            alert("success");
            var NewCRMRecordCreated = data["d"];
            alert("CRM GUID created: " + NewCRMRecordCreated.AccountId);    //AccountId is a Primary field in Account Entity.
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert("failure");
        }
    });
}

Sunday 5 January 2014

Phone no validation in CRM 2011



The Below snippet is essential for Validating Phone no in CRM2011. Add the JavaScript as Web Resource in CRM. Add Web Resource as On-Change Event of a particular Phone no field. Also check the option of Pass Execution Context as first parameter in handler properties.

function validatePhone(context)
{

var phone =context.getEventSource().getValue();
var sTmp = phone.replace(/[^0-9]/g, "");
phoneRegex = /^\d{10}$/;

if( !sTmp.match( phoneRegex ) )
   {
   event.returnValue = false;
   alert("Phone must contain 10 numbers.") ;
   }
else
  {
   var sTmpClean =  "(" + sTmp.substr(0, 3) + ") " + sTmp.substr(3, 3) + "-" + sTmp.substr(6, 4);
   context.getEventSource().setValue(sTmpClean);
  }
}


 Here the Phone no is validated that it contains 10 Characters and all are numeric and later placed in a Pr-defined format which is "(xxx)xxx-xxxx".