• BrandiT
  • NEWBIE
  • 140 Points
  • Member since 2009

  • Chatter
    Feed
  • 5
    Best Answers
  • 1
    Likes Received
  • 0
    Likes Given
  • 89
    Questions
  • 85
    Replies

I could use some help with correcting an apex class I have.  The apex class copies values of fields from one object to another.  I have a field called Request_Type2__c that was a picklist field.  I had to convert this over to a multi-select picklist and now the apex class is not working.  The values don't copy over.  How can I rewrite this so that the values copy over?  There are only 3 possibles values for the field: Media Plan; Art; Digital

 

Here is my class (the part in red is the part not working, both fields are Multi-Select with the same possible values):

 

public class OppSaveAttach{
    ApexPages.StandardController controller;
        public OppSaveAttach(ApexPages.StandardController con){
                controller = con;
                     }                                      
public PageReference save()
 {        
 
Opportunity opp = (Opportunity)controller.getRecord();  

  Media_Plan_History__c mp = new Media_Plan_History__c
    (Opportunity__c=Opp.id, states_needed__c=opp.states__c,
    states_included__c=opp.states_included__c,
    Zip_Locations_Attached__c=opp.zip_locations_attached__c,
    city_locations_attached__c=opp.city_locations_attached__c,
    radius__c=opp.radius__c, media_planner__c=opp.media_planner__c,
    comments__c=opp.comments_to_support__c,
    request_type2__c=opp.sh_request_type__c
    );
 insert mp;
  
  if (opp.support_requests__c != null)
  opp.support_requests__c = opp.support_requests__c + 1;

UPDATE OPP;

            controller.save();           
            return page.Opp_Add_Attachments;
}
}

 

 

Thanks in advance!!

I'm trying to create a custom clone button on opportunity that will clone the current opportunity and populate the current opportunity id in a lookup field on the new opportunity. Then if Opp2 is cloned, the id for Opp2 should populate in the lookup field on the new Opp3.

 

It works great when the original opportunity is cloned.  However, when I clone the 2nd Opportunity (Opp2) and create Opp3, the lookup field on Opp3 shows the original Opportunity, instead of Opp2.  I cannot figure out why it's doing this.  Any ideas how I can fix?

 

Opp1 - Clone to create Opp2 (lookup should show Opp1)

Opp2 - Clone to create Opp3 (lookup should show Opp2, but shows Opp1)

 

Here's my button code.  Can anyone see what I'm doing wrong?

 

/{!Opportunity.Id}/e?clone=1&retURL=%2F006S0000006odYS&CF00NS0000001D9ZZ__lkid={!Opportunity.Id}&CF00NS0000001D9ZZ={!Opportunity.Name}&00NS0000001D93x=0 

I need a second set of eyes on this trigger I'm trying to build.  I don't have a lot of experience with triggers so I found one I'm trying to modify to my purposes.

 

On our opportunity object, if a user needs to make changes after it's been sold, they have to clone the record and start over, instead of editing.  I have a checkbox field called Superceded that should be checked on the original opportunity after it's cloned (this is what I'm trying to accomplish with my trigger).

 

I also have a lookup field for the newly clonsed record that will show the parent or original opportunity called Previous_Version__c.

 

I'm trying to create a trigger that will fire after insert on new opportunities only if the Previous_Version__c field is populated.  The trigger should update the opportunity in the Previous_Version__c lookup field and check the Superceded__c checbox on that parent record.

 

Here is what I've got so far:

 


trigger UpdatePreviousOpp on Opportunity (after insert){
 
Opportunity[] opp;
opp = Trigger.new;
 
set<Id> prevoppIds = new Set <ID>();
 
for (Opportunity op : opp) {
      if(opp.previous_version__c != null) {
         prevoppIds.add(op.previous_version__c);
    }
 
Map<ID, Opportunity> proppsToUpdate = new Map<ID, Opportunity> (
    [select Id, supercedure__c from Opportunity
    where Id in :prevoppIds]);

 
List<Opportunity> preoppUpd = new List<Opportunity>{};
 
for (Opportunity opp : preoppsToUpdate.values()) {
    opp.supercedure__c = true;
    update opp;
    preoppUpd.add(opp);
}


if (preoppUpd != null && !preoppUpd.isEmpty())
Database.update(preoppUpd);

}
}

 

Here is the message I'm getting.  Any idea how I can get this to work?

 

Error: Compile Error: Initial term of field expression must be a concrete SObject: LIST<Opportunity> at line 9 column 10

 

 

 

Good morning,

I'm needing a custom clone functionality and can't figure out how to do it.

 

I want a button that will update the current opportunity (field Previous_Version__c=True), then clone it with Previous_Version__c=False.  I've figured out the cloning part, but is it possible to have the button update the current record before it clones it?

 

Thanks so much!

I have a visualforce page that is supposed to update several objects at once: contract, opportunity, account, parent.parent account; Agency__c.

 

I'm getting this error message:  Attempt to de-reference a null object

 

I'm pretty sure I know why I'm getting this message already, I'm just not sure how to fix it.  On my test account, the NSA_Agencies__c lookup field is null.  What I need to know is how do I modify my apex class to check for nulls before the code tries to do the update.  The part of the code in red updates all related records that might be affected, but should really be modified to ensure the fields are populated first.  What is the format for this null check?

 

Here is my apex class:

public with sharing class RPM_Credit {
   
    ApexPages.StandardController controller;
    public Contract contract {get; set;}

    public Opportunity opportunity {get; set;}
   
    public Account account {get; set;}
   
    public NSA_Agencies__c agency {get; set;}
   
    public Account parent {get; set;}

     
public RPM_Credit(ApexPages.StandardController con){
                            controller = con;

contract = (Contract) controller.getRecord();

opportunity = contract.Opportunity__r;

account = contract.account;

agency = contract.account.RPM_NSA_Agency__r;

parent = contract.account.parent.parent;
                                                      
                                                 }                                  
  public PageReference saveall() {

           update opportunity;
           update account;
           update agency;
           update parent;
           controller.save(); 
          
           PageReference ref = new PageReference('/00O70000003JDRo');
            ref.setRedirect(true);
       
    return ref;
            }

   

}

 

 

Thanks!

I have a trigger on contract that is supposed to update values on the related opportunity.  It has worked fine for a while now, but it suddenly starting throwing duplicate value errors for about half the contracts we update.  I haven't made any recent development changes so I'm not sure what's causing it, or even how to research it.  I would appreciate any insight you can give me.

 

Here's the error I'm getting: 

Validation Errors While Saving Record(s)
There were custom validation error(s) encountered while saving the affected record(s). The first validation error encountered was "Apex trigger ContractSumOppTrigger caused an unexpected exception, contact your administrator: ContractSumOppTrigger: execution of AfterUpdate caused by: System.DmlException: Update failed. First exception on row 0 with id 0067000000OOHZkAAP; first error: DUPLICATE_VALUE, duplicate value found: unknown duplicates value on record with id: 0017000000oL0gj: []: Trigger.ContractSumOppTrigger: line 88, column 1".
 

The interesting thing about the error is that a) the id  0017000000oL0gj is an account record, and I don't do anything with accounts in my trigger, and b) the account is not related to the contract that's being updated in any way.

 

Here's the trigger:

 

