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
christin mathewchristin mathew 

Whenever a new contact is created for a account update the corresponding account phone with the new contact??

Whenever a new contact is created for a account update the corresponding account phone with the new contact??

trigger updatephonenocontact on Account (After insert) {

    List <Contact> Con = new List <Contact>();

    For (Account A: Trigger.new){

    Contact C = new Contact();
 
    C.phone= A.phone;

    C.AccountId = A.Id;
    
    Con.add(C);

    }

    

    Insert Con;

}
 im getting this error message 
Error: Invalid Data. 
Review all error messages below to correct your data.
Apex trigger updatephonenocontact caused an unexpected exception, contact your administrator: updatephonenocontact: execution of AfterInsert caused by: System.DmlException: Insert failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING, Required fields are missing: [Last Name]: [Last Name]: Trigger.updatephonenocontact: line 19, column 1
JeffreyStevensJeffreyStevens
Pretty sure your trigger should be on the contact object.

Just do an after update on the Contact and get the account and update it.  

In fact - you might be able to take care of it with a field-update workflow rule.  Might have to think about that for a minute.

 
JeffreyStevensJeffreyStevens
trigger updateAccountPhone on Contact (after update) {
    // Get accounts & build map
    map<id,id> mAccountContact = new map<id,id>();
    for(Contact c :trigger.new) {
        mAccountContact.put(c.Account,c.id);
    }
    
    // Update the accounts
    list<Account> accountsToUpdate = [SELECT id, ​PhoneNumber 
                                      FROM Account 
                                      WHERE id IN :mAccountContact.keyset()];
    for(Account a :accountsToUpdate) {
        a.PhoneNumber = trigger.newmap.get(a.id).PhoneNumber;
    }
    if(accountsToUpdate.size()>0) {
        update accountsToUpdate;
    }
}

I think that's the bulkified code you'll need.  Not 100% sure on the syntax, and on the field name for PhoneNumber
 
christin mathewchristin mathew
thanks a lot jeffrey 
JeffStevensJeffStevens
You bet! Be sure to remember mark the question as solved.