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
palukuru sfdcpalukuru sfdc 

how to set the value to parent lookup field on child field from anonymous window?

Hi Can someone explain how to set the lookup (from account name value) to conatct name when creating contact from anonymous window.

List<contact> contactToSave = new List<contact> ();
Contact cont = new Contact();
Account acctRef = new Account(name='University of Arizona'); // need to set this name to contact which I'm creating below. Account name already available on org 
cont.FirstName='Test1';
cont.LastName='Test2';
cont.Department='Finance';
cont.name=actRef;
contactToSave.add(cont);
insert contactToSave;

please explain how this works...
Best Answer chosen by palukuru sfdc
Sudipta DebSudipta Deb
Hi Palukuru,

I think you are trying to create contacts for some existing accounts. You can do that by -
 
//Fetch the existing Account
List<Account> accounts = [SELECT ID FROM Account Where <PUT YOUR UNIQUE IDENTIFIER TO FETCH THE EXISTING ACCOUNT>];
List<Contact> allContacts = new List<Contact>();
if(accounts.size()>0){
    Contact singleContact = new Contact();
    singleContact.FirstName = 'John';
    singleContact.LastName = 'Miller';
    singleContact.AccountID = accounts.get(0).Id;
    allContacts.add(singleContact);
}
if(allContacts.size() > 0){
    insert allContacts;
}

Please accept my solution as Best Answer if my reply is helpful.

All Answers

SouvikSomeSouvikSome

Hi Palukuru,

Contact.Name field is consist of 3 different fields Salutation+FirstName+LastName.
 

Contact con = new Contact();
con.FirstName = 'Palukuru';
con.LastName = 'SFDC';
insert con;
List<Contact> conList = [Select Name from contact where LastName = 'SFDC'];
System.debug(conList);

You will get (Contact:{Name=Palukuru SFDC, Id=0032800000n3cG9AAI})

https://success.salesforce.com/ideaView?id=08730000000BqVVAA0

Sudipta DebSudipta Deb
Hi Palukuru,

I think you are trying to create contacts for some existing accounts. You can do that by -
 
//Fetch the existing Account
List<Account> accounts = [SELECT ID FROM Account Where <PUT YOUR UNIQUE IDENTIFIER TO FETCH THE EXISTING ACCOUNT>];
List<Contact> allContacts = new List<Contact>();
if(accounts.size()>0){
    Contact singleContact = new Contact();
    singleContact.FirstName = 'John';
    singleContact.LastName = 'Miller';
    singleContact.AccountID = accounts.get(0).Id;
    allContacts.add(singleContact);
}
if(allContacts.size() > 0){
    insert allContacts;
}

Please accept my solution as Best Answer if my reply is helpful.
This was selected as the best answer
palukuru sfdcpalukuru sfdc
Thank you Sudipta. thats answer my question.