CRM 2011 Javascript etiketine sahip kayıtlar gösteriliyor. Tüm kayıtları göster
CRM 2011 Javascript etiketine sahip kayıtlar gösteriliyor. Tüm kayıtları göster

CRM 2013/ 2015/2016 Javascript - Form Reload

(Reload an entity form in Dynamics CRM 2013/ 2015/2016)

CRM 2013 ten itibaren form save edildiğinde formun tamamı yenilenmez. Daha önceleri formu yenilemek için çoğunlukla window.location.reload(true) yöntemini kullanırdık.

Yeni versiyonlarda Xrm.Page.data.refresh(true|false) ve Xrm.Page.ui.refreshRibbon() yöntemiyle ribbon ve data bölümünü asenkron olarak güncelleyebiliriz.

Tüm formu yeniden yüklemek istediğmizde ise Xrm.Utility.openEntityForm ile işlem yapmamız gerekecektir.

Xrm.Utility.openEntityForm(“account”, Xrm.Page.data.entity.getId());

Örnek;

Crm formundan açtığımız page sonrası formu load işlemine zorlamak istersek aşağıdaki yöntemi kullanabiliriz.


 var win = window.open(url, 'Rapor', features);
            var timer = setInterval(function () {
                if (win.closed) {
                    clearInterval(timer);
                    //window.location.reload(true);

                    // Save the current record to prevent messages about unsaved changes
                    Xrm.Page.data.entity.save();

                    setTimeout(function () {
                        // Call the Open Entity Form method and pass through the current entity name and ID to force CRM to reload the record
                        Xrm.Utility.openEntityForm(Xrm.Page.data.entity.getEntityName(), Xrm.Page.data.entity.getId());
                    }, 3000);
                }

            }, 1000);

CRM 2011 Javascript - Custom Buton ile Form Kaydederken Form Üzerindeki Zorunlu Alanlar Kontrolu

Bazı durumlarda formun kaydedilmesi için custom buttonlar kullanabiliriz. Bu gibi durumlarda kendi kontrolumuzu yapmaya ihtiyacımız oldugunda aşagıdakı metodu kullanabiliriz.

function IsFormValidForSaving() {
    var valid = true;
    Xrm.Page.data.entity.attributes.forEach(function (attribute, index) {
        if (attribute.getRequiredLevel() == "required") {
            if (attribute.getValue() == null) {
                if (valid) {
                    var control = attribute.controls.get(0);
                    alert("You must provide a value for" + " " + control.getLabel());
                    control.setFocus();
                }
                valid = false;
            }
        }
    });
    return valid;
}

CRM 2011 Javascript - CRM Formu Maximum Yapma

Aşağıdaki script kodu ile crm formunu maximum yapabilirsiniz.Yapacağınız işlem form onload eventinde aşağıdaki metodu çağırmanız.


function maximizeCRMFORM() {
  window.top.moveTo(0, 0);
  window.top.resizeTo(screen.availWidth, screen.availHeight);
}


CRM 2011 - Form Kaydetmeyi Engelleme (CANCELING THE SAVE OPERATION)

CRM formlarında bazı durumlarda formun kaydetilmesin engellemk isteyebiliriz . Bu işlemi Javascript yazarak gerçekleştirebiliriz. (Bu işlemi form save metotlarında yapabiliyoruz)

Öncelikle CRM 2011 R12 den önceki versiyonlarda event.returnValue=false ile bu işlem yapılabiliyordu.Ama bu kod satrı sadece IE tarayıcılarında çalışmaktadır . Tüm tarayıcılarda ise aşağıdaki yöntem geçerlidir.

İşlemi gerçekleştirmek için bir Javascript kütüphenesine metot yazacağız. Bunu Form Save anında çağıracağız. Dikkat edilmesi gereken şey Form Save anında metotumuzu eklerken "Pass execution context as first parameter" seçeneğinin seçilmesi gerekir.

Aşağıdaki örnekte Account formunda TcNo yu girmeden formu kaydettirmemeyi sağlayacağız.

Account formuna web resource ekleyelim.




Bir sonraki adımda Form Save eventine metotumuzu ekleyelim.



Not: Pass execution context as first parameter seçeneğini işaretlemezsek işlem çalışmayacaktır.

