1

その連絡先の予定の最新の実際の終了日を計算して連絡先フォームに表示できるようにしたいと考えています。

次のクエリは、アカウント エンティティに対して同じ機能を実現する方法を示しています。

JavaScript と REST OData を使用して CRM 2011 AppointmentSet を照会するときに、d.data.results に存在するデータをテストする方法

今、私は連絡先で同じことをしようとしましたが、に関してオブジェクト ID はどの連絡先とも一致しません。だから私はこれについてどうやって行くのか尋ねています。

主催者、任意出席者、および必須出席者の各パーティーリストを開いて展開する必要がありますか? もしそうなら、どうすればこのクエリを作成できますか? $expand 機能を使用していますか?

困った心を助けてください!

バンプ!

4

1 に答える 1

1

わかりましたので、私はこの問題に数日間取り組んできました。

このタスクは、次のツールXRM Dynamics Toolsを使用して OData クエリ コードを生成することで完了できることがわかりました。

基本的に私が抱えていた問題は、連絡先が予定にどのようにリンクされているかを理解することでした。予定のすべての参加者が予定の「appointment_activity_parties」フィールドに含まれることを理解すると、この問題を処理するための適切なクエリを作成する方法を確認できました。

activityid フィールド、actualEnd フィールドを選択し、appoint_activity_parties の拡張機能を使用して、この拡張フィールドから PartyId を選択することで、パーティー タイプが連絡先であること、パーティーの contactId が現在表示している連絡先と一致することを確認できました。このようにして、一致の総数を数え、その連絡先の最後に完了した予定の日付を記録することができました。

最後に、問題を 2 つのクエリに分割しました。各年に 1 つ: 現在および前の年。お問い合わせフォームに 3 つの新しいフィールドを追加しました。VisitsLastYear と VisitsThisYear の整数を保持する 2 つと、次のスクリーンショットに示すように、Appointment へのリンクを保持するルックアップを保持します。

ここに画像の説明を入力

私のコードは次のとおりです。

/// <reference path="XrmPageTemplate.js" />
/// <reference path="JQuery.js" />
/// <reference path="SDK.REST.js" />
/// <reference path="json2.js" />
function HarrionAB_ContactForm_OnLoad() {

    // get the contact id from the page
    var contactId = Xrm.Page.data.entity.getId().replace("{", "").replace("}", "")
    // if we got a value
    if (contactId != "") {
        var currentYear = new Date().getFullYear();
        var query = "/AppointmentSet?";                                                                         // Appointments table
            query += "$select=ActualEnd,ActivityId,appointment_activity_parties/PartyId";                       // Select
            query += "&$expand=appointment_activity_parties";                                                   // Expand sub tables
            query += "&$filter=ActivityTypeCode eq 'appointment' and StateCode/Value eq 1 and ";                // Where

        CountVisitsThisYear(query, currentYear);
        CountVisitsLastYear(query, currentYear - 1);
    }
}

function CountVisitsThisYear(query, currentYear) {

    var start = currentYear.toString() + "-01-01T00:00:00";
    var end = currentYear.toString() + "-12-31T00:00:00";

    query += "ActualStart ge datetime'" + start + "' or ActualStart le datetime'" + start + "' and ";   // Where  
    query += "ActualEnd ge datetime'" + end + "' or ActualEnd le datetime'" + end + "'";                // Where

    // call function to execute the odata query
    ExecuteVisitsThisYearQuery(query);
}

function CountVisitsLastYear(query, lastYear) {

    var start = lastYear.toString() + "-01-01T00:00:00";
    var end = lastYear.toString() + "-12-31T00:00:00";
    query += "ActualStart ge datetime'" + start + "' or ActualStart le datetime'" + start + "' and ";   // Where  
    query += "ActualEnd ge datetime'" + end + "' or ActualEnd le datetime'" + end + "'";                // Where

    // call function to execute the odata query
    ExecuteVisitsLastYearQuery(query);
}

