function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Pankaj PariharPankaj Parihar 

account city field update trigger

Hi friends
i want a trigger code for this
When a contact is made primary(1) the city of the contact should be updated in the Account’s city(3) field. User-added image
Best Answer chosen by Pankaj Parihar
Saurabh Sood 12Saurabh Sood 12
Trigger on contact(after insert ){
for( Contact con : trigger.new){

if(con.city != null){
Account acc = [SELECT account_city from account where id =: con.AccountId];
acc.Account_city = con.city;
insert acc;
}
}

All Answers

Saurabh Sood 12Saurabh Sood 12
Trigger on contact(after insert ){
for( Contact con : trigger.new){

if(con.city != null){
Account acc = [SELECT account_city from account where id =: con.AccountId];
acc.Account_city = con.city;
insert acc;
}
}
This was selected as the best answer
Pankaj PariharPankaj Parihar
hello sir 
actully this trigger is in account ....contact is related list of account...
and it should copy the city name whose primary value is true..
pls look into this ... the code u provide is also good..but not matching my requirements
Paul S.Paul S.
Pankaj - triggering on account is fine, you can then go get the MailingCity of the related contact marked primary.  But how would you handle the scenario where you make a different contact primary?  There's not necessarily anything that will then trigger the update of your BillingCity field if the trigger is on account (because the account hasn't been updated, the contact has).
Saurabh Sood 12Saurabh Sood 12

 string conCity= SELECT Contact.city FROM contacts WHERE IsPrimary = TRUE and Id = : con.Id].city; 
add this line before if condition
 
shweta chadha 4shweta chadha 4
This should be working
trigger CityonContact on Contact (After insert) {
    
       List<Contact> con = new List<Contact>();
       List<Account> acct = new List<Account>();
    
    for (Contact c : Trigger.new)
    {
        // Contact cont = new Contact(id = c.Id,Lastname = c.LastName,MailingCity = c.MailingCity, Primary_Contact__C = c.Primary_Contact__c);
        con.add(c);
    }
        
      
    for (contact c : con)
    {
        if ((c.Primary_Contact__c==true) && (c.MailingCity!=null))
        {
            Account acc = [Select Id, BillingCity from Account where Id =:c.AccountId];
            acc.BillingCity = c.MailingCity;
            acct.add(acc);
        }
     }
    update acct;

}