Kaydetmeyi engelleyen script kodu   executionObj.getEventArgs().preventDefault()

new_AccountSaveLibrary.js kod

function Account_Form_OnSave(executionObj) {
    try {
        var tcNo = Xrm.Page.getAttribute("accountnumber").getValue();
        var vergiDairesi = Xrm.Page.getAttribute("new_vd").getValue();
        var vergiNo = Xrm.Page.getAttribute("new_vergino").getValue();

        if ((tcNo !=null && tcNo !="") || (vergiNo !=null && vergiNo !="") || (vergiDairesi !=null && vergiDairesi !="")) {

            if (vergiNo != null && vergiNo != "") {
                if (!(vergiDairesi != null && vergiDairesi != "")) {
                    alert("Vergi Dairesi alanı boş bırakılmamalıdır.");
                    executionObj.getEventArgs().preventDefault();
                }
            }

            if (vergiDairesi != null && vergiDairesi != "") {
                if (!(vergiNo != null && vergiNo != "")) {
                    alert("Vergi No alanı boş bırakılmamalıdır.");
                    executionObj.getEventArgs().preventDefault();
                }
            }
        }
        else {
            alert("TC Kimlik No veya Vergi Alanlarından en az biri dolu olmalıdır.");
            executionObj.getEventArgs().preventDefault();
        }

    } catch (e) {
        alert("An error occured in Account_Form_OnSave Function.Message :" + e.message);
    }
}



Yukarıdaki metotta firma formunu kaydetmeye çalıştığımızda tcno veya vergi alanlarından herhangi biriinin doldurulması şartı aranıyor . Ayrıca vergi alanları girilecekse ikisininde girilmesi gerekir.

İlk baş ilgili alanlardan hiçbirini girmeden Kaydet butonuna basalım.




Sadece Vergi No alanını girelim.Kaydet butonuna basalım




Sadece Vergi Dairesi alanını girelim.Kaydet butonuna basalım




CRM 2011 Javascript Library


CRM 2011 Javascript - OptionSet Kullanımı


if (typeof (opt) == "undefined") { opt = {}; }

opt.getValues = function (fieldName) {
    var values = [];
    var attribute = Xrm.Page.getAttribute(fieldName);
    if (attribute != null && attribute.getAttributeType() == "optionset") {
        var options = attribute.getOptions();
        for (var i in options) {
            if (options[i].value != "null") values.push(options[i].value * 1);
        }
    }
    return values;
};

opt.getLabels = function (fieldName) {
    var labels = [];
    var attribute = Xrm.Page.getAttribute(fieldName);
    if (attribute != null && attribute.getAttributeType() == "optionset") {
        var options = attribute.getOptions();
        for (var i in options) {
            if (options[i].value != "null") labels.push(options[i].text);
        }
    }
    return labels;
};

opt.getLabel = function (fieldName, value) {
    var label = "";
    var attribute = Xrm.Page.getAttribute(fieldName);
    if (attribute != null && attribute.getAttributeType() == "optionset") {
        var option = attribute.getOption(value);
        if (option != null) label = option.text;
    }
    return label;
};

opt.getValue = function (fieldName, label) {
    if (label == "") return null;
    var value = null;
    var attribute = Xrm.Page.getAttribute(fieldName);
    if (attribute != null && attribute.getAttributeType() == "optionset") {
        var options = attribute.getOptions();
        for (var i in options) {
            if (options[i].text == label) return options[i].value * 1;
        }
    }
    return value;
};


Kullanimi

opt.GetValues(fieldName)
opt.GetLabels(fieldName)
opt.GetLabel(fieldName, value)
opt.GetValue(fieldName, label)

CRM 2011 - Tarih Alanı Default Olarak Bugün Yapma

Bu işlemi gerçekleştirmemiz için form yüklenrken ilgili tarih alanına javascript ile bugunun tarihinin atanmasıdır.

Bu işlem için Create formunun onload ına bir script yazalım. Örnek script kodu şağıdadır.

function setToday() {
     var formType=Xrm.Page.ui.getFormType();    
     if (formType == 1) {
         Xrm.Page.getAttribute(dateField).setValue(new Date());  
     }
 }

Yukarıdaki setToday function ını onload da çağırmamız yeterli olacaktır.

CRM 2011 Javascript - Lokup Alanın Id sini Alma (Get Lookup Id)


