Sunday, April 18, 2010

MSCRM 4.0: Get CRM Report's ID by its Name

There has been a question on CRM Development Forum about how to get a CRM report's ID by its name. Here is the script that I came up using CRM Web Service Toolkit.
/**
* Get a CRM report's ID by its name.
* @author Daniel Cai, http://danielcai.blogspot.com/
*
* Parameters:
* @param reportName: The CRM Report's name. 
*/
getReportId = function(reportName)
{
    var fetchXml = [
        "<fetch mapping='logical'>",
           "<entity name='report'>",
           "<attribute name='reportid' />",
           "<filter>",
              "<condition attribute='name' operator='eq' value='", reportName, "' />",
           "</filter>",
           "</entity>",
        "</fetch>"
    ].join("");

    var result = CrmServiceToolkit.Fetch(fetchXml);
    if (result === null) {
        throw new Error("Report " + reportName + " cannot be found. "); // This should never happen if the report exists, but you should handle the exception just in case.
    }

    return result[0].getValue("reportid");
};
To use the function, you simply call it with the report's name as the only parameter, e.g.
var reportId = getReportId("Quote"); // Get "Quote" report's GUID
You will have to make CRM Web Service Toolkit available on the form. You can either copy the toolkit's JS code to your form's OnLoad event, or use my another piece of script to load the toolkit from external file.

You may wonder why you ever need this function. The reason is, when you have a custom report built for a CRM entity, and you want to add a custom button on the entity form to launch the report instantly, in which case you will need to call CRM's RunReport() function, which takes report's GUID as the last parameter (sHelpId). When a custom report is downloaded/uploaded from one environment to another one, the report's ID would be different. If you won't want to hard-code your report's ID when you make call to CRM RunReport() function, it is when this function comes to rescue you.

Cheers.

No comments:

Post a Comment