//
// ExecuteQuery executes the specified OData Query asyncronously
//
// NOTE: Requires JSON and jQuery libraries. Review this Microsoft MSDN article before 
//       using this script http://msdn.microsoft.com/en-us/library/gg328025.aspx
//
function ExecuteVisitsThisYearQuery(ODataQuery) {

    // get the server url
    var serverUrl = Xrm.Page.context.getServerUrl();

    // Adjust URL for differences between on premise and online 
    if (serverUrl.match(/\/$/)) {
        serverUrl = serverUrl.substring(0, serverUrl.length - 1);
    }

    var ODataURL = serverUrl + "/XRMServices/2011/OrganizationData.svc" + ODataQuery;

    $.ajax({
        type: "GET",
        contentType: "application/json; charset=utf-8",
        datatype: "json",
        url: ODataURL,
        beforeSend: function (XMLHttpRequest) {
            XMLHttpRequest.setRequestHeader("Accept", "application/json");
        },
        success: function (data, textStatus, XmlHttpRequest) {
            //
            // Handle result from successful execution
            //
            // e.g. data.d.results
            var contactId = Xrm.Page.data.entity.getId().replace("{", "").replace("}", "");
            var lastVisitDate;
            var activityId;

            var count = 0;
            // if we have results
            if (data.d.results.length > 0) {
                // loop through the appointment results
                for (i = 0; i < data.d.results.length; i++) {
                    // if we have results
                    if (data.d.results[i].appointment_activity_parties.results.length > 0) {
                        // loop through the appointment_activity_parties
                        for (j = 0; j < data.d.results[i].appointment_activity_parties.results.length; j++) {
                            // if the party id type is contact and the contact ids match
                            if (data.d.results[i].appointment_activity_parties.results[j].PartyId.LogicalName == "contact" && contactId.toLowerCase() == data.d.results[i].appointment_activity_parties.results[j].PartyId.Id.toLowerCase()) {
                                // if we have not got a date yet
                                if (lastVisitDate == null) {
                                    // set the date as this is the first date we found
                                    lastVisitDate = data.d.results[i].ActualEnd;
                                    activityId = data.d.results[i].ActivityId;
                                } else {
                                    // if the current date is < new date
                                    if (lastVisitDate < data.d.results[i].ActualEnd) {
                                        // reset the date as we have found a later one
                                        lastVisitDate = data.d.results[i].ActualEnd;
                                        activityId = data.d.results[i].ActivityId;
                                    }
                                }
                                ++count;
                            }
                        }
                    }
                }
            }

            Xrm.Page.getAttribute("new_visitsthisyear").setValue(count);
            // if we found a completed appointment
            if (count > 0) {
                SetLookup("new_lastvisitcompleted", activityId, ParseJsonDate(lastVisitDate).toString('dd/MM/yyyy'), "Appointment");
            }
        },
        error: function (XmlHttpRequest, textStatus, errorObject) {
            //
            // Handle result from unsuccessful execution
            //
            alert("OData Execution Error Occurred");
        }
    });
}

//
// ExecuteQuery executes the specified OData Query asyncronously
//
// NOTE: Requires JSON and jQuery libraries. Review this Microsoft MSDN article before 
//       using this script http://msdn.microsoft.com/en-us/library/gg328025.aspx
//
function ExecuteVisitsLastYearQuery(ODataQuery) {

    // get the server url
    var serverUrl = Xrm.Page.context.getServerUrl();

    // Adjust URL for differences between on premise and online 
    if (serverUrl.match(/\/$/)) {
        serverUrl = serverUrl.substring(0, serverUrl.length - 1);
    }

    var ODataURL = serverUrl + "/XRMServices/2011/OrganizationData.svc" + ODataQuery;

    $.ajax({
        type: "GET",
        contentType: "application/json; charset=utf-8",
        datatype: "json",
        url: ODataURL,
        beforeSend: function (XMLHttpRequest) {
            XMLHttpRequest.setRequestHeader("Accept", "application/json");
        },
        success: function (data, textStatus, XmlHttpRequest) {
            //
            // Handle result from successful execution
            //
            // e.g. data.d.results
            var contactId = Xrm.Page.data.entity.getId().replace("{", "").replace("}", "");

            var count = 0;
            // if we have results
            if (data.d.results.length > 0) {
                // loop through the appointment results
                for (i = 0; i < data.d.results.length; i++) {
                    // if we have results
                    if (data.d.results[i].appointment_activity_parties.results.length > 0) {
                        // loop through the appointment_activity_parties
                        for (j = 0; j < data.d.results[i].appointment_activity_parties.results.length; j++) {
                            // if the party id type is contact and the contact ids match
                            if (data.d.results[i].appointment_activity_parties.results[j].PartyId.LogicalName == "contact" && contactId.toLowerCase() == data.d.results[i].appointment_activity_parties.results[j].PartyId.Id.toLowerCase()) {
                                ++count;
                            }
                        }
                    }
                }
            }

            Xrm.Page.getAttribute("new_visitslastyear").setValue(count);
        },
        error: function (XmlHttpRequest, textStatus, errorObject) {
            //
            // Handle result from unsuccessful execution
            //
            alert("OData Execution Error Occurred");
        }
    });
}


// function to parse JSON date into JavaScript Date
function ParseJsonDate(jsonDate) {
    var offset = new Date().getTimezoneOffset() * 60000;
    var parts = /\/Date\((-?\d+)([+-]\d{2})?(\d{2})?.*/.exec(jsonDate);

    if (parts[2] == undefined)
        parts[2] = 0;

    if (parts[3] == undefined)
        parts[3] = 0;

    return new Date(+parts[1] + offset + parts[2] * 3600000 + parts[3] * 60000);
};

//function to create a lookup control
function SetLookup(fieldName, idValue, textValue, typeValue) {
    var value = new Array();
    value[0] = new Object();
    value[0].id = idValue;
    value[0].name = textValue;
    value[0].typename = typeValue;

    Xrm.Page.getAttribute(fieldName).setValue(value);
}


//
// Error Handler
//
function ErrorHandler(XMLHttpRequest, textStatus, errorObject)
{ alert("Error Occurred : " + textStatus + ": " + JSON.parse(XMLHttpRequest.responseText).error.message.value); }

これが同様の問題を抱えている人に役立つことを願っています。

于 2013-11-20T16:48:21.713 に答える