trigger ContractSumOppTrigger on Contract
 (after delete, after insert, after undelete, after update) {   
 
 Contract[] cons;
     if (Trigger.isDelete)
          cons = Trigger.old;
              else
                      cons = Trigger.new;   
 // get list of opptys
     Set<ID> oppIds = new Set<ID>();   
     for (Contract con : cons) {
                 oppIds.add(con.Opportunity__c);
                     }
     Map<ID, Contract> contractsForOpps = new Map<ID, Contract>([select Id                                                           
     ,Opportunity__c                                                          
     from Contract                                                           

where Opportunity__c in :oppIds
                       ]);
               Map<ID, Opportunity> oppsToUpdate = new Map<ID, Opportunity>([select Id                                                                
               ,Total_Contracts__c                                                                 
               from Opportunity                                                                 
               where Id in :oppIds]);    

                     for (Opportunity opp : oppsToUpdate.values()) {
                             Set<ID> conIds = new Set<ID>();
                                     for (Contract con : contractsForOpps.values()
                                     ) {
                                                 if (con.Opportunity__c == opp.Id)
                        conIds.add(con.Id);
                                }
               
                if (opp.Total_Contracts__c != conIds.size())
                    opp.Total_Contracts__c = conIds.size();
                               }
                                   update oppsToUpdate.values();


//Create a set of Oppty IDs and a Map of Opptys to Update
     Set<id> opptyIds = new Set<id>(); Map<Id,Opportunity> opptysToUpdate = new Map<Id,Opportunity>();

//Add Oppty ID's to the set
     if(Trigger.isInsert || Trigger.isUpdate){

          for (Contract c : Trigger.new) {

               opptyIds.add(c.Opportunity__c); } }

     if (Trigger.isUpdate || Trigger.isDelete) {

          for (Contract c : Trigger.old) {

               opptyIds.add(c.Opportunity__c); } }

//Populate the opptysToUpdate map with fields from the Oppty and related Contracts:
     for (Opportunity opptys :

          [SELECT Id, Signed_Contracts__c,

               (SELECT Id, RPM_Signed_Contract__c

               FROM Contracts__r)

          FROM Opportunity WHERE Id in :opptyIds]){

         opptysToUpdate.put(opptys.id,opptys);

     }


//For every oppty...
     for (Opportunity oppty : opptysToUpdate.values()) {

//Initialize all sums to '0':
     double sumSigned = 0;

//... loop through associated contracts and calculate the signed ones:
     for (Contract cnt: oppty.Contracts__r){
          sumSigned += cnt.RPM_Signed_Contract__c;

     }

//Set the rollup sum on the current oppty:
     oppty.Signed_Contracts__c = sumSigned;
     }

//Finally update all affected goals:
update opptysToUpdate.values();


//Create a set of Oppty IDs and a Map of Opptys to Update
     Set<id> opptyIds2 = new Set<id>(); Map<Id,Opportunity> opptysToUpdate2 = new Map<Id,Opportunity>();

//Add Oppty ID's to the set
     if(Trigger.isInsert || Trigger.isUpdate){

          for (Contract c : Trigger.new) {

               opptyIds2.add(c.Opportunity__c); } }

     if (Trigger.isUpdate || Trigger.isDelete) {

          for (Contract c : Trigger.old) {

               opptyIds2.add(c.Opportunity__c); } }

//Populate the opptysToUpdate map with fields from the Oppty and related Contracts:
     for (Opportunity opptys2 :

          [SELECT Id, Cancelled_Recalled_Contracts__c,

               (SELECT Id, Cancelled_Recalled_Ind__c

               FROM Contracts__r)

          FROM Opportunity WHERE Id in :opptyIds2]){

         opptysToUpdate2.put(opptys2.id,opptys2);

     }


//For every oppty...
     for (Opportunity oppty2 : opptysToUpdate2.values()) {

//Initialize all sums to '0':
     double sumSigned = 0;

//... loop through associated contracts and calculate the signed ones:
     for (Contract cnt: oppty2.Contracts__r){
          sumSigned += cnt.Cancelled_Recalled_Ind__c;

     }

//Set the rollup sum on the current oppty:
     oppty2.Cancelled_Recalled_Contracts__c = sumSigned;
     }

//Finally update all affected goals:
update opptysToUpdate2.values();

}

 

 

Thanks!

I have an account trigger that has always worked fine with no problems, but today when I was doing a mass insert / update of records, I kept getting an error message:

 

Apex script unhandled trigger exception by user/organization: 00570000001Frz1/00D700000009SRz

 

AutoCltGroup: execution of BeforeInsert

 

caused by: System.DmlException: Insert failed. First exception on row 0 with id a0F70000009GrlXEAS; first error: INVALID_FIELD_FOR_INSERT_UPDATE, cannot specify Id in an insert call: [Id]

 

Trigger.AutoCltGroup: line 47, column 1

 

 

What do I need to change in my trigger code to prevent this type of error:

 

trigger AutoCltGroup on Account (before insert, before update) {

list <Client_Groups__c> CGs = new list <Client_Groups__c> ();
list <Client_Groups__c> CG996 = new list <Client_Groups__c> ();
list <Client_Groups__c> CG997 = new list <Client_Groups__c> ();

list <Account> P996 = new list <Account> ();
list <Account> P997 = new list <Account> ();
list <Account> A300 = new list <Account> ();
list <Account> A343 = new list <Account> ();
list <Client_Groups__c> NewCG = new list <Client_Groups__c> ();
list <Recordtype> CltRT = new list <Recordtype> ();

List<Account> Agency = new List <Account> {};

CGs = [Select ID From Client_Groups__c Where Name='UNGROUPED' limit 1];
CG996 = [Select ID From Client_Groups__c Where Name='RPM996' limit 1];
CG997 = [Select ID From Client_Groups__c Where Name='RPM997' limit 1];

P996 = [Select ID From Account Where Natl_Identifier__c='343-996-0' limit 1];
P997 = [Select ID From Account Where Natl_Identifier__c='300-997-0' limit 1];
A300 = [Select ID From Account Where Natl_Identifier__c='343-0-0' limit 1];
A343 = [Select ID From Account Where Natl_Identifier__c='300-0-0' limit 1];
CltRT = [Select ID From Recordtype Where Name='Client' limit 1];

for (Account a : trigger.new)
{
    if (a.cmr_number__c == '996' && CG996.size()>0)
    {
        a.Client_Group__c = CG996[0].id;
        a.ParentId = P996[0].id;
        a.Agency_Account__c = A343[0].id;
    }
   
    else if (a.cmr_number__c == '997' && CG997.size()>0)
    {   
        a.Client_Group__c = CG997[0].id;
        a.ParentId = P997[0].id;
        a.Agency_Account__c = A300[0].id;  
    }   

    else if (a.cmr_number__c != '997' && a.cmr_number__c != '996' && a.RecordTypeId == CltRT[0].id && a.Client_Group__c == null)
    {   
        NewCG.add
        (new Client_Groups__c
        (Name=a.client_name__c,Agency_Account__c = a.agency_account__r.id));
        insert NewCG;
       
        a.Client_Group__c = NewCG[0].id;  
    }   

    else if (a.cmr_number__c != '997' && a.cmr_number__c != '996' && a.Client_Group__c!= null)
    {   
        
    }
          
    else
        a.Client_Group__c = CGs[0].id;  
       
    }
}

I need help modifying a trigger I wrote.  The trigger is supposed to update the parent opportunity record everytime the child record, Media_Plan_History__c, is updated, which works correctly.  

 

