+ Start a Discussion
jaw999jaw999 

Insert Opportunity Trigger

Hi, I need to insert an Opportunity when another object is created - both will be linked to the same Account.

Below is my code.

I cannot get the Opportunity to link to the Account. Debug tells me it is finding the right Accout. Thanks

 

 

trigger addProspectfromLeadshort on short__c (after insert) {
List <opportunity> NewOpp = new List<Opportunity>();

List <id> ProspAcct = new List <id>();

Date prepDate = date.today();
Date CloseDate = prepDate.addDays(60);

for (short__c newshort: Trigger.New)
    if (newshort.Status__c=='Lead' && newshort.Account__c != NULL){
       ProspAcct.add(newshort.Account__c);
       system.debug('prospAcct============================='+ProspAcct);
       
       List <Account> TheAcct = [select id, name from Account where ID IN: ProspAcct limit 1];
       system.debug('theAcct============================='+theAcct);
       
        NewOpp.add (new Opportunity (
        Name = newshort.name+TheAcct,
        CloseDate = closeDate,
        StageName = 'Prospecting',
        Account= TheAcct
        ));
}
insert newOpp;
}

 

Samba GSamba G
trigger addProspectfromLeadshort on short__c (after insert) {
List <opportunity> opps = new List<Opportunity>();
Map<String, Short__c> shortAccountMap = new Map<String, Short__c>();
Date CloseDate = date.today().addDays(60);

for (short__c newshort: Trigger.New)
{
    if (newshort.Status__c=='Lead' && newshort.Account__c != NULL)
    {
        shortAccountMap.put(newshort.Id, newshort);
    }  
}
    for(Account acc : [select id, name from Account where ID in : shortAccountMap.keySet()])
    {
        Short__c short = shortAccountMap.get(acc.id);
        opps.add (new Opportunity (
        Name = short.name,
        CloseDate = closeDate,
        StageName = 'Prospecting',
        AccountId = acc.Id
        ));
    }
    if(opps.size() > 0)
    {
       insert opps;
    }
}

 Please give it a try.

 

Hope this helps.

 

Thanks,

Samba

jaw999jaw999

Hmm thanks, but I get a compile error.

Error: Compile Error: Identifier name is reserved: short at line 15 column 22

 

 

Short__c short = shortAccountMap.get(acc.id);
Samba GSamba G

You can change short to shortProxy.

 

 

Thanks,

Samba

 

 

jaw999jaw999

Thanks. 

Hmm. It is not adding an opportunity. 

 

Debug tells me it is finding no rows from the line 15:  for(Account acc : [select id, name from Account where ID in : shortAccountMap.keySet()])

 

I changed the map in line 10 to:

 

shortAccountMap.put(newshort.Account__c, newshort);

 

and it seems to be working now!