Basic Apex Code Script

The following sample Apex script illustrates the brevity and power of the language. This script will help you understand the detailed syntax; it relies on the standard Account and Contact objects from the Sample Schema.

The sample Apex script:

1. Cleans up old data.

2. Inserts Accounts.The Account Ids are written back to the script array, so we can reference those Ids when we create the Contacts in the last step.

3. Supplies the name standard field and the outstandingshares custom field.

4. Inserts two Contacts for each Account.


Integer NUM = 10;

Account[] accs;

// Clean up old data
accs = [select id from account where name like 'test%'];
delete accs;
commit;

accs = new Account[NUM];

for (Integer i = 0; i < NUM; i++) {
    accs[i] = new Account(name='test ' + i, outstandingshares__c=i);
}
insert accs;

Contact[] cons = new Contact[0];
for (Account acc : accs) {
    cons.add(new Contact(lastName=acc.name + '1', accounted=acc.id));
    cons.add(new Contact(lastName=acc.name + '2', accounted=acc.id));
}
insert cons;

Now suppose we're writing an upgrade script that needs to copy the outstandingshares value from the Account object into the child Contact object. This can be accomplished simply in Apex with a foreign key SOQL relationship query and an update operation:


cons = new Contact[0];
for (Contact con : [select id, account.outstandingshares__c 
                    from contact where lastname like 'test%']) {
    con.outstandingshares__c = con.account.outstandingshares__c;
    cons.add(con);
}
update cons;

Finally, we can use the script to move data from the child records to the parent using aggregate relationships. For example, suppose we wanted to sum this new field from the list of child Contacts back into the parent Accounts:

accs = new Account[0];
for (Account acc : [select id, (select outstandingshares__c 
                                from contacts) 
                    from account where name like 'test%']) {
    Double tot = 0;
    for (Contact con : acc.contacts) tot += con.outstandingShares__c;
    acc.totalshares__c = tot;
    accs.add(acc);
}
update accs;