I need to add a condition to the trigger so that the opportunity is only updated if a checkbox called Active__c is set to True on the Media_Plan_History__c record.  Where can I add this logic to the trigger?  I can't quite figure it out.

 

Thanks!

 

Here's my trigger:

 

trigger OppOwnerSH on Media_Plan_History__c (after update) {

 

Media_Plan_History__c[] shs;
shs = Trigger.new;

 

set<Id> oppIds = new Set <ID>();

 

for (Media_Plan_History__c sh : shs) {
    oppIds.add(sh.Opportunity__c);

 

Map<ID, Opportunity> oppsToUpdate = new Map<ID, Opportunity> (
    [select Id, Media_Planner_2__c from Opportunity
    where Id in :oppIds]);

 

List<Opportunity> oppUpd = new List<Opportunity>{};

 

for (Opportunity opp : oppsToUpdate.values()) {
    opp.media_planner_2__c = sh.media_planner_2__c;
    update opp;
    oppUpd.add(opp);

}

 

if (oppUpd != null && !oppUpd.isEmpty())
Database.update(oppUpd);
}
}

I need help with a simple trigger.  I have an object called Media_Plan_History, which is a child to the Opportunity object.  There can only be one active Media Plan History record per Opportunity.

 

Both objects have a lookup field called Media Planner.  I need a trigger that will fire when the Media Plan History record is updated that would update the Media Planner field on the parent opportunity record to match the Media Planner field on the Media History Plan.

 

so opp.Media_Planner__c = mph.Media_Planner__c

 

Here is what I have so far, but I'm missing something important because I keep getting error messages:

 

trigger OppOwnerSH on Media_Plan_History__c (after update) {

Media_Plan_History__c[] shs;
shs = Trigger.new;

set<Id> oppIds = new Set <ID>();

for (Media_Plan_History__c sh : shs) {
    oppIds.add(sh.Opportunity__c);

Map <ID, Media_Plan_History__c> shforOpps = new Map <ID, Media_Plan_History__c> (
    [select Id, opportunity__c, Media_Planner_2__c, Artist_2__c from Media_Plan_History__c
    where opportunity__c in :oppIds]);

Map<ID, Opportunity> oppsToUpdate = new Map<ID, Opportunity> (
    [select Id, Media_Planner_2__c, Artist_2__c from Opportunity
    where Id in :oppIds]);

for (Opportunity opp : oppsToUpdate) {
    opp.media_planner_2__c = sh.media_planner_2__c;
    update opp;
}}}

 

 

Here's the message I'm getting:

Error: Compile Error: Loop must iterate over a collection type: MAP<Id,Opportunity> at line 19 column 24

 

 

 

 

 

I would really appreciate some help with this one.  I'm stil pretty new to coding.  Thank you!!

I'm trying to write a trigger that updates the child records on an Opportunity when a formula field - Contract Status - shows the value Cancelled/Recalled.  I'm not trying to update the Contract Status field, I just referencing it so that the trigger only fires when it shows that one value.

 

Here's the trigger and error message.  I'm at a loss as to how to fix this.

 

trigger CancelSuppHistory on Opportunity (before update) {

If(Trigger.isUpdate){
    
     Set<ID> ids = new Set<ID>();
     list<Opportunity> updOpps =
     [SELECT Id,
                 (Select Id, opportunity__c, active_media_plan__c, active_art__c
                  from Media_Plan_History__r ) FROM Opportunity
                 WHERE Id in :ids];        
                
                 List<Media_Plan_History__c> SHToUpdate = new List<Media_Plan_History__c>();

         //Then loop through each parent object in 'updated parent
         for (Opportunity Opp : updOpps)
         {
             if(opp.contract_status__c = 'Cancelled/Recalled')
            
                //and loop thru each kid in the child set}
               for(Media_Plan_History__c sh : Opp.Media_Plan_History__r)
               {
                         ///update logic from above
                          if(sh.active_media_plan__c = TRUE)

{
       sh.active_media_plan__c =  FALSE;
      shToUpdate.add(sh);
}
                }
        }
       if( !shToUpdate.isEmpty)
       {
            update shToUpdate;
       }
}


}

 

 

Error: Compile Error: Field is not writeable: Opportunity.Contract_Status__c at line 17 column 17

 

I'm trying to create a trigger that will fire when an opportunity is updated with a checkbox "create_hybrid__c" checked.  The trigger should create a new account record and then update a field on the opportunity with the new account.

 

I can get the trigger to create the new account, but any criteria that references the opportunity is ignored.  I've highlighted those lines in red below.  Also, I specifically assign a record type in the trigger, but the account is created with a completely different record type.  I also tried to assign a parent account and that criteria was ignored.

 

Is there any way to modify the trigger below so that all the fields I've specified are populated correctly?  With this trigger, an account is created, the name, agency_id__c, cmr_numer__c, and assign_rpm_client__c are populated correctly, the record type is not correct, and the other fields I specified are just left blank.

 

trigger CreateHybridAcct on Opportunity (before update) {

 

List<Account> a = new List<Account>();

 

for (Opportunity p : Trigger.new){
    if (p.create_hybrid__c == True) {
   
    a.add (new Account(
            name = 'testtrigger',
            agency_id__c = '300',
            cmr_number__c = '997',
            client_name__c = p.account.name,
            hybrid_account__c = p.account.id,
            owner = p.owner,
            recordtypeid = '01270000000UHZcAAO',
            parentid = '0017000000PgOvrAAF',
            assign_rpm_client__c = TRUE
            ));
           
    insert a;
   
    //p.hybrid_account__c = h.id;
    p.create_hybrid__c = false;     
            
    }

}
}

Is it possible to create a link on an external website that will take a user directly to a record in the salesforce.com mobile app?

 

I know I can build a link to view a record in Salesforce.com, but if I wanted to view the record specifically from the mobile app (Ipad users), could a link launch the app and go to the record?  How would I build that functionality or is there a better way to do it?

 

Thanks!

My visualforce page has a section that should only be 1 column wide.  I've specified 1 column in the page block, but the section still displays the information one half of the screen width.  I need the section to stretch across the page.  Any idea how to fix it?

 

Here's the code that's giving me trouble:

<apex:pageblockSection title="Scorecard" columns="1">

 

<apex:pageblockSectionItem >

<apex:outputLabel value="How well does this fit with the vision*?" style="font-weight:bold"/>

<apex:inputField value="{!Ideas_Projects__c.Fits_Vision__c}"/>

</apex:pageBlockSectionItem>

 

<apex:pageblockSectionItem >

<apex:outputLabel value="How effective is this at generating client leads?"/>

<apex:inputField value="{!Ideas_Projects__c.Fits_Vision__c}"/>

</apex:pageBlockSectionItem>

 

<apex:pageblockSectionItem >

<apex:outputLabel value="How well does this support consumer convenience** of one experience?"/>

<apex:inputField value="{!Ideas_Projects__c.Fits_Vision__c}" />

</apex:pageBlockSectionItem>

 

<apex:pageblockSectionItem >

<apex:outputLabel value="How would you describe the consumer driven point-of-difference?"/>

<apex:inputField value="{!Ideas_Projects__c.Fits_Vision__c}" />

</apex:pageBlockSectionItem>

 

<apex:pageblockSectionItem >

<apex:outputLabel value="How adaptable is this to multi-platform distribution?"/>

<apex:inputField value="{!Ideas_Projects__c.Fits_Vision__c}" />

</apex:pageBlockSectionItem>

 

<apex:pageblockSectionItem >

