Search This Blog

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

Monday, September 21, 2015

Retrieve record from related entity using XrmServiceToolkit javascript in crm 2013/2015

Download XrmServiceToolkit from here
Extract and upload these files into CRM as javascript webresource and also Add on the form where you need to retrieve
1. Json2
2. jquery
3. XrmServiceToolkit

Code: In this code i retrieve description field from related entity

function get_details()
{
var Courselookup=null;
var coursetitle_name=null;
var CourselookupId=null;

 Courselookup = Xrm.Page.data.entity.attributes.get('new_school');
    if (Courselookup.getValue() != null)
    {   
        CourselookupId = Courselookup.getValue()[0].id;   
        var course_obj = Retrieve(CourselookupId);
        if (course_obj.new_Description != null )
        {
            coursetitle_name=course_obj.new_Description;
            Xrm.Page.getAttribute("new_description").setValue(coursetitle_name);
            Xrm.Page.getAttribute("new_description").setSubmitMode("always");
        }
        }
}
function Retrieve(_id) {
    var re;   
    XrmServiceToolkit.Rest.Retrieve(
              _id,
              "new_schoolSet",
              null, null,
              function (result) {
                  re = result;                
              },
              function (error) {
                  alert("failed");
              },
              false
          );
          return re;
}



Wednesday, September 16, 2015

Retrieve Lookup value from related entity using javascript + xrmsvctoolkit in crm 2013

    Courselookup = Xrm.Page.data.entity.attributes.get('cms_courseid');
    if (Courselookup.getValue() != null)
    {
        CourselookupId = Courselookup.getValue()[0].id;   
        var course_obj = RecRetrieve(CourselookupId, "cms_course");

if (course_obj.cms_CourseSubArea.Id != null )
        {
           
               var arr_CourseSubArea = new Array();
            //Create an Object add to the array.           
           var obj_CourseSubArea= new Object();               
           obj_CourseSubArea.id = course_obj.cms_CourseSubArea.Id;
            obj_CourseSubArea.typename = 'cms_coursesubarea';//name of entity from where data retrieve
           obj_CourseSubArea.name = course_obj.cms_CourseSubArea.Name;
           arr_CourseSubArea[0] = obj_CourseSubArea;          
            // Set the value of the lookup field to the value of the array.
            Xrm.Page.getAttribute("cms_coursesubarea").setValue(arr_CourseSubArea);   
            Xrm.Page.getAttribute("cms_coursesubarea").setSubmitMode("always");        
        }
}
function RecRetrieve(_id, _entityname)
 {
 var _result;
    XrmSvcToolkit.retrieve({
        entityName: _entityname,
        id: _id,
        async: false,
        successCallback: function (result) {
            _result = result;
        },
        errorCallback: function (error) {
           alert("Error");

        }
    });
    return _result;
}

Saturday, October 25, 2014

Filter Lookup values in CRM 2011 and CRM 2013 without Javascript

In this Example I filter cities of a country. Follow following steps:

  •  Every country have many cities, so i create a 1:N relationship of cities with country entity i.e. in city entity i have lookup of country entity. 
  • Now in Account entity i create two lookups one of Country entity and second city entity.

  • In city entity I added some sample records of cities and also select their country so that city will be filtered related to that country.                                                                                     



  • Now open lookup of city and edit filter record settings as shown in below image. 





  • Filtered records are shown below that When I select country Pakistan only cities related to Pakistan are shown and when I select country Afghanistan only cities related to Afghanistan are shown.                                                                                                                                  















Thursday, October 23, 2014

Change Optionset Values on change of other optionset values using JavaScript in Microsoft Dynamics CRM 2011 and 2013

function optionSetChanged() // apply this function of change of country field
{

    // on the base of country change cities

    var _collection = getCollection();
    var _selectedCity = null;
    var _cityOptionset = Xrm.Page.ui.controls.get("city");  
if (_cityOptionset != null)
    _selectedCity = _cityOptionset.getAttribute().getValue();
var _cityOptions = _cityOptionset.getAttribute().getOptions();
    var _selectedCountry = Xrm.Page.getAttribute("Country").getText();    
    // If Country is empty, then clear the City field.
    if (_selectedCountry == "")
{
        _cityOptionset.clearOptions();
    }
    else
{
        for (var i = 0; i < _collection.length; i++)
{          
if (_selectedCountry.toLowerCase() == _collection[i].Country.toLowerCase())
{                _
cityOptionset.clearOptions();
            for (var j = 0; j < _collection[i].Cities.length; j++)
{                  
for (var k = 0; k < _cityOptions.length; k++)
{                      
if (_collection[i].Cities[j].toLowerCase() == _cityOptions[k].text.toLowerCase())
{                          
_cityOptionset.addOption(_cityOptions[k]);
                        break;
                        }
                    }
                }
                break;
            }
        }    
if (_cityOptionset != null && _selectedCity != null)
            _cityOptionset.getAttribute().setValue(_selectedCity);
    }
}


