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

Tuesday, July 30, 2013

NRIC(Singapore) Validation using Javascript

function IsValidNRIC(theNric) {
    var nric = [];
    nric.multiples = [2, 7, 6, 5, 4, 3, 2];

    if (theNric.length != 9) {
        alert('Invalid NRIC')
        return false;
    }

    var total = 0, count = 0, numericNric;
    var first = theNric.charAt(0), last = theNric.charAt(theNric.length - 1);

    if (first != 'S' && first != 's') {
        alert('Invalid NRIC S');
        return false;
    }
    /*Above is working*/

    numericNric = theNric.substr(1, theNric.length - 2);

    if (isNaN(numericNric)) {
        alert('Invalid NRIC Middle Not a number')
        return false
    }

    if (numericNric != null) {
        while (numericNric != 0) {
            total += (numericNric % 10) * nric.multiples[nric.multiples.length - (1 + count++)];
            numericNric /= 10;
            numericNric = Math.floor(numericNric);
        }
    }

    var outputs;
    if (first == 'S') {
        outputs = ['J', 'Z', 'I', 'H', 'G', 'F', 'E', 'D', 'C', 'B', 'A'];
    }

    if (first == 'T') {
        outputs = ['G', 'F', 'E', 'D', 'C', 'B', 'A', 'J', 'Z', 'I', 'H'];
    }

    if (last != outputs[total % 11]) {
        alert('Invalid end Character')
        return false;
    }

    nric.isNricValid = function (theNric) {
        if (!theNric || theNric == '') {
            return false;
        }
    }
    return true;
}

CRM 2011 - Javascript samples

//FIELDS - Values
// Get Text Value
Xrm.Page.getAttribute("feildName").getText();
//Get Picklist Value
Xrm.Page.getAttribute("FieldName").getValue();
//  Set Value
Xrm.Page.getAttribute("FieldName").setValue(newValue);

//GENERAL
// Get Form Type
Xrm.Page.ui.getFormType();
//Get Record Id
Xrm.Page.data.entity.getId();
//Prevent Saving
ExecutionObj.getEventArgs().preventDefault();
//Get user Id
Xrm.Page.context.getUserId();
// Force Submit
Xrm.Page.getAttribute("FieldName").setSubmitMode("always");
//Set Required Level
Xrm.Page.getAttribute("FieldName").setRequiredLevel("none");
Xrm.Page.getAttribute("FieldName").setRequiredLevel("required");
Xrm.Page.getAttribute("FieldName").setRequiredLevel("recommended");
//Get Server Url
var context = Xrm.Page.context;
var serverUrl = context.getServerUrl();

//IFRMAE
//Set IFrams url 
Xrm.Page.getControl("IFRAME_Name").setSrc(URL_IFRAME_CALLSCRIPT);


//SHOW/HIDE/DISABLE
// Disable Field 
Xrm.Page.getControl("FieldName").setDisabled(true);
//Hide Field
Xrm.Page.ui.controls.get("FieldName").setVisible(false);
//Hite Section
Xrm.Page.ui.tabs.get("TabNumber").sections.get('SectionName').setVisible(flag);
//Hide Tab
Xrm.Page.ui.tabs.get("TabNumber").setVisible(false);
//Tab Expand
Xrm.Page.ui.tabs.get(1).setDisplayState("expanded");
Xrm.Page.ui.tabs.get(1).setDisplayState("collapsed");

//PICKLIST
// Get Selecte Text from picklist
Xrm.Page.getAttribute("FieldName").getSelectedOption().text;
//Remove Option from Picklist
Xrm.Page.getControl("FieldName").removeOption(3);
//Add Option to Picklist
function AddOption(value, text, index) {
    var option = new Option(); option.text = text; option.value = value; typeControl.addOption(option, index);
}

//LOOKUP
//Populate Lookup
function PopulateTemplateLookup(recordid, recordName) {
    Xrm.Page.getAttribute("lookupId").setValue([{ id: recordid, name: recordName, entityType: "EntityName"}]);
}
//Get/Check Lookup Values
var lookupObject = Xrm.Page.getAttribute("lookupfield");
if (lookupObject != null) {
    var lookUpObjectValue = lookupObject.getValue();
    if ((lookUpObjectValue != null)) {
        var lookuptextvalue = lookUpObjectValue[0].name;
        var plookupid = lookUpObjectValue[0].id;
    }
}