<apex:outputLabel value="How would you describe the competitive landscape?"/>

<apex:inputField value="{!Ideas_Projects__c.Fits_Vision__c}" />

</apex:pageBlockSectionItem>

 

<apex:pageblockSectionItem >

<apex:outputLabel value="How much revenue*** does this generate?"/>

<apex:inputField value="{!Ideas_Projects__c.Fits_Vision__c}" />

</apex:pageBlockSectionItem>

 

<apex:pageblockSectionItem >

<apex:outputLabel value="How operationally complex will this be to implement?"/>

<apex:inputField value="{!Ideas_Projects__c.Fits_Vision__c}" />

</apex:pageBlockSectionItem>

 

<apex:pageblockSectionItem >

<apex:outputLabel value="How much time will this take to launch?"/>

<apex:inputField value="{!Ideas_Projects__c.Fits_Vision__c}" />

</apex:pageBlockSectionItem>

 

<apex:outputText >

* Vision, as defined in Internet Strategy document.<br/>

** Convenience as defined by the ability to deliver a "Find, Discover, Buy" experience.<br/>

*** Estimated revenue for first 12 months following launch.

</apex:outputText>

 

</apex:pageblockSection>

 

Any ideas?

I have a apex extension class that is supposed to save data from a visualforce page into several different objects.  The main object is contract, but the class should also update the account, opportunity, and a custom object called NSA_Agencies__c.  The NSA_Agencies__c field is not a required lookup field, so when I try to save a contract that has no agency, I get an exception - Attempt to de-reference a null object

 

How do I code my controller extension to only save if that lookup field is populated?  If not populated, the code should ignore that part of the save function.

 

Here is my extension:

 

public

withsharingclassRPM_Credit {

 

ApexPages.StandardController controller;

publicContract contract {get; set;}

 

publicOpportunity opportunity {get; set;}

 

publicAccount account {get; set;}

 

publicNSA_Agencies__c agency {get; set;}

 

public

RPM_Credit(ApexPages.StandardController con){

controller = con;

 

contract = (

Contract) controller.getRecord();

 

opportunity = contract.Opportunity__r;

 

account = contract.account;

 

agency = contract.account.RPM_NSA_Agency__r;

 

}

publicPageReference saveall() {

 

updateopportunity;

 

updateaccount;

 

updateagency;

controller.save();

 

PageReference pageRef =

new PageReference('https://na5.salesforce.com/00O70000003JDRo');

 

returnnull;

}

 

 

 

}

 

Thank you!!

 

  • September 28, 2011
  • Like
  • 0

I'm trying to create a trigger on Opportunities that will create a new account when a box on the opportunity is checked, then update a lookup field on that same opportunity with the newly created account.  I'm getting a self-reference error.

 

Here is the trigger:

 

trigger

CreateHybridAcct onOpportunity (beforeupdate) {

 

for

(Opportunity p : [SELECT ID, ACCOUNT.Name, ACCOUNT.ID, ACCOUNT.Client_Name__c, Create_Hybrid__c, Ownerid

 

FROM OPPORTUNITY WHERE ID in :Trigger.new]){

 

if(p.create_hybrid__c == True) {

 

Account h = newAccount(

name =

'testhybrid',

agency_id__c =

'300',

cmr_number__c =

'997',

client_name__c = p.account.name,

hybrid_account__c = p.account.id,

//owner = p.owner,

lead_converted_date__c = date.

today()

 

//recordtypeid = '01270000000UHZcAAO',//parentid = '0017000000PgOvrAAF'

);

inserth;

 

p.hybrid_account__c = h.id;

p.create_hybrid__c =

false;

 

updatep;

 

}

 

}

}

 

Here's the error message:

Error: Invalid Data.
Review all error messages below to correct your data.
Apex trigger CreateHybridAcct caused an unexpected exception, contact your administrator: CreateHybridAcct: execution of BeforeUpdate caused by: System.DmlException: Update failed. First exception on row 0 with id 0067000000LJK3FAAX; first error: SELF_REFERENCE_FROM_TRIGGER, Object (id = 0067000000LJK3F) is currently in trigger CreateHybridAcct, therefore it cannot recursively update itself: []: Trigger.CreateHybridAcct: line 25, column 5
 
 
What can I do to get around this error message?  Inserting the new account does me no good if I can't tie it back to the opportunity.
 
Thanks!
  • September 26, 2011
  • Like
  • 0

I'm trying to deploy a pretty simple trigger into production.  It works fine in my sandbox, but when I deploy I get all kinds of error message on line 4. 


Here's the trigger:

 

trigger AutoCltGroup on Account (before insert, before update) {

   Client_Groups__c CGU = [Select ID From Client_Groups__c  Where Name='UNGROUPED' limit 1];
   client_groups__c CG996 = [Select ID From Client_Groups__c where Name='RPM996' limit 1];
   Client_Groups__c CG997 = [Select ID From Client_Groups__c where Name='RPM997' limit 1];

    
 for (Account a : Trigger.new) {
    if(a.cmr_number__c == '996')

{
      a.Client_Group__c =CG996.id;

    } 

 

    if(a.cmr_number__c == '997')

{
      a.Client_Group__c =CG997.id;

    } 


    if(a.Client_Group__c==null && a.cmr_number__c != '996' && a.cmr_number__c != '997')

{
      a.Client_Group__c =CGu.id;

    } 
}

 

 

}

 

 

Here's the error I'm getting:

Failure Message: "System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, AutoCltGroup: execution of BeforeInsert caused by: System.QueryException: List has no rows for assignment to SObject Trigger.AutoCltGroup: line 4, column 29: []", Failure Stack Trace: "Class.Accoun...


 

I would appreciate any help you can give me with this one.

 

Thanks!

  • September 26, 2011
  • Like
  • 0

I have a custom object called Email_Draft__c which is meant to replace SFDC standard email functionality.  It is just about completed, but I cannot figure out how to add attachments. 

 

I have an apex class which takes information from this custom object and sends an email, but I need to edit the class to pull in files that might be in the Notes & Attachments section of my custom object.  I also have a related object called VPL__c.  If there are files attached to that related object, I need those to be attached to the email as well. 

 

I've tried several options with no luck.  I would really appreciate any help you can give me with this.

 

I'm sure I need to create a new list of attachments and add the Email_Draft__c & VPL__c attachments to that list, but I can't even seem to get that to work.

 

Here is the class I'm using:

 

public class EmailDraft
{
private Email_Draft__c ed;
public EmailDraft(ApexPages.StandardController controller)
{
this.ed=(Email_Draft__c)controller.getRecord();
}

public PageReference SendEmail()
{
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();

if(ed.introduction_contact__r.email != null){
String[] toAddresses = new String[] {ed.introduction_contact__r.email};
                  mail.setToAddresses(toAddresses);   
                  }

 

if(ed.send_cc_contact__r.email != null){
String[] ccAddresses = new String[] {ed.send_cc_contact__r.email};
                  mail.setCcAddresses(CcAddresses);   
                  }

if(ed.send_bcc_contact__r.email != null){
String[] bccAddresses = new String[] {ed.send_bcc_contact__r.email};
                  mail.setbCcAddresses(bCcAddresses);   
                  }


    
mail.setOrgWideEmailAddressId('0D2F0000000CbiO');
mail.setWhatId(ed.id);
mail.setTemplateId('00XF0000001KOXA');
mail.settargetobjectid(ed.send_to_contact__r.id);

Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });

ed.approval_status__c = 'Approved & Sent';
update ed;

     PageReference next = new PageReference('https://na10.salesforce.com/a0s?fcf=00BF0000006XuMw');
          next.setRedirect(true);
 
     return next;

}
}

I have a situation where I need to report on two child objects on Accounts.

 

Is it possible to copy all the values of a related list as a text string and paste into a text field on the parent object?

 

For example, Commitment object has a lookup relationship to Accounts.  So I want to create a field on Accounts called Commitment list that looks like this:

 

Commitment Name 1 - Commit. 1 $ amount;

Commitment Name 2 - Commit 2 $ ammount;

Commitment Name 3 - Commit 3 $ ammount;

etc

 

Where commitment name and $ amount are two fields on each related list record.

 

I was thinking I could use a trigger that's fired when a related list is added, deleted, or edited to update the text field.  I just don't know how to convert the list to a text string in the trigger.

 

Any ideas how I can do this?  This is a very urgent need for my org.

 

Thanks again!

I have a custom object called Commitments that is a child object to accounts (master-detail).  I need to send a mass email to all contacts that have a certain field checked.  The mass email should contain information from the account with the account's related list for Commitments.

 

I know I cna use a visualforce email template to pull in related lists, but you can't send a mass email with a visualforce template.

 

Is there any other way I can accomplish this in SFDC?  This is a very urgent problem we are facing and have not been able to find a good solution.

 

I am open to ANY suggestions you can give me.

 

Thanks so much!!

I created an apex class for sending outbound emails on a custom objec.t  The class is supposed to referenced a visualforce page rendered as pdf and attach it to the email.

 

I created the visualforce page and the pdf renders correctly when I view it in salesforce.com.  But when I send the email with the pdf attached, the pdf shows up as an attachment, but it is completely blank.

 

I think this has something to do with the apex class not passing the correct id to the VF page, but I'm not sure.  Any idea why this isn't working? 

 

 

public class EmailDraft
{

private Email_Draft__c ed;
public EmailDraft(ApexPages.StandardController controller)
{
this.ed=(Email_Draft__c)controller.getRecord();
}

public PageReference SendEmail()
{

// Reference the attachment page, pass in the account ID  
    
        PageReference pdf =  Page.VPL_Attach;
        pdf.getParameters().put('id',(String)ed.Value_Payload__r.id);
        pdf.setRedirect(true);

        // Take the PDF content 
   
        Blob b = pdf.getContent();

        // Create the email attachment 
   
        Messaging.EmailFileAttachment efa = new Messaging.EmailFileAttachment();
        efa.setFileName('attachment.pdf');
        efa.setBody(b);


Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
String[] toAddresses = new String[] {ed.send_to_contact__r.email};
IF(ed.introduction_contact__r.email != null) {
toAddresses.add(ed.introduction_contact__r.email);
}
mail.setToAddresses(toAddresses);
if(ed.send_cc_contact__r.email != null){
String[] ccAddresses = new String[] {ed.send_cc_contact__r.email};
                  mail.setCcAddresses(CcAddresses);   
                  }
mail.setHTMLBody(ed.email_body__c);
mail.setSubject(ed.subject__c);
mail.setFileAttachments(new Messaging.EmailFileAttachment[] {efa});

Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });


ed.approval_status__c = 'Approved & Sent';
update ed;

     PageReference next = new PageReference('/apex/email_draft_detail?id='+ed.id);
          next.setRedirect(true);
 
     return next;
 }    

}

I have a trigger on the Account object that is supposed to populate the Parent Account during Lead Conversion.  The trigger works fine for that purpose.  When a lead is converted, the Parent Account populates.

 

However, when someone creates an account (without going through the lead process) and populates the parent account, the parent account goes away when that person hits save.  That person has to then update the account again with the parent account information to get the parent account to stay populated.

 

I thought my trigger would only affect accounts created from lead conversion.  I've copied the code below.  Any ideas how I can correct this issue?

 

 

trigger populateParentAccount on Account (before Insert){
  List<Lead> convertedLeads=[SELECT Id, ConvertedAccountID, Parent_Account__c
    FROM Lead WHERE IsConverted=True AND ConvertedAccountId IN :trigger.new];
      Map<ID,ID> acctParentMap=new Map<ID,ID>();
        for (lead l: convertedleads){
            acctParentMap.put(l.ConvertedAccountId,l.Parent_Account__c);
              }
                for (account a:trigger.new){
                    if (acctParentMap.containsKey(a.Id)){
                          a.ParentId=acctParentMap.get(a.Id);
                              }  }}

 

 

Thanks so much!!

Brandi

  • September 03, 2010
  • Like
  • 1

I'm trying to create a custom clone button on opportunity that will clone the current opportunity and populate the current opportunity id in a lookup field on the new opportunity. Then if Opp2 is cloned, the id for Opp2 should populate in the lookup field on the new Opp3.

 

It works great when the original opportunity is cloned.  However, when I clone the 2nd Opportunity (Opp2) and create Opp3, the lookup field on Opp3 shows the original Opportunity, instead of Opp2.  I cannot figure out why it's doing this.  Any ideas how I can fix?

 

Opp1 - Clone to create Opp2 (lookup should show Opp1)

Opp2 - Clone to create Opp3 (lookup should show Opp2, but shows Opp1)

 

Here's my button code.  Can anyone see what I'm doing wrong?

 

/{!Opportunity.Id}/e?clone=1&retURL=%2F006S0000006odYS&CF00NS0000001D9ZZ__lkid={!Opportunity.Id}&CF00NS0000001D9ZZ={!Opportunity.Name}&00NS0000001D93x=0 

I need a second set of eyes on this trigger I'm trying to build.  I don't have a lot of experience with triggers so I found one I'm trying to modify to my purposes.

 