function getCollection() {

    var _collection = new Array();  
var India_Cities = new Array("NewYork");
    var India_obj = { Country: "USA", Cities: India_Cities };
    _collection.push(India_obj);

    var Srilanka_Cities = new Array("Lahore");
    var SriLanka_obj = { Country: "pakistan", Cities: Srilanka_Cities };
    _collection.push(SriLanka_obj);

    var USA_Cities = new Array("Mumbai");
    var USA_obj = { Country: "India", Cities: USA_Cities };
    _collection.push(USA_obj);

    return _collection;
}

Thursday, September 25, 2014

Run Workflow using javascript CRM 2013

only change GUID of your workflow
function RunWorkflow() {
     var _return = window.confirm('Are you want to execute workflow.');
     if (_return) {
         var url = Xrm.Page.context.getServerUrl();
         var entityId = Xrm.Page.data.entity.getId();
         var workflowId = '87038619-3DA9-47A9-92A8-263E5C0533B4';
         var OrgServicePath = "/XRMServices/2011/Organization.svc/web";
         url = url + OrgServicePath;
         var request;
         request = "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\">" +
                       "<s:Body>" +
                         "<Execute xmlns=\"http://schemas.microsoft.com/xrm/2011/Contracts/Services\" xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">" +
                           "<request i:type=\"b:ExecuteWorkflowRequest\" xmlns:a=\"http://schemas.microsoft.com/xrm/2011/Contracts\" xmlns:b=\"http://schemas.microsoft.com/crm/2011/Contracts\">" +
                             "<a:Parameters xmlns:c=\"http://schemas.datacontract.org/2004/07/System.Collections.Generic\">" +
                               "<a:KeyValuePairOfstringanyType>" +
                                 "<c:key>EntityId</c:key>" +
                                 "<c:value i:type=\"d:guid\" xmlns:d=\"http://schemas.microsoft.com/2003/10/Serialization/\">" + entityId + "</c:value>" +
                               "</a:KeyValuePairOfstringanyType>" +
                               "<a:KeyValuePairOfstringanyType>" +
                                 "<c:key>WorkflowId</c:key>" +
                                 "<c:value i:type=\"d:guid\" xmlns:d=\"http://schemas.microsoft.com/2003/10/Serialization/\">" + workflowId + "</c:value>" +
                               "</a:KeyValuePairOfstringanyType>" +
                             "</a:Parameters>" +
                             "<a:RequestId i:nil=\"true\" />" +
                             "<a:RequestName>ExecuteWorkflow</a:RequestName>" +
                           "</request>" +
                         "</Execute>" +
                       "</s:Body>" +
                     "</s:Envelope>";
         var req = new XMLHttpRequest();
         req.open("POST", url, true)
         // Responses will return XML. It isn't possible to return JSON.
         req.setRequestHeader("Accept", "application/xml, text/xml, */*");
         req.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
         req.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/xrm/2011/Contracts/Services/IOrganizationService/Execute");
         req.onreadystatechange = function () { assignResponse(req); };
         req.send(request);
     }
 }
 function assignResponse(req) {
     if (req.readyState == 4) {
         if (req.status == 200) {
             alert('successfully executed the workflow');
         }
     }
 }

Friday, July 11, 2014

Make field mode always same

So if you want to save a read only field you need to set the SubmitMode to be always, which ensures the value is sent to the database.



Xrm.Page.getAttribute("fieldName").setSubmitMode("always");

Monday, June 2, 2014

Retrieve Record using Odata query filter with GUID of Record



var GroupId = Xrm.Page.data.entity.getId();
var _query = "?$filter=new_GroupId/Id eq (Guid'"+ GroupId +"')";
var obj = RecRetrieveMultiple(_query, 'new_student');

Retrieve Multiple Records Using Odata and Using Soap library


First Download xrmsvctoolkit library from here

Case: Apply code on account form and get account id and use this account id to check how many contacts are against that account id in retrieve multiple using OData.

