[SalesForce] Custom Button to Update Child Records

Can someone point me to a code sample that does the following:

I want to update a custom field on all the account related contact records called relationship__c from a button on the parent account record.

I do not care if the button is a detail or list button. All it needs to do is get the account ID, search for all the child contact records and update that field to say relationship__C = "New". That's it but for someone who is not familiar with javascript, I'm hitting a wall. (I can update the account record but can't seem to get the contacts.) If anyone can help with a code example, I'd appreciate it.

Best Answer

You can invoke an apex class using the AJAX Toolkit. Here is one small example.

Create a custom button on Account and select JavaScript Execute onclick:

{!REQUIRESCRIPT("/soap/ajax/24.0/connection.js")} 
{!REQUIRESCRIPT("/soap/ajax/24.0/apex.js")} 
var id= '{!Account.Id}'; 
alert(id); 
sforce.apex.execute('buttoncls','updateRecord',{recId :id}); 

window.location.href = window.location.href;

Create an Apex webservive class and write your logic. Here is the code:

global class buttoncls {
    webservice static void updateRecord(Id recId){

        System.debug('------Method called on button click.....');
        list<contact> con  = new list<contact>();

        if(recId!=null)
        {
            for (Contact c :[select id ,phone from Contact where accountid=:recId])
            {
                c.phone='123';
                con.add(c);
            }

             update con;
        }
    } 
}

Add your button from page layouts...

Cheers Vineeth

Related Topic