On our opportunity object, if a user needs to make changes after it's been sold, they have to clone the record and start over, instead of editing.  I have a checkbox field called Superceded that should be checked on the original opportunity after it's cloned (this is what I'm trying to accomplish with my trigger).

 

I also have a lookup field for the newly clonsed record that will show the parent or original opportunity called Previous_Version__c.

 

I'm trying to create a trigger that will fire after insert on new opportunities only if the Previous_Version__c field is populated.  The trigger should update the opportunity in the Previous_Version__c lookup field and check the Superceded__c checbox on that parent record.

 

Here is what I've got so far:

 


trigger UpdatePreviousOpp on Opportunity (after insert){
 
Opportunity[] opp;
opp = Trigger.new;
 
set<Id> prevoppIds = new Set <ID>();
 
for (Opportunity op : opp) {
      if(opp.previous_version__c != null) {
         prevoppIds.add(op.previous_version__c);
    }
 
Map<ID, Opportunity> proppsToUpdate = new Map<ID, Opportunity> (
    [select Id, supercedure__c from Opportunity
    where Id in :prevoppIds]);

 
List<Opportunity> preoppUpd = new List<Opportunity>{};
 
for (Opportunity opp : preoppsToUpdate.values()) {
    opp.supercedure__c = true;
    update opp;
    preoppUpd.add(opp);
}


if (preoppUpd != null && !preoppUpd.isEmpty())
Database.update(preoppUpd);

}
}

 

Here is the message I'm getting.  Any idea how I can get this to work?

 

Error: Compile Error: Initial term of field expression must be a concrete SObject: LIST<Opportunity> at line 9 column 10

 

 

 

I have an account trigger that has always worked fine with no problems, but today when I was doing a mass insert / update of records, I kept getting an error message:

 

Apex script unhandled trigger exception by user/organization: 00570000001Frz1/00D700000009SRz

 

AutoCltGroup: execution of BeforeInsert

 

caused by: System.DmlException: Insert failed. First exception on row 0 with id a0F70000009GrlXEAS; first error: INVALID_FIELD_FOR_INSERT_UPDATE, cannot specify Id in an insert call: [Id]

 

Trigger.AutoCltGroup: line 47, column 1

 

 

What do I need to change in my trigger code to prevent this type of error:

 

trigger AutoCltGroup on Account (before insert, before update) {

list <Client_Groups__c> CGs = new list <Client_Groups__c> ();
list <Client_Groups__c> CG996 = new list <Client_Groups__c> ();
list <Client_Groups__c> CG997 = new list <Client_Groups__c> ();

list <Account> P996 = new list <Account> ();
list <Account> P997 = new list <Account> ();
list <Account> A300 = new list <Account> ();
list <Account> A343 = new list <Account> ();
list <Client_Groups__c> NewCG = new list <Client_Groups__c> ();
list <Recordtype> CltRT = new list <Recordtype> ();

List<Account> Agency = new List <Account> {};

CGs = [Select ID From Client_Groups__c Where Name='UNGROUPED' limit 1];
CG996 = [Select ID From Client_Groups__c Where Name='RPM996' limit 1];
CG997 = [Select ID From Client_Groups__c Where Name='RPM997' limit 1];

P996 = [Select ID From Account Where Natl_Identifier__c='343-996-0' limit 1];
P997 = [Select ID From Account Where Natl_Identifier__c='300-997-0' limit 1];
A300 = [Select ID From Account Where Natl_Identifier__c='343-0-0' limit 1];
A343 = [Select ID From Account Where Natl_Identifier__c='300-0-0' limit 1];
CltRT = [Select ID From Recordtype Where Name='Client' limit 1];

for (Account a : trigger.new)
{
    if (a.cmr_number__c == '996' && CG996.size()>0)
    {
        a.Client_Group__c = CG996[0].id;
        a.ParentId = P996[0].id;
        a.Agency_Account__c = A343[0].id;
    }
   
    else if (a.cmr_number__c == '997' && CG997.size()>0)
    {   
        a.Client_Group__c = CG997[0].id;
        a.ParentId = P997[0].id;
        a.Agency_Account__c = A300[0].id;  
    }   

    else if (a.cmr_number__c != '997' && a.cmr_number__c != '996' && a.RecordTypeId == CltRT[0].id && a.Client_Group__c == null)
    {   
        NewCG.add
        (new Client_Groups__c
        (Name=a.client_name__c,Agency_Account__c = a.agency_account__r.id));
        insert NewCG;
       
        a.Client_Group__c = NewCG[0].id;  
    }   

    else if (a.cmr_number__c != '997' && a.cmr_number__c != '996' && a.Client_Group__c!= null)
    {   
        
    }
          
    else
        a.Client_Group__c = CGs[0].id;  
       
    }
}

I need help modifying a trigger I wrote.  The trigger is supposed to update the parent opportunity record everytime the child record, Media_Plan_History__c, is updated, which works correctly.  

 

I need to add a condition to the trigger so that the opportunity is only updated if a checkbox called Active__c is set to True on the Media_Plan_History__c record.  Where can I add this logic to the trigger?  I can't quite figure it out.

 

Thanks!

 

Here's my trigger:

 

trigger OppOwnerSH on Media_Plan_History__c (after update) {

 

Media_Plan_History__c[] shs;
shs = Trigger.new;

 

set<Id> oppIds = new Set <ID>();

 

for (Media_Plan_History__c sh : shs) {
    oppIds.add(sh.Opportunity__c);

 

Map<ID, Opportunity> oppsToUpdate = new Map<ID, Opportunity> (
    [select Id, Media_Planner_2__c from Opportunity
    where Id in :oppIds]);

 

List<Opportunity> oppUpd = new List<Opportunity>{};

 

for (Opportunity opp : oppsToUpdate.values()) {
    opp.media_planner_2__c = sh.media_planner_2__c;
    update opp;
    oppUpd.add(opp);

}

 

if (oppUpd != null && !oppUpd.isEmpty())
Database.update(oppUpd);
}
}

I need help with a simple trigger.  I have an object called Media_Plan_History, which is a child to the Opportunity object.  There can only be one active Media Plan History record per Opportunity.

 

Both objects have a lookup field called Media Planner.  I need a trigger that will fire when the Media Plan History record is updated that would update the Media Planner field on the parent opportunity record to match the Media Planner field on the Media History Plan.

 

so opp.Media_Planner__c = mph.Media_Planner__c

 

Here is what I have so far, but I'm missing something important because I keep getting error messages:

 

trigger OppOwnerSH on Media_Plan_History__c (after update) {

Media_Plan_History__c[] shs;
shs = Trigger.new;

set<Id> oppIds = new Set <ID>();

for (Media_Plan_History__c sh : shs) {
    oppIds.add(sh.Opportunity__c);

Map <ID, Media_Plan_History__c> shforOpps = new Map <ID, Media_Plan_History__c> (
    [select Id, opportunity__c, Media_Planner_2__c, Artist_2__c from Media_Plan_History__c
    where opportunity__c in :oppIds]);

Map<ID, Opportunity> oppsToUpdate = new Map<ID, Opportunity> (
    [select Id, Media_Planner_2__c, Artist_2__c from Opportunity
    where Id in :oppIds]);

for (Opportunity opp : oppsToUpdate) {
    opp.media_planner_2__c = sh.media_planner_2__c;
    update opp;
}}}

 

 

Here's the message I'm getting:

Error: Compile Error: Loop must iterate over a collection type: MAP<Id,Opportunity> at line 19 column 24

 

 

 

 

 

I would really appreciate some help with this one.  I'm stil pretty new to coding.  Thank you!!

I'm trying to write a trigger that updates the child records on an Opportunity when a formula field - Contract Status - shows the value Cancelled/Recalled.  I'm not trying to update the Contract Status field, I just referencing it so that the trigger only fires when it shows that one value.

 

Here's the trigger and error message.  I'm at a loss as to how to fix this.

 

trigger CancelSuppHistory on Opportunity (before update) {

If(Trigger.isUpdate){
    
     Set<ID> ids = new Set<ID>();
     list<Opportunity> updOpps =
     [SELECT Id,
                 (Select Id, opportunity__c, active_media_plan__c, active_art__c
                  from Media_Plan_History__r ) FROM Opportunity
                 WHERE Id in :ids];        
                
                 List<Media_Plan_History__c> SHToUpdate = new List<Media_Plan_History__c>();

         //Then loop through each parent object in 'updated parent
         for (Opportunity Opp : updOpps)
         {
             if(opp.contract_status__c = 'Cancelled/Recalled')
            
                //and loop thru each kid in the child set}
               for(Media_Plan_History__c sh : Opp.Media_Plan_History__r)
               {
                         ///update logic from above
                          if(sh.active_media_plan__c = TRUE)

{
       sh.active_media_plan__c =  FALSE;
      shToUpdate.add(sh);
}
                }
        }
       if( !shToUpdate.isEmpty)
       {
            update shToUpdate;
       }
}


}

 

 

Error: Compile Error: Field is not writeable: Opportunity.Contract_Status__c at line 17 column 17

 

I'm trying to create a trigger that will fire when an opportunity is updated with a checkbox "create_hybrid__c" checked.  The trigger should create a new account record and then update a field on the opportunity with the new account.

 

I can get the trigger to create the new account, but any criteria that references the opportunity is ignored.  I've highlighted those lines in red below.  Also, I specifically assign a record type in the trigger, but the account is created with a completely different record type.  I also tried to assign a parent account and that criteria was ignored.

 

Is there any way to modify the trigger below so that all the fields I've specified are populated correctly?  With this trigger, an account is created, the name, agency_id__c, cmr_numer__c, and assign_rpm_client__c are populated correctly, the record type is not correct, and the other fields I specified are just left blank.

 

trigger CreateHybridAcct on Opportunity (before update) {

 

List<Account> a = new List<Account>();

 

for (Opportunity p : Trigger.new){
    if (p.create_hybrid__c == True) {
   
    a.add (new Account(
            name = 'testtrigger',
            agency_id__c = '300',
            cmr_number__c = '997',
            client_name__c = p.account.name,
            hybrid_account__c = p.account.id,
            owner = p.owner,
            recordtypeid = '01270000000UHZcAAO',
            parentid = '0017000000PgOvrAAF',
            assign_rpm_client__c = TRUE
            ));
           
    insert a;
   
    //p.hybrid_account__c = h.id;
    p.create_hybrid__c = false;     
            
    }

}
}

I'm trying to create a trigger on Opportunities that will create a new account when a box on the opportunity is checked, then update a lookup field on that same opportunity with the newly created account.  I'm getting a self-reference error.

 

Here is the trigger:

 

trigger

CreateHybridAcct onOpportunity (beforeupdate) {

 

for

(Opportunity p : [SELECT ID, ACCOUNT.Name, ACCOUNT.ID, ACCOUNT.Client_Name__c, Create_Hybrid__c, Ownerid

 

FROM OPPORTUNITY WHERE ID in :Trigger.new]){

 

if(p.create_hybrid__c == True) {

 

Account h = newAccount(

name =

'testhybrid',

agency_id__c =

'300',

cmr_number__c =

'997',

client_name__c = p.account.name,

hybrid_account__c = p.account.id,

//owner = p.owner,

lead_converted_date__c = date.

today()

 

//recordtypeid = '01270000000UHZcAAO',//parentid = '0017000000PgOvrAAF'

);

inserth;

 

p.hybrid_account__c = h.id;

p.create_hybrid__c =

false;

 

updatep;

 

}

 

}

}

 

Here's the error message:

Error: Invalid Data.
Review all error messages below to correct your data.
Apex trigger CreateHybridAcct caused an unexpected exception, contact your administrator: CreateHybridAcct: execution of BeforeUpdate caused by: System.DmlException: Update failed. First exception on row 0 with id 0067000000LJK3FAAX; first error: SELF_REFERENCE_FROM_TRIGGER, Object (id = 0067000000LJK3F) is currently in trigger CreateHybridAcct, therefore it cannot recursively update itself: []: Trigger.CreateHybridAcct: line 25, column 5
 
 
What can I do to get around this error message?  Inserting the new account does me no good if I can't tie it back to the opportunity.
 
Thanks!
  • September 26, 2011
  • Like
  • 0

I'm trying to deploy a pretty simple trigger into production.  It works fine in my sandbox, but when I deploy I get all kinds of error message on line 4. 


Here's the trigger:

 

trigger AutoCltGroup on Account (before insert, before update) {

   Client_Groups__c CGU = [Select ID From Client_Groups__c  Where Name='UNGROUPED' limit 1];
   client_groups__c CG996 = [Select ID From Client_Groups__c where Name='RPM996' limit 1];
   Client_Groups__c CG997 = [Select ID From Client_Groups__c where Name='RPM997' limit 1];

    
 for (Account a : Trigger.new) {
    if(a.cmr_number__c == '996')

{
      a.Client_Group__c =CG996.id;

    } 

 

    if(a.cmr_number__c == '997')

{
      a.Client_Group__c =CG997.id;

    } 


    if(a.Client_Group__c==null && a.cmr_number__c != '996' && a.cmr_number__c != '997')

{
      a.Client_Group__c =CGu.id;

    } 
}

 

 

}

 

 

Here's the error I'm getting:

Failure Message: "System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, AutoCltGroup: execution of BeforeInsert caused by: System.QueryException: List has no rows for assignment to SObject Trigger.AutoCltGroup: line 4, column 29: []", Failure Stack Trace: "Class.Accoun...


 

I would appreciate any help you can give me with this one.

 

Thanks!

  • September 26, 2011
  • Like
  • 0

I have a situation where I need to report on two child objects on Accounts.

 

Is it possible to copy all the values of a related list as a text string and paste into a text field on the parent object?

 

For example, Commitment object has a lookup relationship to Accounts.  So I want to create a field on Accounts called Commitment list that looks like this:

 

Commitment Name 1 - Commit. 1 $ amount;

Commitment Name 2 - Commit 2 $ ammount;

Commitment Name 3 - Commit 3 $ ammount;

etc

 

Where commitment name and $ amount are two fields on each related list record.

 

I was thinking I could use a trigger that's fired when a related list is added, deleted, or edited to update the text field.  I just don't know how to convert the list to a text string in the trigger.

 

Any ideas how I can do this?  This is a very urgent need for my org.

 

Thanks again!

I created an apex class for sending outbound emails on a custom objec.t  The class is supposed to referenced a visualforce page rendered as pdf and attach it to the email.

 

I created the visualforce page and the pdf renders correctly when I view it in salesforce.com.  But when I send the email with the pdf attached, the pdf shows up as an attachment, but it is completely blank.

 

I think this has something to do with the apex class not passing the correct id to the VF page, but I'm not sure.  Any idea why this isn't working? 

 

 

public class EmailDraft
{

private Email_Draft__c ed;
public EmailDraft(ApexPages.StandardController controller)
{
this.ed=(Email_Draft__c)controller.getRecord();
}

public PageReference SendEmail()
{

// Reference the attachment page, pass in the account ID  
    
        PageReference pdf =  Page.VPL_Attach;
        pdf.getParameters().put('id',(String)ed.Value_Payload__r.id);
        pdf.setRedirect(true);

        // Take the PDF content 
   
        Blob b = pdf.getContent();

        // Create the email attachment 
   
        Messaging.EmailFileAttachment efa = new Messaging.EmailFileAttachment();
        efa.setFileName('attachment.pdf');
        efa.setBody(b);


Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
String[] toAddresses = new String[] {ed.send_to_contact__r.email};
IF(ed.introduction_contact__r.email != null) {
toAddresses.add(ed.introduction_contact__r.email);
}
mail.setToAddresses(toAddresses);
if(ed.send_cc_contact__r.email != null){
String[] ccAddresses = new String[] {ed.send_cc_contact__r.email};
                  mail.setCcAddresses(CcAddresses);   
                  }
mail.setHTMLBody(ed.email_body__c);
mail.setSubject(ed.subject__c);
mail.setFileAttachments(new Messaging.EmailFileAttachment[] {efa});

Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });


ed.approval_status__c = 'Approved & Sent';
update ed;

     PageReference next = new PageReference('/apex/email_draft_detail?id='+ed.id);
          next.setRedirect(true);
 
     return next;
 }    

}

