Open a new lead form in Crm 2013 by clicking a button and automatically passing the details of the

I have integrated an Add New Lead button into the main form on the Homepage for contacts.

Clicking this button triggers a script that opens a new form and passes "Crm Parameter FirstSelectedItemId" as a parameter.

By selecting a contact and clicking create new lead, I can pass the ID as a parameter to the function:

function openNewLead(SelectedID) {
      parameters["customer"] = SelectedID;
      Xrm.Utility.openEntityForm("lead", null, parameters);
}

The field "customer" is a lookup field. However, I encountered an issue where it populates the lookup but does not pass the full name correctly. It works fine after saving and refreshing!

To address this, I attempted:

function openNewLead(SelectedID) {
    if (SelectedID != null) {

        var parameters = {};

        var request = Xrm.Page.context.getServerUrl() + "/XRMServices/2011/OrganizationData.svc/ContactSet?$select=FullName&$filter=ContactId eq guid'" + SelectedID + "'";
        $.ajax({
            type: "GET",
            contentType: "application/json; charset=utf-8",
            datatype: "json",
            url: request,
            async: false,
            beforeSend: function (XMLHttpRequest) {
                XMLHttpRequest.setRequestHeader("Accept", "application/json");
            },
            success: function (data, textStatus, XmlHttpRequest) {
                if (data.d.results.length > 0) {

                        var lookupValue = new Array();
                        lookupValue[0] = new Object();
                        lookupValue[0].id = SelectedID;
                        lookupValue[0].name = data.d.results[0].FullName;
                        lookupValue[0].entityType = "contact";
                        parameters["customer"] = lookupValue;

                }
            },
            error: function (XmlHttpRequest, textStatus, errorThrown) {
                /*Error Occurred*/
            }
        });

        Xrm.Utility.openEntityForm("lead", null, parameters);
    }
    else {
        Xrm.Utility.openEntityForm("lead");
    }
}

This solution does not work from the homepage/main screen since no reference can be added for JSON.

Therefore, my question is how do I reference JSON from here or is there a more efficient way to approach this?

Thank you

Answer №1

Give this modification a shot

achievement: function (info, statusText, XmlRequest) {
                if (info.d.output.length > 0) {
                     attributes["visitorid"] = ChosenID;
                     attributes["visitorname"] = info.d.output[0].FullName;
                     attributes["visitortype"] = "guest";    
                }
            }

Answer №2

Here is the solution:

A new button has been added to the main homepage that triggers a script opening a new form and passing the CrmParameter FirstSelectedItemId.

function openNewLead(SelectedID) {
    if (SelectedID != null) {
        var parameters = {};

        var contact = {};
        contact.Id = SelectedID;

        var jsonContact = JSON.stringify(contact);

        var PassContactReq = new XMLHttpRequest();
        PassContactReq.open("GET", Xrm.Page.context.getServerUrl() + "/XRMServices/2011/OrganizationData.svc/ContactSet?$select=ContactId, FullName&$filter=ContactId eq guid'" + SelectedID + "'");
        PassContactReq.setRequestHeader("Accept", "application/json");
        PassContactReq.setRequestHeader("Content-Type", "application/json; charset=utf-8");
        PassContactReq.onreadystatechange = function () {
            PassContact(this);
        };
        PassContactReq.send(jsonContact);

        function PassContact(PassContactReq) {
            if (PassContactReq.readyState == 4 /* complete */) {
                PassContactReq.onreadystatechange = null; //avoids memory leaks
                if (PassContactReq.status == 200) {
                    //Success

                    parameters["customer"] = JSON.parse(PassContactReq.responseText).d.results[0].ContactId;
                    parameters["customername"] = JSON.parse(PassContactReq.responseText).d.results[0].FullName;

                    Xrm.Utility.openEntityForm("lead", null, parameters);
                }
                else {
                    //Failure
                    Xrm.Utility.openEntityForm("lead");
                }
            }
        };

    } else {
        Xrm.Utility.openEntityForm("lead");
    }
}

Big thanks to @Nicknow for the helpful comment!

Since this was a custom lookup field, remember to ignore the "id" part of the string and no type needs to be set for the parameters.

It took some time to figure out this solution, so hopefully it will be beneficial for others as well :)

Answer №3

Experiment with incorporating JavaScript actions using referenced web resources and unique function names like "isNaN". Here is an example of how the Ribbon Xml may appear:

<Actions>
        <JavaScriptFunction FunctionName="isNaN" Library="new_json2"></JavaScriptFunction>
        <JavaScriptFunction FunctionName="isNaN" Library="new_jquery"></JavaScriptFunction>
        <JavaScriptFunction FunctionName="customFunctionWithExternalLibs" Library="new_referencinglibrary"></JavaScriptFunction>
      </Actions>

Please excuse any language mistakes in my writing :)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

choose a unique jQuery id without any duplicates

Trying to implement a simple system comment feature similar to Facebook, but struggling with selecting the right ID for submission. The issue I'm facing is that the first form works correctly, but for subsequent forms, I always retrieve the data-id fr ...

non-concurrent in Node.js and JavaScript

