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
Scott0987Scott0987 

apex salesforce object lookup

I am very new to apex.  I would like to be able to assign a variable the id from a salesforce object.  For instance I have a apex code that creates a contact.  I would like to tie that contact to the account.  So I want to do a lookup for the account salesforce object that meets a few criteria, like account name = contact name. 

Best Answer chosen by Admin (Salesforce Developers) 
nickwick76nickwick76

Hi,

This is the way I perceived want you want to accomplish. On the first lines an account and a contact is created separately. Then query an account where the account name is equal to a contact name. In this case update the contact with a reference to this account.

 

public class Test2 {
    public void testInsertContact() {
        Account a = new Account(Name='John Smith');
        insert a;
        
        Contact c = new Contact(Firstname='John',LastName='Smith');             
        insert c;
        
        Contact c2 = [select Name from Contact where Name = 'John Smith'];
        
        Account acc = [select Id,Name from Account where Name = :c2.Name][0];

        System.debug(acc.Name);
        if (acc != null) {
            c.AccountId=acc.Id;
            update c;
        }        
    }
}

 

// Niklas

All Answers

nickwick76nickwick76

Hi,

This is the way I perceived want you want to accomplish. On the first lines an account and a contact is created separately. Then query an account where the account name is equal to a contact name. In this case update the contact with a reference to this account.

 

public class Test2 {
    public void testInsertContact() {
        Account a = new Account(Name='John Smith');
        insert a;
        
        Contact c = new Contact(Firstname='John',LastName='Smith');             
        insert c;
        
        Contact c2 = [select Name from Contact where Name = 'John Smith'];
        
        Account acc = [select Id,Name from Account where Name = :c2.Name][0];

        System.debug(acc.Name);
        if (acc != null) {
            c.AccountId=acc.Id;
            update c;
        }        
    }
}

 

// Niklas

This was selected as the best answer
Scott0987Scott0987

Thanks.  Learning Apex from scratch has been an entertaining project.