• AndrewFisher_TGP
  • NEWBIE
  • 25 Points
  • Member since 2012

  • Chatter
    Feed
  • 1
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 8
    Questions
  • 16
    Replies
I have a custom button which instigates Apex to create a PDF and attach it to the record - this works. What I now want it to attach the PDF to a related object (child/parent relationship) but struggling with the ParentID - I underlined where the error is occurring.
Here is the code I have 
public with sharing class SaveAndOpenPDF {   public String recordId {     get {       return ApexPages.currentPage().getParameters().get('Id');     }   }   // this is to make testing a lot easier -- simply append renderAs=html   // to the url parameters to test, add displayOnly=1 if you don't want to save   public String renderAs {     get {       if (String.isBlank(ApexPages.currentPage().getParameters().get('renderAs'))) {         return 'pdf';       } else {         return ApexPages.currentPage().getParameters().get('renderAs');       }     }   }   public PageReference saveAndOpenPDF() {     if (String.isBlank(ApexPages.currentPage().getParameters().get('displayOnly'))) {       Id attachmentId = savePDF();       return openPDF(attachmentId);     } else {       return null;     }   }   public Id savePDF() {     Attachment attachment = new Attachment();     attachment.ParentId = 'aFA.Id';     attachment.name = 'PDF_'+String.valueof(Datetime.now())+'.pdf';     PageReference pdf = Page.SaveAndOpenPDF;     pdf.getParameters().put('Id', recordId);     pdf.getParameters().put('displayOnly', '1');     pdf.setRedirect(true);     try {       attachment.Body = pdf.getContent();     }     catch (VisualForceException e) {       attachment.Body = Blob.valueof('There was an error.');     }     attachment.ContentType = 'application/pdf';     insert attachment;     return attachment.Id;   }   public PageReference openPDF(Id attachmentId) {     PageReference ret = new PageReference('/servlet/servlet.FileDownload?file=' + attachmentId);     ret.setRedirect(true);     return ret;   } }
Could someone help me write a test class for this apex code please?

public with sharing class ProfileTabUserController {
    // Purpose: Custom Chatter profile page
    private ApexPages.StandardController c;

    // Getter methods you can call from your Visualforce page, e.g. {! viewingMyProfile }
    public User subjectUser { get; set; }
    public boolean viewingMyProfile { get; set; } // Whether or not I’m viewing my profile
    public String viewerID { get; set; } // UID string for the viewing user
    public String subjectID { get; set; } // UID string for the subject user (being viewed)

    // Constructor method for the controller
    public ProfileTabUserController(ApexPages.StandardController stdController) {
        c = stdController;
        subjectID = getTargetSFDCUID();

        // If we're operating inside a tab running inside of a profile...
        if (subjectID != null) {
            // Inject the sfdc.userId URL parameter value into the id param
            // so the std User controller loads the right User record
            ApexPages.currentPage().getParameters().put('id', subjectID);
        }

        // Load the User record for the user whose profile we’re viewing
        this.subjectUser = (User)stdController.getRecord();
        Id viewer = Id.valueOf(UserInfo.getUserId());
        Id subject = Id.valueOf(subjectID);
        viewingMyProfile = (viewer == subject);
        viewerID = UserInfo.getUserId();
    }

    // Fetches URL parameter passed into a profile tab indicating which user is being viewed
    private String getTargetSFDCUID() {
        return ApexPages.currentPage().getParameters().get('sfdc.userId');
    }
    // Overrides StandardController save method to force reload of current page afterwards
    public PageReference save() {
        c.save();
        return ApexPages.currentPage();
    }

    // Overrides StandardController cancel method to force page reload
    public PageReference cancel() {
        c.cancel();
        return ApexPages.currentPage();
    }
}
I have created a Profile tab in user profile, but want to display an image from a custom field in the user profile by user, so if that field is populated it displays for that user.
I can do this for all users (see code below) but want it individually by user to allow me to control who dsiplays which image: eg User 1 is ticked on the custom field and the image shows, user 2 is not ticked so that user does not display it.

<apex:page showHeader="false" sidebar="false" standardController="User"> <apex:pageBlock > <apex:pageBlockSection columns="3"> <apex:pageblocksectionItem ><b> Welcome to Salesforce </b></apex:pageblocksectionItem> <apex:pageblocksectionItem ><b> Accounts and Contacts </b></apex:pageblocksectionItem> <apex:pageblocksectionItem ><b> Navigating Salesforce </b></apex:pageblocksectionItem> <apex:pageblocksectionItem > <apex:image url="/servlet/servlet.FileDownload?file=015w0000002vwsL" width="100" height="100"/> </apex:pageblocksectionItem> <apex:pageblocksectionItem > <apex:image url="/servlet/servlet.FileDownload?file=015w0000002vyql" width="100" height="100"/> </apex:pageblocksectionItem> <apex:pageblocksectionItem > <apex:image url="/servlet/servlet.FileDownload?file=015w0000002vyqq" width="100" height="100"/> </apex:pageblocksectionItem> </apex:pageBlockSection> </apex:pageBlock> <apex:pageBlock > <apex:pageBlockSection columns="3"> <apex:pageblocksectionItem ><b> Converting Leads </b></apex:pageblocksectionItem> <apex:pageblocksectionItem ><b> Reports and Dashboards </b></apex:pageblocksectionItem> <apex:pageblocksectionItem ><b> Chatter </b></apex:pageblocksectionItem> <apex:pageblocksectionItem > <apex:image url="/servlet/servlet.FileDownload?file=015w0000002vyqv" width="100" height="100"/> </apex:pageblocksectionItem> <apex:pageblocksectionItem > <apex:image url="/servlet/servlet.FileDownload?file=015w0000002vyr0" width="100" height="100"/> </apex:pageblocksectionItem> <apex:pageblocksectionItem > <apex:image url="/servlet/servlet.FileDownload?file=015w0000002vyr5" width="100" height="100"/> </apex:pageblocksectionItem> </apex:pageBlockSection> </apex:pageBlock> </apex:page>
 
I am trying to add a new flow to a process builder which is to create an opportunity line item with defaulted price book and a defaulted product. I have created the opportunity and contact roles but now need the Opportunity line item. I want it to add when a field is checked (process builder cn do that bit so all ok there) but cannot get the flow to work 

Any help would be appreciated !
Created a report which includes Prevgroup val to trend Quarter on Quarter by year. On the report it works and I can show the historic trend, but cannot add this to a graph as would like it on a dashboard

Is there a workaround ?

Hello one and all, and Merry Christmas (or Happy Holidays).

 

I have an issue with some code I have written that uses AggregateResult (SUM) function, the code is totalling the sum back to the org default currency (which is what is stated in the help documentation).  My issue is when placing the amount totalled back into a currency field on a record with a different currency.

 

So say (hypothetically - for arguments sake lets say that it is £1=$2 conversion rate):
Acct A = US$10 (£5)
Acct B = US$6 (£3)
 
The total should obviously be = US$16 (£8).  The total it is showing is US$ 8 - so it converts the figures into GBP values,  totals the values and then puts this amount into the currency field - though the field is showing the wrong currency code as the account currency is USD.
 
If there is an account that is in GBP - there is no issue though - so yay :-)
 
