Monday, May 27, 2013

Opening Forms using the Xrm.Utility.openEntityForm



Using the openEntityForm

Opening a New Form

To simply open a form for creating a new record you can use the following line of code. Simply replace account with the entity of your choice.

Xrm.Utility.openEntityForm("account");

Open a Form with an Existing Record

If you want to open a specific record you just add the guid for that record like this:

Xrm.Utility.openEntityForm("account","A85C0252-DF8B-E111-997C-00155D8A8410″);

Disable / Enable fields, sections, tabs and the whole Form in MS CRM 2011


When working with the MS CRM form , Your requirement will be to enable (set to read/write) or disable (set to read / only) selected fields, sections, tabs and the Whole form.

Please have a glance below code for these functionalities to work out.

1)     Enable / Disable a field

Xrm.Page.getControl(“fieldname”).setDisabled(false);

2)    Enable / Disable a Section

function sectiondisable (sectionname, disablestatus)

{

var ctrlName = Xrm.Page.ui.controls.get();

for(var i in ctrlName) {

var ctrl = ctrlName[i];

var ctrlSection = ctrl.getParent().getName();

if (ctrlSection == sectionname) {

ctrl.setDisabled(disablestatus);

}

}

}  // sectiondisable

3)    Enable / Disable a Tab

function tabdisable (tabname, disablestatus)
{
 var tab = Xrm.Page.ui.tabs.get(tabname);
 if (tab == null) alert("Error: The tab: " + tabname + " is not on the form");
 else {
     var tabsections =  tab.sections.get();
     for (var i in tabsections) {
         var secname = tabsections[i].getName();
         sectiondisable(secname, disablestatus);
     }
  }
}   // tabdisable


4)    Enable / Disable a Form

function formdisable(disablestatus)
{
    var allAttributes = Xrm.Page.data.entity.attributes.get();
    for (var i in allAttributes) {
           var myattribute = Xrm.Page.data.entity.attributes.get(allAttributes[i].getName());
           var myname = myattribute.getName();        
           Xrm.Page.getControl(myname).setDisabled(disablestatus);
    }
} // formdisable

5)     Enable / Disable All Controls in the TAB

function DisableAllControlsInTab(tabControlNo)
{
var tabControl = Xrm.Page.ui.tabs.get(tabControlNo);
    if (tabControl != null)
{  
      Xrm.Page.ui.controls.forEach
(
     function (control, index)
{        
if (control.getParent().getParent() == tabControl && control.getControlType() != "subgrid")
{              control.setDisabled(true);
        }    
});
      }
 }
function EnableAllControlsInTab(tabControlNo)
 {    
var tabControl = Xrm.Page.ui.tabs.get(tabControlNo);    
if (tabControl != null)
{      
 Xrm.Page.ui.controls.forEach
(    
function (control, index)
{        
if (control.getParent().getParent() == tabControl && control.getControlType() != "subgrid")
{            
control.setDisabled(false);
        }
    });
    }
 }
 Hope this will help.

Regards,

Friday, May 24, 2013

Get Required Attendee(Activity Party) value from Appointment.


Guid Id = new Guid("D77839B3-CBC2-E211-8DC3-B4B52F6714CA");
            XrmServiceContext _context = new XrmServiceContext(_service);
            Appointment appointment = _context.AppointmentSet.Where(p=>p.ActivityId==Id).SingleOrDefault();
            if (appointment != null)
            {
               
                EntityCollection receipt = new EntityCollection();
                receipt = appointment.GetAttributeValue<EntityCollection>("requiredattendees");
                for (int i = 0; i < receipt.Entities.Count; i++)
                {
                    ActivityParty ap = receipt[i].ToEntity<ActivityParty>();

                    string id,name;

                    if (ap.PartyId.LogicalName == "account")
                    {
                        id = ap.PartyId.Id.ToString();
                        name = ap.PartyId.Name;
                    }
                    if (ap.PartyId.LogicalName == "contact")
                    {
                        id = ap.PartyId.Id.ToString();
                        name = ap.PartyId.Name;
                    }
                    if (ap.PartyId.LogicalName == "systemuser")
                    {
                        id = ap.PartyId.Id.ToString();
                        name = ap.PartyId.Name;
                    }
                }
            }