//Disable Form Fields
function doesControlHaveAttribute(control) {
    var controlType = control.getControlType();
    return controlType != "iframe" && controlType != "webresource" && controlType != "subgrid";
}

function disableFormFields(onOff) {

    Xrm.Page.ui.controls.forEach(function (control, index) {
        if (doesControlHaveAttribute(control)) {
            control.setDisabled(onOff);
        }
    });
}

//Set Email To [Party List]
function setToPartyList() {
        var partlistData = new Array();
        partlistData[0] = new Object();
        partlistData[0].id = '{08C6AFB3-9673-E011-8720-00155DA5304E}'; // userId
        partlistData[0].name = 'Jill Frank'; //user name
        partlistData[0].entityType = 'systemuser'; // Entity name
        Xrm.Page.getAttribute("to").setValue(partlistData);
    }
MSDN Reference :http://msdn.microsoft.com/en-us/library/jj602964.aspx

Sunday, June 23, 2013

How to Refresh a SubGrid in MS CRM 2011

Code snippet 1 :

function LoadSubGrid(SubGridName) {
    var grid = document.getElementById(SubGridName);
    if (grid) {
        if (grid.readyState == "complete") {
            grid.Refresh();
        }
    }
}
Code snippet 2 :

function LoadSubGrid(SubGridName) {
    var grid = Xrm.Page.ui.controls.get("SubGridName")
    if (grid) {
        if (grid.readyState == "complete") {
            grid.Refresh();
        }
    }
}

Friday, June 21, 2013

Using OData endpoint in MS CRM 2011

As most of you already know in CRM 2011 there are two ways which we can write client script to work with CRM Data.

  • SOAP endpoint: recommended for retrieving metadata, assigning records, executing messages 
  • REST endpoint: recommended for create, retrieve, delete and update, associating and disassociating records, 

Here I’m explaining one of the easiest ways to retrieve data using OData query designer.

Download Link OData Query designer: http://crm2011odatatool.codeplex.com/
For this example I’m getting Template Id by Name,
First Generate query using CRM 2011 OData Query Designer

 

function GetTemplateId() {

    var query = serverUrl + "xrmservices/2011/OrganizationData.svc/new_interventiontemplateSet?$select=new_interventiontemplateId&$filter=new_WebResourceName eq '" + webName + "'";
    var templateId;

    jQuery.ajax({
        type: "GET",
        contentType: "application/json; charset=utf-8",
        datatype: "json",
        url: query,
        async: false,
        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) {
            if (data && data.d != null) {
                templateId = data.d;
            }
        },
        error: function (XmlHttpRequest, textStatus, errorThrown) {
            alert("Error :  has occured during retrieval of the Template");
        }
    });

    return templateId;
}
Update Record:
function Update(id, entityObject, odataSetName) {
        var jsonEntity = window.JSON.stringify(entityObject);
        var serverUrl = Xrm.Page.context.getServerUrl();

        var ODATA_ENDPOINT = "/XRMServices/2011/OrganizationData.svc";
        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
        datatype: "json",
        data: jsonEntity,
        url: serverUrl + ODATA_ENDPOINT + "/" + odataSetName + "(guid'" + id + "')",
        beforeSend: function (XMLHttpRequest) {
            XMLHttpRequest.setRequestHeader("Accept", "application/json");
            XMLHttpRequest.setRequestHeader("X-HTTP-Method", "MERGE");
        },
        success: function (data, textStatus, XmlHttpRequest) {
        },
        error: function (XmlHttpRequest, textStatus, errorThrown) {

            if (XmlHttpRequest && XmlHttpRequest.responseText) {

                alert("Error while updating " + odataSetName + " ; Error – " + XmlHttpRequest.responseText);
            }
        }
    });
}
You can call this function like below;
     var pp = new Object();
     // Update fields
     pp.new_ApprovedOn = "2013/12/06";
     Update(accountId, pp, "accountSet");