function GetLookupId(fieldName) {
    var lookupObject = Xrm.Page.getAttribute(fieldName).getValue();
    if (lookupObject != null && lookupObject != undefined) {
        if (lookupObject[0].id != "")
            return lookupObject[0].id;
    }

    return "00000000-0000-0000-0000-000000000000";
}

CRM 2011 Javascript - Kullanıcı Takımlarını Alma (Get User Teams)

function GetUserTeams(userid) {
    var teamList = new Array();

    try {
        var query = "TeamMembershipSet?$select=TeamId,SystemUserId&$filter=SystemUserId eq guid'" + ConverttoStringFromGuid(userid) + "'";
        var teamMemmberShipEntity = ODataRetrieveMultipleAjax(query);
        if (teamMemmberShipEntity != null && teamMemmberShipEntity.results != null && teamMemmberShipEntity.results.length != 0) {
            for (var i = 0; i < teamMemmberShipEntity.results.length; i++) {
                if (teamMemmberShipEntity.results[i] != null) {
                    var _teamid = teamMemmberShipEntity.results[i].TeamId;
                    if (_teamid != null) {
                        var query2 = "TeamSet?$select=TeamId,Name&$filter=TeamId eq guid'" + ConverttoStringFromGuid(_teamid) + "'";
                        var teamEntity = ODataRetrieveMultipleAjax(query2);
                        if (teamEntity != null && teamEntity.results != null && teamEntity.results.length != 0) {
                            if (teamEntity.results.length == 1 && teamEntity.results[0] != null) {
                                teamList[teamList.length] = teamEntity.results[0].Name.toUpperCase();
                            }
                        }
                    }
                }
            }
        }
    }
    catch (e) {
        alert("An error occured in GetUserTeams Function.Message :" + e.message);
    }

    return teamList;
}



function ConverttoStringFromGuid(guidid) {
    if (guidid != null && guidid != "") {
        return guidid.toString().replace('{', '').replace('}', '').toUpperCase();
    }

    return "00000000-0000-0000-0000-000000000000";
}

function ODataRetrieveMultipleAjax(oDataSelect) {
    var crmOrgSvc = Xrm.Page.context.prependOrgName("/xrmservices/2011/OrganizationData.svc/");
    var result = null;

    oDataSelect = crmOrgSvc + oDataSelect;
    jQuery.support.cors = true;

    $.ajax({
        type: "GET",
        contentType: "application/json; charset=utf-8",
        datatype: "json",
        url: oDataSelect,
        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 != null && data.d != null) {
                result = data.d;
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert("Status: " + textStatus + "; ErrorThrown: " + errorThrown, "Error Function:" + "ODataRetrieveMultipleAjax");
        }
    });
    return result;
}

CRM 2011 Javascript - Form Kullanıcısının Id sini Alma (Get Current User Id)

Aşağıdaki metot bize formu açan kullanıcını Guid değerini verecektir.

function GetCurrentUserId() {
    return Xrm.Page.context.getUserId();
}

CRM 2011 Javascript - Organizasyon Data Servisin URL ini Alma (Get Organization Data Service)

Javascript üzerinden odatasquery üzerinden sorgulama yapmak için bize organization data servisin url gereklidir.

Bu bilgiye CRM üzerinden erişip string olarak sabit yazabiliriz ama CRM i farklı bir makineye taşıdığımızda bu alanı güncellememiz gerekecektir.Bunun yerine aşağıdaki javascript metodunu kullanalım.

function GetOrganizationDataService() {
    return Xrm.Page.context.prependOrgName("/xrmservices/2011/OrganizationData.svc/");
}


CRM üzerinden Organization Data Servis e Ulaşım

Settings  - Customizations - Developer Resources



CRM 2011 Javascript - Varlık Id sini Alma (Get EntityId)

function GetEntityId() {
    return Xrm.Page.data.entity.getId();
}

CRM 2011 Javascript - Organizasyonun Adını Alma (Get OrganizationName)

function GetOrganizationName() {
    return Xrm.Page.context.getOrgUniqueName();
}

CRM 2011 Javascript - Kullanıcı Departmanını Alma (Get User Departman)