I have a custom object called Email Drafts and I have an apex class that will send an outbound email out to specific contacts based on information on the email drafts object.

 

I have two questions I need help on:

 

1.)  If there is an attachment on the email drafts object (notes & attachments section), is there any way to specify in my apex class that the email needs to include that attachment as well?  The only documentation I can find about attachments is about creating a pdf from a visualforce page and attaching.  I need images and documents already in SFDC to be attached to my email.

 

2.) I need to modify this code to redirect the user to another visualforce page after the email is sent and update a status field to Email Sent.  I cannot figure out how to do this.  I keep getting error messages when I add a pagereference to the class.

 

Here is my class and the error message I've been getting.  I would really appreciate any help you can give me on it.

 

public class EmailDraft
{
private Email_Draft__c ed;
public EmailDraft(ApexPages.StandardController controller)
{
this.ed=(Email_Draft__c)controller.getRecord();
}

public void SendEmail()
{
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
String[] toAddresses = new String[] {ed.send_to_contact__r.email};
IF(ed.introduction_contact__r.email != null) {
toAddresses.add(ed.introduction_contact__r.email);
}
mail.setToAddresses(toAddresses);
if(ed.send_cc_contact__r.email != null){
String[] ccAddresses = new String[] {ed.send_cc_contact__r.email};
                  mail.setCcAddresses(CcAddresses);   
                  }
    
mail.setOrgWideEmailAddressId('0D2F0000000CbiO');
mail.setHTMLBody(ed.email_body__c);
mail.setSubject(ed.subject__c);

Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });

     update ed;
}
}

 

 

