0

I am trying to add a new contact record with below condition where Account has greter than 99 employees an limit is 1. THough new contact is not getting created in accounts where employess are more than 99. let me know what is wrong in below code. (New to apex)

Contact c = new Contact(Account = [SELECT Name FROM Account 
    WHERE NumberOfEmployees > 99 Limit 1]);
c.FirstName = 'Test';
c.LastName = 'AM';
System.debug('Contact name  is '+c);
0

You need to separate the identification of the Accounts - the query part - from the data modification of the Contacts. There is no concept of "conditional insert" in SOQL (or SQL for that matter). Also, if you only want to insert one Contact, you need to be more specific about which Account it is e.g. by using order by as well as limit.

To insert a Contact for all Accounts that match this condition (and assuming the record numbers are well inside the governor limits):

Contact[] contacts = new Contact[] {};
for (Account account : [
        select Id
        from Account
        where NumberOfEmployees > 99
        ] {
    contacts.add(new Contact(
        AccountId = account.Id,
        FirstNme = 'Test',
        LastName = 'AM'
    ));
}
insert contacts;
| improve this answer | |
0

To insert contact, perform a dml operation insert in this case and to associate with the account account field on contact is need to be populated. Check out below mentioned code.

Contact c = new Contact(Account = [SELECT Name FROM Account WHERE NumberOfEmployees > 99 Limit 1]);
c.FirstName = 'Test';
c.LastName = 'AM';
c.accountid= c.account.Id;
insert c;
System.debug('Contact name  is '+c.id);
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.