Is there a way to take the figure that the aggregateresult figure and then convert it back to the account currency?

Hi all,

 

I think my brian is fried as I have been coding all day - I don't even know if I am searching using the correct terminology as I have been jumping between SQL, SOQL, APEX & VB all day...

 

Essentially looking to see if it is possible to compare the results a list collection to the results in another list.

 

As an example - list 1 is generated from the following code:

list<recordType> rT = list<Recordtype>(SELECT ID FROM RecordType  WHERE (Name LIKE '%Standard%' OR Name LIKE '%Parent%')  AND sObjectType = 'Account');

 List 2 is a list of all accounts:

list<Account> ac = list<Account>(SELECT Id, RecordTypeID FROM Account);

 

I know with SOQL you can have a nested query, though in using the 'Database.getQueryLocator' method I seem to be unable to use nested SOQL statements for my batch code...

Hi all, second post here - and I have been toiling away at this all day!! Would very much appreciate some help as I can't seem to find the similar issue in the forum and a solution that I can extrapolate to this scenario.

 

Error message from log/status in Dev Console:

Insert failed: First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, trigger_name: execution of BeforeInsert caused by: System.typeException: Invalid integer: expr0

 

Bit of background, I am writing my first apex trigger to generate a total (sum) in a field on the Account which sums the total amount for related contracts, that will eventually fit within certain criteria (I haven't added this part yet as I just want the basics working first!).

 

 

I know the problem is with my map, aggregateResult/SOQL.  I somehow had it working last night, but I didn't backup & obviously didn't stop to think what I had before I started playing with it!  Originally I had the map populate when it is declared (this isn't is but i remember vaugley it was all inline - something along the lines of):

map<ID, integer> cMap_THISFY = new map<ID, integer>(AggregateResult c: [SELECT AccountID, SUM(Invoice_Amount__c) FROM Contract WHERE AccountID IN :BookingAcctIDs GROUP BY AccountID]);

 

So after tinkering and realising I didn't know where/how all the bolts go back - but it doesn't run!  I had/having all sorts of trouble with the SOQL -> cMap_THISFY - first shot at rebuilding it was:

 

    	map<ID, integer> cMap_THISFY = new map<ID, integer>();
        for (AggregateResult c: [SELECT AccountID, SUM(Invoice_Amount__c)total
                                 FROM Contract 
                                 WHERE AccountID IN :BookingAcctIDs
                                 GROUP BY AccountID])
        	cMap_THISFY.put(c.get('AccountId'), c.get('expr0'));

 But this resulted in a compile error: 'Incompatiable key type Object for MAP<Id,Integer> - which I assume is due to AggregateResult being an object datatype

 

 

I finally got it to compile - this is the full set of the code I have at the moment:

 

/* Trigger to total up the related bookings linked to an account and get a 'total' 
   booking signed amount, when a record is inserted/updated/undeleted/deleted

   Written by: Adam Gill 
   Date: 01/11/2012
   (c) The Gap Partnership
   
*/   

trigger tr_updateBookingSigned on Contract (before insert, before update, after undelete, before delete) {

    //Create new list & map to store Account ID fields & the aggregateresult of SOQL
    set<ID> BookingAcctIDs = new set<ID>();  
	
    //Generate list of Account IDs, for accounts that need to be updated, based on type of trigger
    if (trigger.isDelete){
		for (Contract c : trigger.old){
       		BookingAcctIDs.add(c.AccountID);
      	}
    }
    else {
        for (Contract c : trigger.new){
            BookingAcctIDs.add(c.AccountID);
        }
	}
    
    
    //If Account IDs have been added successfully to list, process required calculations
    if (BookingAcctIDs.size() > 0) {

        system.debug('~~~~ CREATING MAP ~~~~');
    	
        //Create new map to store Account ID & sum amount fields 
    	map<ID, integer> cMap_THISFY = new map<ID, integer>();
        for (AggregateResult c: [SELECT AccountID, SUM(Invoice_Amount__c)total
                                 FROM Contract 
                                 WHERE AccountID IN :BookingAcctIDs
                                 GROUP BY AccountID]){
			ID aID = id.valueof('AccountID');
            integer aSUM = integer.valueof('expr0');
            system.debug('*** ' + aID + ' / ' + aSUM + ' ***');
        	cMap_THISFY.put(aID, aSUM);
        }
    	
        //Create new list to generate list of 'AccountsToUpdate'
    	list<Account> AccountsToUpdate = new list<Account>();
    	
        //From set of accounts IDs, retrieve ID & Bookings_Signed_This_FY field & assign sum from ContractMap.
    	for (Account acct : [SELECT Id, Bookings_Signed_This_FY__c
                             FROM Account
                             WHERE Id IN :BookingAcctIDs]){
//				double dblBookingsSignedThisFY = cMap_THISFY.get(acct.Id);
//          	acct.Bookings_Signed_This_FY__c = dblBookingsSignedThisFY;
            acct.Bookings_Signed_This_FY__c = cMap_THISFY.get(acct.Id);
           	AccountsToUpdate.add(acct);
      	}
    	
        //Update list of accounts with totalled data.
    	update AccountsToUpdate;
    }
}

 I feel like all I am doing is moving side ways, not actually understanding what the problem is... I have looked at a number of blogs but they seem to have been coded in previous versions of the API too: here is one of the blogs I was using to disect and try and learn while reverse engineering the solution I needed.  I orginally started out using the similar map methods but I couldn't get it to complie.  And I have tried to peice together the related examples in the developer blog for aggregateresults, bulk soql queries and maps - but I think I have sent too long looking at it and I can't make heads or tails of it anymore.

 

So with that code above I have it compling and I am using the Execute section of the dev console to create a mini-test which is very basic, but this all I had when I had the script above working, and I haven't updated any permissions in the Dev Sandbox over the last few days (trying to isolate permissions/FLS):

Contract c1 = new Contract();
c1.AccountId = '001R000000kxmFf';
c1.Delivery__c = 'a0IR0000002e7cN';
c1.Key_Booking_Contact__c = '003R000000ihmt5';
c1.Invoice_Amount__c = 50000;
c1.name = 'Test booking:' + string.valueof(datetime.now());
c1.StartDate = date.today();

insert c1;

 

I am pretty sure I am missing something quite simple - but as APEX syntax is a little different from VBA/etc that I have developed with until now, any guidance or assistance would be greatly appreciated - as I am about to start pulling out my hair!! :-)

I have a custom button which instigates Apex to create a PDF and attach it to the record - this works. What I now want it to attach the PDF to a related object (child/parent relationship) but struggling with the ParentID - I underlined where the error is occurring.
Here is the code I have 
public with sharing class SaveAndOpenPDF {   public String recordId {     get {       return ApexPages.currentPage().getParameters().get('Id');     }   }   // this is to make testing a lot easier -- simply append renderAs=html   // to the url parameters to test, add displayOnly=1 if you don't want to save   public String renderAs {     get {       if (String.isBlank(ApexPages.currentPage().getParameters().get('renderAs'))) {         return 'pdf';       } else {         return ApexPages.currentPage().getParameters().get('renderAs');       }     }   }   public PageReference saveAndOpenPDF() {     if (String.isBlank(ApexPages.currentPage().getParameters().get('displayOnly'))) {       Id attachmentId = savePDF();       return openPDF(attachmentId);     } else {       return null;     }   }   public Id savePDF() {     Attachment attachment = new Attachment();     attachment.ParentId = 'aFA.Id';     attachment.name = 'PDF_'+String.valueof(Datetime.now())+'.pdf';     PageReference pdf = Page.SaveAndOpenPDF;     pdf.getParameters().put('Id', recordId);     pdf.getParameters().put('displayOnly', '1');     pdf.setRedirect(true);     try {       attachment.Body = pdf.getContent();     }     catch (VisualForceException e) {       attachment.Body = Blob.valueof('There was an error.');     }     attachment.ContentType = 'application/pdf';     insert attachment;     return attachment.Id;   }   public PageReference openPDF(Id attachmentId) {     PageReference ret = new PageReference('/servlet/servlet.FileDownload?file=' + attachmentId);     ret.setRedirect(true);     return ret;   } }
Could someone help me write a test class for this apex code please?

public with sharing class ProfileTabUserController {
    // Purpose: Custom Chatter profile page
    private ApexPages.StandardController c;

    // Getter methods you can call from your Visualforce page, e.g. {! viewingMyProfile }
    public User subjectUser { get; set; }
    public boolean viewingMyProfile { get; set; } // Whether or not I’m viewing my profile
    public String viewerID { get; set; } // UID string for the viewing user
    public String subjectID { get; set; } // UID string for the subject user (being viewed)

    // Constructor method for the controller
    public ProfileTabUserController(ApexPages.StandardController stdController) {
        c = stdController;
        subjectID = getTargetSFDCUID();

        // If we're operating inside a tab running inside of a profile...
        if (subjectID != null) {
            // Inject the sfdc.userId URL parameter value into the id param
            // so the std User controller loads the right User record
            ApexPages.currentPage().getParameters().put('id', subjectID);
        }

        // Load the User record for the user whose profile we’re viewing
        this.subjectUser = (User)stdController.getRecord();
        Id viewer = Id.valueOf(UserInfo.getUserId());
        Id subject = Id.valueOf(subjectID);
        viewingMyProfile = (viewer == subject);
        viewerID = UserInfo.getUserId();
    }

    // Fetches URL parameter passed into a profile tab indicating which user is being viewed
    private String getTargetSFDCUID() {
        return ApexPages.currentPage().getParameters().get('sfdc.userId');
    }
    // Overrides StandardController save method to force reload of current page afterwards
    public PageReference save() {
        c.save();
        return ApexPages.currentPage();
    }

    // Overrides StandardController cancel method to force page reload
    public PageReference cancel() {
        c.cancel();
        return ApexPages.currentPage();
    }
}
I have created a Profile tab in user profile, but want to display an image from a custom field in the user profile by user, so if that field is populated it displays for that user.
I can do this for all users (see code below) but want it individually by user to allow me to control who dsiplays which image: eg User 1 is ticked on the custom field and the image shows, user 2 is not ticked so that user does not display it.

<apex:page showHeader="false" sidebar="false" standardController="User"> <apex:pageBlock > <apex:pageBlockSection columns="3"> <apex:pageblocksectionItem ><b> Welcome to Salesforce </b></apex:pageblocksectionItem> <apex:pageblocksectionItem ><b> Accounts and Contacts </b></apex:pageblocksectionItem> <apex:pageblocksectionItem ><b> Navigating Salesforce </b></apex:pageblocksectionItem> <apex:pageblocksectionItem > <apex:image url="/servlet/servlet.FileDownload?file=015w0000002vwsL" width="100" height="100"/> </apex:pageblocksectionItem> <apex:pageblocksectionItem > <apex:image url="/servlet/servlet.FileDownload?file=015w0000002vyql" width="100" height="100"/> </apex:pageblocksectionItem> <apex:pageblocksectionItem > <apex:image url="/servlet/servlet.FileDownload?file=015w0000002vyqq" width="100" height="100"/> </apex:pageblocksectionItem> </apex:pageBlockSection> </apex:pageBlock> <apex:pageBlock > <apex:pageBlockSection columns="3"> <apex:pageblocksectionItem ><b> Converting Leads </b></apex:pageblocksectionItem> <apex:pageblocksectionItem ><b> Reports and Dashboards </b></apex:pageblocksectionItem> <apex:pageblocksectionItem ><b> Chatter </b></apex:pageblocksectionItem> <apex:pageblocksectionItem > <apex:image url="/servlet/servlet.FileDownload?file=015w0000002vyqv" width="100" height="100"/> </apex:pageblocksectionItem> <apex:pageblocksectionItem > <apex:image url="/servlet/servlet.FileDownload?file=015w0000002vyr0" width="100" height="100"/> </apex:pageblocksectionItem> <apex:pageblocksectionItem > <apex:image url="/servlet/servlet.FileDownload?file=015w0000002vyr5" width="100" height="100"/> </apex:pageblocksectionItem> </apex:pageBlockSection> </apex:pageBlock> </apex:page>
 
Hi I have an apex class:
public with sharing class ProfileTabUserController {
// Purpose: Custom Chatter profile page
private ApexPages.StandardController c;
// Getter methods you can call from your Visualforce page, e.g. {!viewingMyProfile }
public User subjectUser { get; set; }
public boolean viewingMyProfile { get; set; } // Whether or not I’m viewing my profile
public String viewerID { get; set; } // UID string for the viewing user
public String subjectID { get; set; } // UID string for the subject user (being viewed)
// Constructor method for the controller
public ProfileTabUserController(ApexPages.StandardController stdController) {
c = stdController;
subjectID = getTargetSFDCUID();
// If we're operating inside a tab running inside of a profile...
if (subjectID != null) {
// Inject the sfdc.userId URL parameter value into the id param
// so the std User controller loads the right User record
ApexPages.currentPage().getParameters().put('id', subjectID);
}
// Load the User record for the user whose profile we’re viewing
this.subjectUser = (User)stdController.getRecord();
Id viewer = Id.valueOf(UserInfo.getUserId());
Id subject = Id.valueOf(subjectID);
viewingMyProfile = (viewer == subject);
viewerID = UserInfo.getUserId();
}
// Fetches URL parameter passed into a profile tab indicating which user is being viewed
private String getTargetSFDCUID() {
return
ApexPages.currentPage().getParameters().get('sfdc.userId');
}
// Overrides StandardController save method to force reload of current page afterwards
public PageReference save() {
c.save();
return ApexPages.currentPage();
}
// Overrides StandardController cancel method to force page reload
public PageReference cancel() {
c.cancel();
return ApexPages.currentPage();
}
}



But I need help with a test class. I have this but I keep getting error and it won't let me save. Can anyone help me fix the test class or help me to create a new one? Thanks in advance, here is the test class. 

@isTest
private class ProfileTabControllerTests {

private static testMethod void testProfileTabController() {

User u = [select Id from User where Id = :UserInfo.getUserId() ];

PageReference pageRef = Page.Chatter_Custom;
Test.setCurrentPage(pageRef);
ApexPages.StandardController con = new ApexPages.StandardController(u);
ProfileTabUserController ext = new ProfileTabUserController(con);

System.assertEquals(u.Id, ext.subjectID);
System.assert(viewingMyProfile);

String cancelPage = ext.cancel().getUrl();
String savePage = ext.save().getUrl();

}
}
Thanks in advance.

Requirement is to have a text field or drop down list that the users enters/chooses a product and then clicks search.  The search button then displays all of the opps and quotes where this product is listed.

What would be the best way to achieve this?

Regards,

Hi All, Hoping to get some insights and guidance to solve the first part of the problem. The code below provides the user with a browser window, lets select a file, and on clickling Done should create a record with File Name and File Path. However, this is the error I am getting right now..Please help!((Originally this was a scontrol code working ONLY in IE..this is the second part of the problem)

 

{faultcode:'sf:INVALID_SESSION_ID',faultstring:'INVALID_SESSION_ID:Invalid Session ID found in
SessionHeader: Illegal Session', detail:{UnexpectedErrorFault:{exceptionCode:'INVALID_SESSION_ID',exceptionMessage:'Invalid Session ID found in SessionHeader:Illegal Session',},},}

 

 

Hi,

 

I have a string which I am decoding using base64Decode method, then am encoding it back using base64Encode. Then ultimately I should have the initial string, but in certain case its been truncated.

 

Any idea, why is this happening or am I missing here something?

 

Thanks.

Hello one and all, and Merry Christmas (or Happy Holidays).

 

I have an issue with some code I have written that uses AggregateResult (SUM) function, the code is totalling the sum back to the org default currency (which is what is stated in the help documentation).  My issue is when placing the amount totalled back into a currency field on a record with a different currency.

 

So say (hypothetically - for arguments sake lets say that it is £1=$2 conversion rate):
Acct A = US$10 (£5)
Acct B = US$6 (£3)
 
The total should obviously be = US$16 (£8).  The total it is showing is US$ 8 - so it converts the figures into GBP values,  totals the values and then puts this amount into the currency field - though the field is showing the wrong currency code as the account currency is USD.
 
If there is an account that is in GBP - there is no issue though - so yay :-)
 
Is there a way to take the figure that the aggregateresult figure and then convert it back to the account currency?

Hi all,

 

I think my brian is fried as I have been coding all day - I don't even know if I am searching using the correct terminology as I have been jumping between SQL, SOQL, APEX & VB all day...

 

Essentially looking to see if it is possible to compare the results a list collection to the results in another list.

 

As an example - list 1 is generated from the following code:

list<recordType> rT = list<Recordtype>(SELECT ID FROM RecordType  WHERE (Name LIKE '%Standard%' OR Name LIKE '%Parent%')  AND sObjectType = 'Account');

 List 2 is a list of all accounts:

list<Account> ac = list<Account>(SELECT Id, RecordTypeID FROM Account);

 

I know with SOQL you can have a nested query, though in using the 'Database.getQueryLocator' method I seem to be unable to use nested SOQL statements for my batch code...

Hi all, second post here - and I have been toiling away at this all day!! Would very much appreciate some help as I can't seem to find the similar issue in the forum and a solution that I can extrapolate to this scenario.

 

Error message from log/status in Dev Console:

Insert failed: First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, trigger_name: execution of BeforeInsert caused by: System.typeException: Invalid integer: expr0

 

Bit of background, I am writing my first apex trigger to generate a total (sum) in a field on the Account which sums the total amount for related contracts, that will eventually fit within certain criteria (I haven't added this part yet as I just want the basics working first!).

 

 

I know the problem is with my map, aggregateResult/SOQL.  I somehow had it working last night, but I didn't backup & obviously didn't stop to think what I had before I started playing with it!  Originally I had the map populate when it is declared (this isn't is but i remember vaugley it was all inline - something along the lines of):

map<ID, integer> cMap_THISFY = new map<ID, integer>(AggregateResult c: [SELECT AccountID, SUM(Invoice_Amount__c) FROM Contract WHERE AccountID IN :BookingAcctIDs GROUP BY AccountID]);

 

So after tinkering and realising I didn't know where/how all the bolts go back - but it doesn't run!  I had/having all sorts of trouble with the SOQL -> cMap_THISFY - first shot at rebuilding it was:

 

    	map<ID, integer> cMap_THISFY = new map<ID, integer>();
        for (AggregateResult c: [SELECT AccountID, SUM(Invoice_Amount__c)total
                                 FROM Contract 
                                 WHERE AccountID IN :BookingAcctIDs
                                 GROUP BY AccountID])
        	cMap_THISFY.put(c.get('AccountId'), c.get('expr0'));

 But this resulted in a compile error: 'Incompatiable key type Object for MAP<Id,Integer> - which I assume is due to AggregateResult being an object datatype

 

 

I finally got it to compile - this is the full set of the code I have at the moment:

 

/* Trigger to total up the related bookings linked to an account and get a 'total' 
   booking signed amount, when a record is inserted/updated/undeleted/deleted

   Written by: Adam Gill 
   Date: 01/11/2012
   (c) The Gap Partnership
   
*/   

trigger tr_updateBookingSigned on Contract (before insert, before update, after undelete, before delete) {

    //Create new list & map to store Account ID fields & the aggregateresult of SOQL
    set<ID> BookingAcctIDs = new set<ID>();  
	
    //Generate list of Account IDs, for accounts that need to be updated, based on type of trigger
    if (trigger.isDelete){
		for (Contract c : trigger.old){
       		BookingAcctIDs.add(c.AccountID);
      	}
    }
    else {
        for (Contract c : trigger.new){
            BookingAcctIDs.add(c.AccountID);
        }
	}
    
    
    //If Account IDs have been added successfully to list, process required calculations
    if (BookingAcctIDs.size() > 0) {

        system.debug('~~~~ CREATING MAP ~~~~');
    	
        //Create new map to store Account ID & sum amount fields 
    	map<ID, integer> cMap_THISFY = new map<ID, integer>();
        for (AggregateResult c: [SELECT AccountID, SUM(Invoice_Amount__c)total
                                 FROM Contract 
                                 WHERE AccountID IN :BookingAcctIDs
                                 GROUP BY AccountID]){
			ID aID = id.valueof('AccountID');
            integer aSUM = integer.valueof('expr0');
            system.debug('*** ' + aID + ' / ' + aSUM + ' ***');
        	cMap_THISFY.put(aID, aSUM);
        }
    	
        //Create new list to generate list of 'AccountsToUpdate'
    	list<Account> AccountsToUpdate = new list<Account>();
    	
        //From set of accounts IDs, retrieve ID & Bookings_Signed_This_FY field & assign sum from ContractMap.
    	for (Account acct : [SELECT Id, Bookings_Signed_This_FY__c
                             FROM Account
                             WHERE Id IN :BookingAcctIDs]){
//				double dblBookingsSignedThisFY = cMap_THISFY.get(acct.Id);
//          	acct.Bookings_Signed_This_FY__c = dblBookingsSignedThisFY;
            acct.Bookings_Signed_This_FY__c = cMap_THISFY.get(acct.Id);
           	AccountsToUpdate.add(acct);
      	}
    	
        //Update list of accounts with totalled data.
    	update AccountsToUpdate;
    }
}

 I feel like all I am doing is moving side ways, not actually understanding what the problem is... I have looked at a number of blogs but they seem to have been coded in previous versions of the API too: here is one of the blogs I was using to disect and try and learn while reverse engineering the solution I needed.  I orginally started out using the similar map methods but I couldn't get it to complie.  And I have tried to peice together the related examples in the developer blog for aggregateresults, bulk soql queries and maps - but I think I have sent too long looking at it and I can't make heads or tails of it anymore.

 

So with that code above I have it compling and I am using the Execute section of the dev console to create a mini-test which is very basic, but this all I had when I had the script above working, and I haven't updated any permissions in the Dev Sandbox over the last few days (trying to isolate permissions/FLS):

Contract c1 = new Contract();
c1.AccountId = '001R000000kxmFf';
c1.Delivery__c = 'a0IR0000002e7cN';
c1.Key_Booking_Contact__c = '003R000000ihmt5';
c1.Invoice_Amount__c = 50000;
c1.name = 'Test booking:' + string.valueof(datetime.now());
c1.StartDate = date.today();

insert c1;

 

I am pretty sure I am missing something quite simple - but as APEX syntax is a little different from VBA/etc that I have developed with until now, any guidance or assistance would be greatly appreciated - as I am about to start pulling out my hair!! :-)

I got this error trying to deploy some test code: 

 

System.DmlException: Insert failed. First exception on row 0; first error: DUPLICATE_VALUE, duplicate value found: <unknown> duplicates value on record with id: <unknown>

 

Is anyone familiar with this?