I'm a beginner in the world of NodeJS and I have a question that's been bugging me. Node is known for its asynchronous nature, but JavaScript itself also has asynchronous features (like setTimeout). So why weren't concepts like Promise intr ...

InvalidSyntaxError: Client login cannot be completed due to an unexpected end of input. Please

I encountered an issue while trying to create a bot that sends welcome messages for my friend's server. Despite numerous attempts to troubleshoot the problem within my code, I have been unable to resolve it. Any assistance in solving this error would ...

mongoose.js now prevents update methods from returning documents

Is it feasible to avoid fetching any data from the database after performing the SOME_MODEL.findOneAndUpdate() operation? I could potentially utilize the lean() and select() methods. However, all I really require is a callback confirming the successful up ...

Issue (@websanova/vue-auth): http plugin has not been properly configured in drivers/http/axios.js

I've been working on integrating vue-auth into my laravel-vue application, but I'm encountering some console errors: Error (@websanova/vue-auth): drivers/http/axios.js: http plugin has not been set. Uncaught TypeError: this.plugins.http is u ...

The Jetty server is unable to provide JSON responses

Whenever I use the command mvn jetty:run to initiate my server, it fails to return JSON formatted strings. Instead, it only returns raw strings or "null" for all objects. In the code snippet for my endpoint, you can observe that there is no variation in r ...

Creating Event Handlers for corresponding elements in HTML with the help of JQuery and JavaScript

Struggling with HTML and debugging an issue in my ASP.NET Core App. The problem lies in a CSHTML view that functions as a timeclock system for tracking user input against job numbers. The current Index.cshtml is operational, verifying JobNumbers against t ...

Personalized JSON serialization within the Spring Framework and Apache CXF

Working on my Spring Framework project, I am developing web services (Apache CXF) where I handle the (de)serialization of inputs and outputs using JacksonJsonProvider. I have a requirement to serialize DTO objects differently for each instance. While I am ...

Generating interactive charts using JSON data parsed from MySQL database for Highcharts visualization

Just starting out and feeling (almost) desperate. My goal is to: Read temperature data from a sensor (working, returns float) Save the data in a MySQL database table called boxklima.sensorid (working - table name: boxklima.0414604605ff) as sets of date-t ...

What is the best way to retrieve the root binding node from a viewmodel in order to apply jQuery.blockUI when performing an AJAX post request?

Within my code, I have a designated DIV element that serves as the root node for applying knockout bindings like so: ko.applyBindings(viewModel, document.getElementById('myContainerDiv')); In all of my viewmodel types, there is a generic post m ...

Retrieve information from Angular 2 response

In my code, I am working with 1 component and 1 service. Here is the component element : ... constructor(private requestService : RequestService) { } ngOnInit() { this.a = this.requestService.send_request(urlWebAPI); console.log(this.a); } ... ...

Transform this color matching game into an image matching game using JavaScript and jQuery

I have a color matching game that I would like to enhance by matching background-images instead of just background-colors. However, I am facing difficulties in making this change. For instance, instead of matching the color red with the text "red," I wan ...

The React Material Component stubbornly resists being horizontally aligned in the Code Sandbox

Currently, I am working on getting my Material design to function properly within the CodeSandbox environment. One issue I am encountering is attempting to center it horizontally. As of now, it appears like this: https://i.sstatic.net/ZK02y.png To make ...

The options object provided for Ignore Plugin initialization in Webpack 5.21.2 does not conform to the API schema, resulting in an error

Here is the setup of my webpack.config.js on a backend server running webpack version 5.21.1: /* eslint-disable */ const path = require('path'); const webpack = require('webpack'); module.exports = { target: 'node', modul ...

Working with JSON responses in Laravel 4 and Mandrill

Recently, I have been utilizing Laravel (4.2) and its inbuilt Mandrill driver to send emails. However, I am facing a challenge in capturing the response from Mandrill. Below is the code snippet I am using to dispatch the message: Mail::queue('emails ...

Dynamically load modules within an AngularJS application

Is there a way to dynamically load module scripts? I have 2 JS files: module1.js (function() { var mod = angular.module('module1', []); .... })(); This is the second one: module2.js (function() { var mod = angular.module('m ...

Refreshing JSON data every 10 seconds using SVG/D3

What is the best way to program a D3/json/ajax query that retrieves new data every 10 seconds? Here is my initial attempt at a solution, but I believe it may not be ideal: setInterval(function() { d3.json("http://1.....", function(json) { .... }) ...

Incorporate PrimeVue into Vue's custom elements

Can you guide me on integrating a PrimeVue component into a Vue3 custom element? I have created a Vue3 composition+setup custom element. I expect the button to be styled with PrimeVue and appear red due to the severity="danger" attribute. Howev ...

Error Encountered - Node.js application experiencing issues in passport login functionality

I'm in the process of developing a login application using nodejs and incorporating passport js for authentication. The app is connected to a local MySql database and utilizes sequelize as its ORM library. Within my user model, I've implemented ...

The event listener for browser.menus.onClicked is dysfunctional in Firefox

Currently, I am in the process of developing my own Firefox extension and I have encountered an issue with adding a listener to an onclick event for a context menu item. manifest.json { "manifest_version": 2, "name": "My exten ...