Error: Compile Error: Void method must not return a value at line 33 column 1 

 

 

I have a visualforce page whose standard controller is Contract.  It contains input fields from both the contract record and a related opportunity record (opportunity__c lookup field).

 

I need a controller extension to override the standard save function and update both the contract and the opportunity records. 

 

Here is what I have so far, but I can't figure out how to reference the related opportunity object so that both records are saved.

 

Please help!!  Thank you!

 

 

public class ContractSaveMKTG{
    ApexPages.StandardController controller;
           
public ContractSaveMKTG(ApexPages.StandardController con){
                            controller = con;
                                                       
                                                 }                                  
  public PageReference save() {
           Contract cnt = (Contract)controller.getRecord();
           Opportunity Opp = cnt.opportunity__r.id;
           Opp.save();               
           controller.save();                      
           
            return cnt;
            }}

 

 

 

Visualforce Page:

 

<apex:page standardController="Contract" showHeader="true" sidebar="false">
<apex:form >
<apex:pageBlock >
<apex:pageBlockButtons >
<apex:commandButton action="{!save}" value="Save"/>
<apex:commandButton action="{!cancel}" value="Cancel"/>
</apex:pageBlockButtons>
<apex:pageblockSection >
<apex:inputField value="{!contract.opportunity__r.RPM_As_Sold__c}"/> 

/*Need this field saved to the related opportunity record and the others saved to the contract record*/
<apex:inputField value="{!contract.Distribution__c}"/>
<apex:inputField value="{!contract.Margin_Dollars__c}"/>
<apex:inputField value="{!contract.Average_Ad_Size__c}"/>
<apex:inputField value="{!contract.Margin_Percent__c}"/>
</apex:pageblockSection>
</apex:pageBlock>
</apex:form>
</apex:page>

I wrote a simple apex class that should send an outbound email when a button is clicked.  This is on a custom object called Email_Draft__c.  I need the To address to be populated from a contact record listed in a custom lookup field called Send_to_Contact__c.

 

I was able to create the class with no errors, but when I test the button I get the following error message:

SendEmail failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING, Missing target address (target, to, cc, bcc): []

 

 

Here is the actual apex class I'm trying to use.  I did set a target value and ensured that the contact I chose has an email address populated.  What do I need to do to correct this class?

 

Thanks!

 

public class EmailDraft
{
private Email_Draft__c ed;
public EmailDraft(ApexPages.StandardController controller)
{
this.ed=(Email_Draft__c)controller.getRecord();
}

public void SendEmail()
{
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
/*Create an instance of SingleEmailMessage Object*/
mail.setTargetObjectId(ed.Send_to_Contact__r.Id);
/*Setting the recipient as the Contact mentioned in the Id*/
mail.setHTMLBody(ed.email_body__c);
/*Setting the html body as the rich text body field on email draft*/
mail.setSubject(ed.subject__c);
/*Setting the subject of the email to the subject field on email draft*/
mail.setWhatid(ed.id);
/*Setting the whatid of the email to the email draft record*/

Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
/*Sending Email*/
}
}

Our accounts object has 2 related lists (contacts & commitments).  I need to send an email to a certain list of contacts where the email references data from the contact's Account record and displays the account's related list for commitments.

 

If I change the relatedToType to account, I no longer get the error message, but when I send the template from a contact record, it doesn't populate.  Seems what I'm looking for should be easy to do, but I cannot get it to work.  Any ideas???

 

I keep getting the following error message:

Error: Aggregate Relationship is used in an unsupported complex expression containing 'Account.r00na00000035kqema2__r' 

 

Here is the visualforce email template I'm trying to use:

 

<messaging:emailTemplate subject="Commitments" recipientType="Contact" relatedToType="contact">

<messaging:htmlEmailBody >
 <html>
        <body>

LP Commitments for the
<apex:outputText value="{!relatedto.account}" escape="false"/>

<table border="2" width="100%">
                 <tr >
                     <th>Internal Fund</th><th>Amount</th>
                  </tr>
<apex:repeat var="cx" value="{!relatedTo.account.commitments__r}">
       <tr>
           <td>{!cx.Internal_Fund__c}</td>
           <td>{!cx.Commitment__c}</td>
       </tr>
    </apex:repeat>
    </table><br></br>

</body></html>
</messaging:htmlEmailBody>

I have an email service that creates a new record in a custom object called Equests.  I need to somehow assign a value for a date field on that newly created custom record.  I was hoping to have the sender would add the due date at the very beginning of the email body and then have the apex class for the email service pull that first part of the email body to populate the due date field.

 

Here is the code I have so far:

 

global class myEquestsHandler_BrandiT implements Messaging.InboundEmailHandler {
      global Messaging.InboundEmailResult handleInboundEmail(Messaging.InboundEmail email, Messaging.InboundEnvelope envelope) {
          Messaging.InboundEmailResult result = new Messaging.InboundEmailresult();
         
          equests__c q = new Equests__c();
          q.name = email.subject;
          q.Email_Body__c = email.plaintextbody;
          q.sent_email_address__c = envelope.fromaddress;
          q.assigned_to__c = 'Brandi Tanyaviriya';
          q.due_date__c = email.plaintextbody.substring(0,11);
          insert q;
         
          System.debug('====> Created equest '+equests__c.Id);
         
          if (email.binaryAttachments != null && email.binaryAttachments.size() > 0) {
      for (integer i = 0 ; i < email.binaryAttachments.size() ; i++) {
        Attachment attachment = new Attachment();
        attachment.ParentId = q.id;
        attachment.Name = email.binaryAttachments[i].filename;
        attachment.Body = email.binaryAttachments[i].body;
        attachment.ContentType = 'image/equest';
        insert attachment;
      }
          }
               return result;
      }
  }

 

 

Here is the message I'm getting:

 

Error: Compile Error: Illegal assignment from String to Date at line 10 column 11 

 

 

I know I'm getting the message because I need to use the ValueOf method instead of IndexOf, but I'm not sure how to get it to work.  I've never had to use these methods before.

 

Please help!!

 

Thank you!