Thursday, May 23, 2013

Find the day of the week.


 var startday = Xrm.Page.getAttribute("new_quotestart").getValue().getDay();

Find the Number of Days between two Days.



function CalculateDaysOpen()
{
        var FormType = Xrm.Page.ui.getFormType();
        if (FormType != null && FormType==2)
{
                  var currentDate=new Date();
 var createdDate=Xrm.Page.data.entity.attributes.get("createdon").getValue();
                  cycletime = Math.abs(currentDate- createdDate)
          alert(Math.round(cycletime / 86400000));
         }
}

Get Current User's Teams in crm 2011 using javascript.


function GetCurrentUserTeams() {

  var user = Xrm.Page.context.getUserId();
  var userId = user.substring(1,37);

    var xml = "" +
    "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
    "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">" +
    GenerateAuthenticationHeader() +
    " <soap:Body>" +
    " <RetrieveMultiple xmlns=\"http://schemas.microsoft.com/crm/2007/WebServices\">" +
    " <query xmlns:q1=\"http://schemas.microsoft.com/crm/2006/Query\" xsi:type=\"q1:QueryExpression\">" +
    " <q1:EntityName>team</q1:EntityName>" +
    " <q1:ColumnSet xsi:type=\"q1:ColumnSet\">" +
    " <q1:Attributes>" +
    " <q1:Attribute>name</q1:Attribute>" +
    " </q1:Attributes>" +
    " </q1:ColumnSet>" +
    " <q1:Distinct>false</q1:Distinct>" +
    " <q1:LinkEntities>" +
    " <q1:LinkEntity>" +
    " <q1:LinkFromAttributeName>teamid</q1:LinkFromAttributeName>" +
    " <q1:LinkFromEntityName>team</q1:LinkFromEntityName>" +
    " <q1:LinkToEntityName>teammembership</q1:LinkToEntityName>" +
    " <q1:LinkToAttributeName>teamid</q1:LinkToAttributeName>" +
    " <q1:JoinOperator>Inner</q1:JoinOperator>" +
    " <q1:LinkCriteria>" +
    " <q1:FilterOperator>And</q1:FilterOperator>" +
    " <q1:Conditions>" +
    " <q1:Condition>" +
    " <q1:AttributeName>systemuserid</q1:AttributeName>" +
    " <q1:Operator>Equal</q1:Operator>" +
    "<q1:Values>" +
    //code to get the owner
    "<q1:Value xsi:type=\"xsd:string\">" + userId + "</q1:Value>" +
    "</q1:Values>" +

    " </q1:Condition>" +
    " </q1:Conditions>" +
    " </q1:LinkCriteria>" +
    " </q1:LinkEntity>" +
    " </q1:LinkEntities>" +
    " </query>" +
    " </RetrieveMultiple>" +
    " </soap:Body>" +
    "</soap:Envelope>" +
    "";
    var xmlHttpRequest = new ActiveXObject("Msxml2.XMLHTTP");
    xmlHttpRequest.Open("POST", "/mscrmservices/2007/CrmService.asmx", false);
    xmlHttpRequest.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/crm/2007/WebServices/RetrieveMultiple");
    xmlHttpRequest.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
    xmlHttpRequest.setRequestHeader("Content-Length", xml.length);
    xmlHttpRequest.send(xml);
    var resultXml = xmlHttpRequest.responseXML;
    //alert(resultXml.xml);

    // Save all entity nodes in an array.
    var entityNodes = resultXml.selectNodes("//RetrieveMultipleResult/BusinessEntities/BusinessEntity");

    var teamnames = new Array();
    var teamids = new Array();

    for (var i = 0; i < entityNodes.length; i++) {

        var entityNode = entityNodes[i];
        var teamidNode = entityNode.selectSingleNode("q1:teamid");
        var teamNode = entityNode.selectSingleNode("q1:name");
        var teamid = (teamidNode == null) ? null : teamidNode.text;
        var team = (teamNode == null) ? null : teamNode.text;

        teamnames[i] = team;
        teamids[i] = teamid;
    }

    alert(teamnames);
}


Above script will not work in CRM 2013. For CRM 2013,the script is as below