function GetUserDepartman() {
    try {
        var result = "";
        var userid = Xrm.Page.context.getUserId();
        var query = "SystemUserSet?$select=SystemUserId,BusinessUnitId&$filter=SystemUserId eq guid'" + ConverttoStringFromGuid(userid) + "'";
        var userEntity = ODataRetrieveMultipleAjax(query);
        if (userEntity != null && userEntity.results[0] != null) {
            if (userEntity.results[0].BusinessUnitId != null && userEntity.results[0].BusinessUnitId.Id != null) {
                result = userEntity.results[0].BusinessUnitId.Name;
            }
        }

        return result;
    } catch (e) {
        alert("Function GetUserDepartman()\n" + e.message);
        return "";
    }
}

function ConverttoStringFromGuid(guidid) {
    if (guidid != null && guidid != "") {
        return guidid.toString().replace('{', '').replace('}', '').toUpperCase();
    }

    return "00000000-0000-0000-0000-000000000000";
}

function ODataRetrieveMultipleAjax(oDataSelect) {
    var crmOrgSvc = Xrm.Page.context.prependOrgName("/xrmservices/2011/OrganizationData.svc/");
    var result = null;

    oDataSelect = crmOrgSvc + oDataSelect;
    jQuery.support.cors = true;

    $.ajax({
        type: "GET",
        contentType: "application/json; charset=utf-8",
        datatype: "json",
        url: oDataSelect,
        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 != null && data.d != null) {
                result = data.d;
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert("Status: " + textStatus + "; ErrorThrown: " + errorThrown, "Error Function:" + "ODataRetrieveMultipleAjax");
        }
    });
    return result;
}


CRM Javascript - Lookup Alana Değer Atama


function SetLookupValue(idValue, textValue, typeValue) {
    var value = new Array();
    value[0] = new Object();
    value[0].id = idValue;
    value[0].name = textValue;
    value[0].entityType = typeValue;

    return value;
}

SetLookupValue("{8234371E-07DF-E211-81A8-0050569505A4}", "Test", "account");

CRM Javascript - IFRAME URL İşlemleri


Aşağıdaki function da url varsa iframe atanır , url yoksa iframe gilenir.

function SetIFRAMEURL(visible, url, iframename, tabname) {
    if (visible) {
        if (url != null && url != "")
            Xrm.Page.getControl(iframename).setSrc(url);
    }
    else if (visible == false) {
        Xrm.Page.ui.tabs.get(tabname).setVisible(false);
    }
}

CRM 2011 Javascript - Form Tipleri

Xrm.Page.ui.getFormType();

Crm 2011 kullanıcılarının form üzerinde işlem yaparken , form üzrinde yapılan işlemin client tarafında "Create-Update-Delete vs." anında olup olmadığını öğrenip buna gore bir süreç yönetmemiz geekebiliyor .

Bunun için Crm 2011 formlarının client tarafındaki durumunu bulmak için aşağıdaki javaScript functionunu kullanabilirsiniz.


CRM 2011 Javascript - Form Disabled

function onLoad()
{
    disableFormFields(true);
}

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

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

CRM 2011 - Opportunity Note Tabı Gizleme-(ODataQuery)

Opportunity altına eklenen bir not (annotation) varsa notes tabını görünür yapan ,eğer opportunity e ait daha önceden girilen bir not yoksa bu tabı gizleyen script aşagıdadır.

Burada sorgumuzu odataquery ile olusturduk.
ODataRetrieveMultipleAjax : Sorgu larımızı calıstıracagımız metot.

/*Gökhan Mentese-gkhnmnts@gmail.com*/
function NoteTabVisibleInOpportunity() {
    try {
        var entityid = GetEntityId();
        var formType = Xrm.Page.ui.getFormType();
        if (formType == 1) {
            Xrm.Page.ui.tabs.get("notetabopportunity").setVisible(false);
        }
        else {
            if (entityid != null) {
                var query = "AnnotationSet?$filter=ObjectId/Id eq guid'" + ConverttoStringFromGuid(entityid) + "'";
                var noteEntity = ODataRetrieveMultipleAjax(query);
                if (noteEntity != null && noteEntity.results != null && noteEntity.results.length != null && noteEntity.results.length != 0) {
                    Xrm.Page.ui.tabs.get("notetabopportunity").setVisible(true);
                }
                else {
                    Xrm.Page.ui.tabs.get("notetabopportunity").setVisible(false);
                }
            }
        }
    } catch (e) {
        alert("Function NoteTabVisibleInOpportunity() \n" +e.message);
    }
}