MSDN Sample for JSON : http://msdn.microsoft.com/en-us/library/1bb82714-1bd6-4ea4-8faf-93bf29cabaad#BKMK_UsingJQuery

OData System Query Options Using the REST Endpoint : http://msdn.microsoft.com/en-us/library/gg309461.aspx

Tuesday, March 6, 2012

How to pass current view id to Custom web page through ribbon button in CRM 2011

In my recent project I wanted to get all the records which are in current view and do some processing and display those records in a custom web page.

My Approach

1. Get the selected View id
2. pass it to the custom web page as query string through ribbon button.
function LoadRecords() {
var selectedViewId = document.getElementsByTagName("span");

var el = getElementsByAttribute("span", "currentview");
var viewId = el[0].id;

var UserID = GetCurrentUserID();
var sUrl = '/ISV/myCustomPage.aspx?crmuserid=' + UserID + '&viewid=' + viewId;
var sWin = window.open(sUrl, '', 'height=750 ,width=900, left=75, top=50 ,toolbar=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,modal=yes');
}

function getElementsByAttribute(strTagName, strAttributeName) {
var arrElements = document.getElementsByTagName(strTagName);

var arrReturnElements = new Array();
var oCurrent;
var oAttribute;
for (var i = 0; i < arrElements.length; i++) {
oCurrent = arrElements[i];

oAttribute = oCurrent.getAttribute && oCurrent.getAttribute(strAttributeName);
if (typeof oAttribute == "string" && oAttribute.length > 0) {
arrReturnElements.push(oAttribute);
}
}
return arrReturnElements;
}

3. get the selected view from SavedQuery table
public SavedQuery GetSavedQueryById(Guid viewId)
{
SavedQuery savedQuery = null;
if (!viewId.Equals(Guid.Empty))
{
savedQuery = (SavedQuery)service.Retrieve(SavedQuery.EntityLogicalName, viewId, new ColumnSet(true));
}
return savedQuery;
}

4. extract the conditions for selected view from FetchXml column

private Dictionary<string, string> getCoditionListForSelectedView(string selectedView)
{
try
{
Dictionary<string, string; condList = new Dictionary<string, string>();
commonFacadecs = new CommonFacade();
string fetchXML = commonFacadecs.GetSavedQueryById(viewId).FetchXml.ToString();

string formattedXML = XElement.Parse(fetchXML).ToString();

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(formattedXML);
XmlNodeList nodeList = xmlDoc.SelectNodes("/entity");
XmlNodeList nodeList2 = xmlDoc.GetElementsByTagName("condition");

for (int i = 0; i &lt; nodeList2.Count; i++)
{
XmlAttributeCollection xmlAttrc = nodeList2[i].Attributes;
string name = xmlAttrc[0].Value;
string oper = xmlAttrc[1].Value;
string Value = xmlAttrc[2].Value;
condList.Add(oper, Value);
}
return condList;
}
catch (Exception exception)
{
throw
}
}

5.Retrieve records according to the filter condition

Results

Above approach will give you the all the records which are coming from the selected view
then you can do whatever the processing and display it in custom web page.

Sunday, February 26, 2012

Reload CRM 2011 sub-grid manually

Recently I wanted to add a subgrid to the one of my CRM form. It's a simple thing you just want to follow the normal procedure.

1. Settings - Customizations - Customize the System

2. Open the entity form and go to the Insert tab and click on Sub-Grid button


3. Now give a name for "Name" field then select Entity and Default View
ntity form and go to the Insert tab and click on Sub-Grid button

That's it. Save and publish the form.

Normally now all of the sub records should populate in the main form load. But in my case it didn't load the sub grid records, so just had to find a reason for that. actually in my main CRM form there were more than 10 sub grids. Finally I came to know that it will load only first 5 sub grids in the page load. So then we need to manually load my sub grid using javascript. It was not that much default you can simply use the following javascript code.




var grid = document.getElementById("SubGridName");
if (grid != null) {
if (grid.readyState == "complete") {
grid.Refresh();
}
}

MS CRM 2011 KB Article customization Issue.

Recently I have encountered some issue while customizing Kb Article Entity. I was doing following configuration in Article form. 1. Add Ba...