[SalesForce] OnClick Javascript Ajax Toolkit: Syntax to evaluate Sobject field within if expression

I have a Javascript button on Case that merely changes the owner when clicked, so far so good. But I'd like to extend it with a tiny bit of validation that chck to see whether there's a picklist value that is empty (that is, not set) on the Case. If so, it throws an alert, else updates the case with the new ownerId. Here's what I've got:

{!REQUIRESCRIPT("/soap/ajax/30.0/connection.js")} 


var updateRecord = new Array(); 
var myquery = "SELECT Id,txFaultRequestInfo__c,pl_ReasonForAssignment__c FROM Case WHERE Id = '{!Case.Id}' limit 1"; 

result = sforce.connection.query(myquery); 
records = result.getArray("records"); 

if(records[0]) 
{ 
var update_Case = records[0]; 

if("{update_Case.pl_ReasonForAssignment__c}" == '') 
{ 
alert("Picklist value is not set!"); 

} 
else 
{ 
update_Case.OwnerId = "00G20000000jeqC" ;  /* New Value */
//update_Case.OwnerId = "00G20000000jdLD"; /* Older Value */

updateRecord.push(update_Case); 
} 
} 

result = sforce.connection.update(updateRecord); 
parent.location.href = parent.location.href;

No matter what, it always evaluates the if condition as false and goes to the else condition that updates the OwnerId. Can you spot the error?

Best Answer

update_Case is a variable at the point where you're referencing it in the if condition so you don't need the quotes nor the merge syntax.

A couple of other points, you should always declare JavaScript variables with the var keyword and I would suggest using the triple-equals operator in the if expression to avoid type coercion:
if (update_Case.pl_ReasonForAssignment__c === '') {

{!REQUIRESCRIPT("/soap/ajax/30.0/connection.js")}

var updateRecord = new Array();
var myquery = "SELECT Id, txFaultRequestInfo__c, pl_ReasonForAssignment__c FROM Case WHERE Id = '{!Case.Id}' limit 1";

var result = sforce.connection.query(myquery);
var records = result.getArray("records");

if (records[0]) {
    var update_Case = records[0];

    // a little debugging
    alert(update_Case.pl_ReasonForAssignment__c);

    if (update_Case.pl_ReasonForAssignment__c == '') {
        alert("Picklist value is not set!");

    } else {
        update_Case.OwnerId = "00G20000000jeqC"; /* New Value */
        //update_Case.OwnerId = "00G20000000jdLD"; /* Older Value */

        updateRecord.push(update_Case);
    }
}

result = sforce.connection.update(updateRecord);
parent.location.href = parent.location.href;
Related Topic