function get_call()
{             
                var GUIDvalue = Xrm.Page.data.entity.getId();
                //alert(GUIDvalue);
                var lookupObject = Xrm.Page.getAttribute("primarycontactid");
                var lookUpObjectValue = lookupObject.getValue();
                var query = "?$filter=ParentCustomerId/Id eq (Guid'"+GUIDvalue+"')";
                var obj1 = get_Multiple(query,"Contact");
                //var obj1 = get_Multiple(lookUpObjectValue[0].id,"Contact");
                if(obj1==null)
                {
                                alert("I am null");
                }
                else
                {
                                alert(obj1.FullName+"currency : "+obj1.TransactionCurrencyId.type+obj1.TransactionCurrencyId.Name);
                }
                //for (var indx = 0; indx < obj1.length; indx++)
                //{
                                //alert("Name – " + obj1[indx].FullName + " "+"mobile  no: "+obj1.MobilePhone);
                //}
}
function get_Multiple(_query,_entitynames)
{

    XrmSvcToolkit.retrieveMultiple({
        entityName: _entitynames,
        async: false,
        odataQuery: _query,//"?$filter=FirstName eq 'Jim'  and EMailAddress1 eq 'someone@example.com' ",
        successCallback: function (result) {
            contacts = result;
        },
        errorCallback: function (error) {
           alert("Error");
        }
    });
                alert(contacts.length);
    var contact = contacts[0];
                return contact;
}

Thursday, January 2, 2014

Disable Lead Ribbon button using javascript in CRM 2011 and 2013

var x= top.document.getElementById("lead|NoRelationship|Form|Mscrm.Form.lead.ConvertLeadQuick-Large");
x.disabled = true;

Set Notification in Form and clear Notification

Xrm.Page.ui.setFormNotification('Please Fill the Required Fields for this Stage' ,'INFORMATION','3');// set notification

Xrm.Page.ui.clearFormNotification('3'); // clear notification


Refresh Ribbon using javascript in crm 2011 and 2013

Xrm.Page.ui.refreshRibbon();

Run dialogue by clicking Button

function project_code()//project code button
{
var dialogId = "{E8F6C5EC-E606-447E-B253-C950FB6F29B2}"; // dialogue id
var typeName = "salesorder";
var recordId = Xrm.Page.data.entity.getId();
LaunchModalDialog(dialogId,typeName,recordId);
//alert("project code");
}

function project_manager()//project manager button
{
var dialogId = "{6322F944-7202-4EDF-81A0-3EFAB678068D}"; // dialogue id
var typeName = "salesorder";
var recordId = Xrm.Page.data.entity.getId();
LaunchModalDialog(dialogId,typeName,recordId);
//alert("project manager");
}
//**This function will run buttons and dialogs working on these button**//
function LaunchModalDialog(dialogId,typeName,recordId)
{
    var serverUrl = Xrm.Page.context.getServerUrl();
    recordId=recordId.replace("{", "");
    recordId=recordId.replace("}", "");
   
    dialogId=dialogId.replace("{", "");
    dialogId=dialogId.replace("}", "");
   
   //var project_code_id = {E8F6C5EC-E606-447E-B253-C950FB6F29B2};
   //var project_manager_id = {6322F944-7202-4EDF-81A0-3EFAB678068D};

   var serverUri = serverUrl +'/cs/dialog/rundialog.aspx';
   var mypath =  serverUri +'?DialogId=%7b' +dialogId.toUpperCase()  +'%7d&EntityName=' + typeName+'&ObjectId=%7b' +recordId+'%7d';
 
   //var mypath =  serverUri +'?DialogId=%7b' +project_code_id.toUpperCase()  +'%7d&EntityName=' + typeName+'&ObjectId=%7b' +recordId+'%7d';
   // First item from selected contacts only
   window.showModalDialog(mypath);
 
   // Reload form.
   window.location.reload(true);
}

Friday, December 6, 2013

Get lookup value and also set into other field

var P_lookupValue = new Array();             
P_lookupValue[0] = new Object();
P_lookupValue[0].id = lookup.Id;
P_lookupValue[0].name = lookup.Name;
P_lookupValue[0].entityType = "lookup_name";
              
Xrm.Page.getAttribute("field_name").setValue(lookupValue); //set lookup value into field
Xrm.Page.data.entity.attributes.get("field_name").setSubmitMode("always"); // this line will set value if field is readonly

Enable and Disable Section

Xrm.Page.ui.tabs.get('tab_name').sections.get('section_name').setVisible(false);

Enable and disable fields

Xrm.Page.ui.controls.get("fieldname").setDisabled(false); // to enable field
Xrm.Page.ui.controls.get("fieldname").setDisabled(true);// to diable field

Get OptionSet Value

var optionSet = Xrm.Page.data.entity.attributes.get("optionsetname");
var optionSetValue = optionSet.getValue();