[SalesForce] Get value of custom field using Javascript

I am trying to make a button that shows up on the Lead List results page. In order to sync with another system properly I need to have this button basically copy the name of an Account that has a lookup relationship with the associated Lead then copy the name of that Account to another field within the Lead. My problem is that I can do a query for the ID of that Account, the query says the ID, but won't let me do anything with it.

This is what I get when I check a value:

00Q6100000FQiRw
{done:'true', queryLocator:null, records:{type:'Lead', Id:null, Partner_Owner_Account__c:'0016100000RuwBRAAZ', }, size:'1', }
{id:'00Q6100000FQiRwEAL', success:'true', }

This is what I have on the button, it's not done of course, but I am trying to figure out why my query reports the lookup ID, like I want, but if I try to put it into an array all it does is grab the Lead ID instead:

{!REQUIRESCRIPT("/soap/ajax/36.0/connection.js")}
var records = {!GETRECORDIDS($ObjectType.Lead)};
var updateRecords = [];
var result = [];

if (records[0] == null) { 
    alert("Please select at least one record to update.");
} else {
    for (var a=0; a<records.length; a++) {
        var my_Query = "SELECT Partner_Owner_Account__c FROM Lead WHERE Id = '" + records[a] + "'";
        var query_Result = sforce.connection.query(my_Query);
        result[a] = query_Result.getArray("query_Result");
    }
    result = sforce.connection.update(updateRecords);
    alert(records[0] + "\n" + query_Result + "\n" + result[0]);
}

I don't understand this result. If the query_Result reports the ID that I want (0016100000RuwBRAAZ) why then, when I put it into an array, it gives me the ID of the Lead itself instead (00Q6100000FQiRwEAL)? Thanks!

Best Answer

Your code makes no sense, and it's wasting a lot of API calls in the process. What you're apparently looking for, so far, would look like this:

{!RequireScript("/soap/ajax/37.0/connection.js")}
var recordIds = {!GetRecordIds($ObjectType.Lead)};
var updates = [];
if(!recordIds.length) {
    alert("Select at least one lead.");
} else {
    var qr = sforce.connection.query(
         "select partner_owner_account__c from lead"+
         " where id in ('"+recordIds.join("','")+"')");
    var leads = qr.getArray("records");
    leads.forEach(function(v) {
        var acc = new sforce.SObject("Account");
        acc.id = v.Partner_Owner_Account__c;
        updates.push(acc);
    });
    sforce.connection.update(updates);
}

Also, see the documentation on Processing Results to see how this should work. Finally, when working with pure Id variables, consider using "retrieve" instead of "query", as it has better performance.

Related Topic