function ODataRetrieveMultipleAjax(oDataSelect) {
    var crmOrgSvc = GetCrmSvc();
    var result = null;

    oDataSelect = crmOrgSvc + oDataSelect;
    jQuery.support.cors = true;

    $.ajax({
        type: "GET",
        contentType: "application/json; charset=utf-8",
        datatype: "json",
        url: oDataSelect,
        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 != null && data.d != null) {
                result = data.d;
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert("Status: " + textStatus + "; ErrorThrown: " + errorThrown, "Error Function:" + "ODataRetrieveMultipleAjax");
        }
    });
    return result;
}

function GetCrmSvc() {
    //return GetClientUrl() + "/xrmservices/2011/OrganizationData.svc/";
    return Xrm.Page.context.prependOrgName("/xrmservices/2011/OrganizationData.svc/");
}
function GetEntityId() {
    return Xrm.Page.data.entity.getId();
}

CRM 2011- Sub Gridde Seçili Eleman Bilgilerini Custom Sayfaya Yollama

Ben burada subgriddeki secili elemanları alıp custom sayfaya yollama işlemlerini ribbondaki bir butona tıklayınca gerceklestırecegım.Siz baska bir eventte de yapabilirsiniz.

Asagıdaki örnekte, subgridde secılı olan productların Id lerını custom sayfaya yollayıp burada bu secılenlere gore ıslem yapacagız.

Not:Custom sayfaya querystring yoluyla verileri aktaracagız.

CloseAsWonButtonOnClick : Butona tıklandıgında calısacak javascript fonksiyonu.
GetSelectedSubGridRow : Subgridden secili elemanları alan javascript fonksiyonu.
Default.aspx.cs  :Custom aspx sayfamızın kod tarafı

function CloseAsWonButtonOnClick() {
    var userId = Xrm.Page.context.getUserId();
    var entityid = Xrm.Page.data.entity.getId();
    var orgname = Xrm.Page.context.getOrgUniqueName();

    if (userId != null && entityid != null && orgname != null) {
        var url = null;

        var selectedRowsGuidId = GetSelectedSubGridRow('opportunityproductsGrid');
        if (selectedRowsGuidId != null) {
            if (selectedRowsGuidId.length == 0) {
                alert('You must select opportunity product.');
            }
            else{
                var selectedrow = "&selectedrow=" + selectedRowsGuidId.join("&selectedrow=");
                url = "http://deneme:1111/Modules/OpportunityEntity/WinOpportunity/Default.aspx?orgname=" + orgname.toUpperCase() + "&userid=" + userId.toString() + "&entityid=" + entityid.toString() + selectedrow;
            }
            else {
                alert("Only,you can copy one product");
            }

            if (url != null) {
                var features = 'height=500,width=500,left=300,top=150,resizable=yes,titlebar=no,resizable=no,scrollbars=no,toolbar=no,menubar=no,location=no,directories=no, status=no';
                window.open(url, 'OpportunityWonInterface', features);
            }
        }
    }
}

function GetSelectedSubGridRow(subGridName) {
    var array = new Array();
    var grid = document.getElementById(subGridName).control;
    for (var rowNo = 0; rowNo < grid.get_selectedRecords().length; rowNo++) {
        array[rowNo] = grid.get_selectedRecords()[rowNo].Id;
        /*        alert(grid.get_selectedRecords()[rowNo].Id);
        alert(grid.get_selectedRecords()[rowNo].Name);*/
    }

    if (array.length != 0) {
        return array;
    }
    else {
        return new Array();
    }
}


Default.aspx.cs
/**/
protected void Page_Load(object sender, EventArgs e) {
            if (!IsPostBack) {

                string selectedProductsID = Request.QueryString["selectedrow"];
                if (!string.IsNullOrEmpty(selectedProductsID)) {
                            ArrayList array = new ArrayList();
                            for (int indexLog = 0; indexLog < selectedProductsID.Split(',').Length; indexLog++) {
                                string id = selectedProductsID.Split(',')[indexLog];
                                array.Add(new Guid(id));
                            }
                            ViewState["selectrowid"] = array;
                        }
           }
}