function GetCurrentUserTeams()
{
    var teamName="Communities Team";
if (teamName != null && teamName != "") {
// build endpoint URL
var serverUrl = Xrm.Page.context.getServerUrl();
var oDataEndpointUrl = serverUrl + "/XRMServices/2011/OrganizationData.svc/";
// query to get the teams that match the name
oDataEndpointUrl += "TeamSet?$select=Name,TeamId&$filter=Name eq '" + teamName + "'";
var service = GetRequestObject();
if (service != null) {
// execute the request
service.open("GET", oDataEndpointUrl, false);
service.setRequestHeader("X-Requested-Width", "XMLHttpRequest");
service.setRequestHeader("Accept", "application/json,text/javascript, */*");
service.send(null);
// parse the results
var requestResults = eval('(' + service.responseText + ')').d;
if (requestResults != null && requestResults.results.length > 0) {
var teamCounter;
// iterate through all of the matching teams, checking to see if the current user has a membership
for (teamCounter = 0; teamCounter < requestResults.results.length; teamCounter++) {
var team = requestResults.results[teamCounter];
var teamId = team.TeamId;
// get current user teams
var currentUserTeams = getUserTeams(teamId);
// Check whether current user teams matches the target team
if (currentUserTeams != null) {
for (var i = 0; i < currentUserTeams.length; i++) {
var userTeam = currentUserTeams[i];
// check to see if the team guid matches the user team membership id
if (GuidsAreEqual(userTeam.TeamId, teamId)) {
return true;
}
}
}
else {
return false;
}
}
}
else {
alert("Team with name '" + teamName + "' not found");
return false;
}
return false;
}
 }
 else {
 alert("No team name passed");
 return false;
 }
}
function getUserTeams(teamToCheckId) {
 // gets the current users team membership
 var userId = Xrm.Page.context.getUserId().substr(1, 36);
 var serverUrl = Xrm.Page.context.getServerUrl();
 var oDataEndpointUrl = serverUrl + "/XRMServices/2011/OrganizationData.svc/";
 oDataEndpointUrl += "TeamMembershipSet?$filter=SystemUserId eq guid' " + userId + " ' and TeamId eq guid' " + teamToCheckId + " '";
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 > 0) {
 return requestResults.results;
 }
 }
}
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) {
 // compares two guids
 var isEqual = false;
 if (guid1 == null || guid2 == null) {
 isEqual = false;
 } else {
 isEqual = (guid1.replace(/[{}]/g, "").toLowerCase() == guid2.replace(/[{}]/g, "").toLowerCase());
 }
 return isEqual;
}

Thursday, May 16, 2013

How to use Multivalued Parameter in Fetch XML based report in CRM 2011 online.


 you can use like this.
<filter type="and">
        <condition attribute="ownerid" operator="in" value="@UserName"/>
  </filter>

or using like


<filter type="and">
        <condition attribute="fullname" operator="like" value="@fname"/>
 </filter>

Monday, May 13, 2013

How to calculate current age from Date of Birth using Javascript in Dynamics CRM 2011


function CalculateAge()
    {
    if(Xrm.Page.getAttribute("birthdate").getValue() != null)
    {
           var currentdate = new Date();
           var birthdate = Xrm.Page.getAttribute("birthdate").getValue();
           var monthdiff = currentdate.getMonth() - birthdate.getMonth();          
       var currentage;
 
           if(monthdiff > -1)
           {
        currentage = currentdate.getFullYear() - birthdate.getFullYear();                    
                Xrm.Page.getAttribute("new_currentage").setValue(currentage);
           }
           else
           {
        currentage = currentdate.getFullYear() - birthdate.getFullYear() - 1
                Xrm.Page.getAttribute("new_currentage").setValue(currentage);
           }
    }
    }

Sunday, May 12, 2013

How to add Month in given date using Jscript.


 var startdate=Xrm.Page.data.entity.attributes.get(startingdate).getValue();
 var duration=Xrm.Page.data.entity.attributes.get(nodays).getValue();
  var endwarrantydate=Xrm.Page.data.entity.attributes.get(endingdate);
  if(startdate!=null && duration!=null)
  {            
var enddate= startdate.setMonth(startdate.getMonth() + duration);
        endwarrantydate.setValue(enddate);
  }