• SFAdmin5
  • SMARTIE
  • 575 Points
  • Member since 2011

  • Chatter
    Feed
  • 22
    Best Answers
  • 1
    Likes Received
  • 0
    Likes Given
  • 39
    Questions
  • 182
    Replies

Hi Everyone,

 

Can someone please help.

 

I have a custom object called Student and has associated tasks with it. 

 

when a student is not active, I want all the tasks to be automatically marked as completed. can someone please help with the trigger and test class.

 

Many many thanks in advance.

Hi,

 

We have a trigger which submits an oportunity automatically for approval if the 'Stage' is changed to either 'Won' or 'Lost' from some other stage status.

This part of the trigger works fine.

 

What we would like to implement as well is that when an opportunity is entered with the Stage set to 'Lost' (or 'Won') directly the submission to approval should also be triggered. So on creation the trigger should check if Stage equals 'Won' or 'Lost'

 

I am not sure how to write the IF statement for this instance.

It would need to include something like the ISNEW( ) function which however is only available in formulas.

 

Ideally if possible both functionalities, the existing and the check on record entry would be dealt with in one trigger.

 

Any help is appreciated!

Many thanks...

 

 

Trigger OpportunitySubmitForOrderListApproval on Opportunity (after update) {
 
    for(Integer i = 0; i < Trigger.new.size(); i++) 
    
     {
  if((Trigger.new[i].StageName == 'Won' && Trigger.old[i].StageName <> 'Won') ||

     (Trigger.new[i].StageName == 'Lost' && Trigger.old[i].StageName <> 'Lost'))

        {
 
            Approval.ProcessSubmitRequest req = new Approval.ProcessSubmitRequest();
            req.setComments('Submitted for approval. Please approve.');
            req.setObjectId(Trigger.new[i].Id);
            Approval.ProcessResult result = Approval.process(req);
            System.assert(result.isSuccess());  
 
        }
       
    }
 }

 

I have a situation when ever I insert a record a work flow fires and creates two tasks. What my question is... If I'm asked to insert those records using a data loader will workflow also fires then?  Cos right now for testing purpose I am manually entering the fields in the record and saving.. Just wanted to know if it works for bulk uploads. I tried doing one record using dataloader and it fired. But Just wanted to confirm that with 100 records

I have this trigger defined:

 

trigger convertLeadToImplementationOpportunity on Lead (before update) {
    for (Lead lead : Trigger.new){

      if(lead.Status == 'Qualified' && !lead.isConverted && lead.isApproved__c == true){
          Database.LeadConvert leadConvert = new database.LeadConvert();
          LeadStatus convertStatus = [SELECT Id, MasterLabel FROM LeadStatus WHERE IsConverted=true LIMIT 1];

          leadConvert.setConvertedStatus(convertStatus.MasterLabel); // ("Closed - Converted");
          leadConvert.setLeadId(lead.id);

          Database.LeadConvertResult leadConvertResult = Database.convertLead(leadConvert);
          System.assert(leadConvertResult.isSuccess());
      }
    }
}

 

When I execute the main trigger code anonymously via the IDE, it succeeds.


I have this (failing) test defined for the trigger:

 

@isTest
privateclass tests {
static testMethod void approvedLeadShouldConvertToImplementationOpportunity() {

      Lead testLead = new Lead(FirstName='John', LastName='Smith', Status='Qualified');
      insert testLead;

      test.startTest();

       testlead.isApproved__c = true;
       update testlead;  //trigger convertLeadToImplementationOpportunity

       test.stopTest();

       Lead isConverted = [SELECT id, isConverted FROM Lead WHERE Id=:testlead.id];
       System.assert(isConverted.isConverted);    // fails - i.e. isConverted == false
    }
}

 

Can anyone please tell me why the assert is failing? I'm quite new to Apex, so forgive any obvious stupidity.


Thanks!

Adam Breen

 

 

 

I have recently created a trigger that validates that 3 LOOKUP Field related objects have completed status before allowing a user to complete a case the is being used for project management.

 

What I need to know is what is the benefit of using a Trigger and a Class Vs. just a trigger, if there is any?

 

Which is easier normally to do unit test on for code coverage?

 

Please let me know what you think.

 

Thank you,

Steve Laycock

I am rather new to apex and would greatly appreciate any help. I have 2 custom objects: Medical_Inquiry__c, Medical_Inquiry_Response__c

 

There is a lookup relationship from Medical_Inquiry_Response__c to Medical_Inquiry__c.  

 

I need a trigger that will update  

Medical_Inquiry__c.Reply_Status_btg__c

with

Medical_Inquiry_Response__c.Status__c

based on the lookup relationship whenever a Medical_Inquiry_Response__c is inserted or updated.

 

Thanks!

Steve

 

Hi All,

 

I have a schedule job of email alerts for task due date. It runs every day at 7.00am and checks for task over dues. If I created a record at 1.00pm with the overdue coondition satisfying then do I get a mail instantaneously or I get mail when the scheduled job run tomorrow at 7.00 and sees this as overdue and maile me?

Hello All, 

 

I am trying to write a test class for a trigger I created.

 

The trigger is a simple trigger:

trigger SD_Member_No_Contact_30_Days on Task (after update) {
for (Task t:System.Trigger.new)


{if (t.Subject == 'Lost Contact Follow Up Call' ){ 
    {if (t.IsClosed==True  && t.status<>'No More Calls This Cycle'  ){ 
    SD_Member__c SDM = New SD_Member__c (id=t.whatid, Lost_Contact_Follow_Up__c=True);
    Update SDM;
    }}}}
 
}

 When I write the test class, I only get 60% coverage:

@isTest
class TestClass_LostContact30Days {    
static testMethod void myUnitTest() {        
// TO DO: implement unit test       

// Create SD Member Record
SD_Member__c sd = New SD_Member__c(First_Name__c = 'John', 
                                   Last_Name__c = 'Smith', 
                                   Ins_ID_Member__c = '123456', 
                                   Ins_ID_Suscriber__c = '456789',
                                   address__c = '123 Main Stret', 
                                   city__c = 'Aster', 
                                   state__c = 'CT', 
                                   zip__c = '06001', 
                                   name = 'John Smith',
                                   Lost_Contact_Follow_Up__c =False);
insert sd;
                                 
// Test 1
Task o = new Task();
o.Subject = 'Lost Contact Follow Up Call'; //set the required fields
o.WhatId=sd.id;
o.Status='In Progress';
insert o;

o.Status='Complete';
update o;


}}

 With the explanation of:

 

trigger SD_Member_No_Contact_30_Days on Task (after update) {
for (Task t:System.Trigger.new)


{if (t.Subject == 'Lost Contact Follow Up Call' ){
{if (t.IsClosed==True && t.status<>'No More Calls This Cycle' ){
SD_Member__c SDM = New SD_Member__c (id=t.whatid, Lost_Contact_Follow_Up__c=True);
Update SDM;
}}}}

}

 

Any ideas?

 

Thanks Todd B.

 

Hello,

 

I have a trigger that fires on a custom object to update the associated Account record.  The trigger works fine when I make changes manaully, however, when I try to make a bulk change to records via the Dataloader, I get the following error message:

 

Scorecard2Account: execution of BeforeUpdate caused by: System.QueryException: List has more than 1 row for assignment to Sobject Trigger.Scorecard2Account: line 14, column 1

 

 

I know it's probably something pretty simple, but I can't figure it out.  Can anyone help?  My trigger code is below.  Thanks,

 

 

trigger Scorecard2Account on Client_Status_Scorecard__c (before insert, before update, before delete)
{
//Update Account with Scorecard name in lookup field

list<Account> L1 = new list<Account>();
set<Id> Ids = new Set <Id>();

if(trigger.isUpdate)
{
FOR(Client_Status_Scorecard__c css :trigger.new) {
Ids.add(css.Client_Name__c);
}

Account acct1 = [SELECT Id
FROM Account
WHERE Id IN :Ids];

for(Client_Status_Scorecard__c css1 : trigger.new)
{
acct1.Client_Status_Scorecard__c = css1.Id;
L1.add(acct1);
}
}
IF(trigger.isDelete)
{
FOR(Client_Status_Scorecard__c css :trigger.old) {
Ids.add(css.Client_Name__c);
}

Account acct1 = [SELECT Id
FROM Account
WHERE Id IN :Ids];

for(Client_Status_Scorecard__c css1 : trigger.old)
{
acct1.Client_Status_Scorecard__c = null;
L1.add(acct1);
}
}
IF(L1.size()>0)
Update L1;
}

  • November 13, 2012
  • Like
  • 0

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!! :-)

Hi,

 

I have a date field called "Schedule_Date__c".

 

I tried the below query:

 

select id, name from Opportunity_Division where Schedule_Date__c >= CURRENT_YEAR.

 

I am getting the error message "unexpected token: CURRENT_YEAR"

 

Please let me know what the issue is?

 

Thanks,

Babu.

  • November 12, 2012
  • Like
  • 0

I want to update a field on Lead when a task is created for  that lead .

 

What is the mistake i am doing ?

 

 

 

trigger LeadFollowUp on Task (after insert)
{
List<Lead> LeadsToUpdate = new List<Lead>();
for (Task t: Trigger.new)
{
if (t.subject<>'')
{
Lead l = new Lead(Id=t.WhoId);

l.Follow_up_done__c = true;
LeadsToUpdate.add(l);
}
}
try {
update LeadsToUpdate;
} catch (system.Dmlexception e) {
system.debug (e);
}
}

 

Thanks

Akhil

  • November 12, 2012
  • Like
  • 0

I'm having an issue with my test coverage.  I recently built a trigger that doesn't allow anyone except for Sys Admins to insert or delete certain types of opportunities.  The triggers work fine, I just cant get the code coverage on my delete part.  Since I the reps can't insert the records, I'm thinking that's where it's failing, but in my test code I am testing it so a system administrator create the opportunity and then the standard user is deleting it.  Not sure why it's not working.

 

@IsTest
private class TestTrgCannotDeleteAcctMgmtRenewal
{
    static testMethod void testDelete()
    {
      Profile p = [SELECT Id FROM Profile WHERE Name='System Administrator'];
      User u = new User(Alias = 'sysadmin', Email='saplingsysadmin@testorg.com',
      EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US',
      LocaleSidKey='en_US', ProfileId = p.Id,
      TimeZoneSidKey='America/Los_Angeles', UserName='saplingsysadmin@testorg.com');

      test.starttest();
      System.runAs(u) {
      
      try
           {
           Account a=new Account(Name='Test Account');
           insert a;

           Opportunity o = new Opportunity(Name='Test Opportunity',
           closedate=system.today(), stagename='Discovery',Type='Acct. Mgmt. Renewal',LeadSource = 'Marketing Mailer');
           insert o;
           delete o;
           }
           catch (Exception e)
           {
           system.debug('Error:'+e);

} 
         
        }
  test.stopTest();
      }


    static testMethod void testDeleteFail()
    {
      Profile p = [SELECT Id FROM Profile WHERE Name='Standard User'];
      User u1 = new User(Alias = 'standa', Email='saplingstandarduser@testorg.com',
      EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US',
      LocaleSidKey='en_US', ProfileId = p.Id,
      TimeZoneSidKey='America/Los_Angeles', UserName='saplingstandarduser@testorg.com');
      
      Profile p2 = [SELECT Id FROM Profile WHERE Name='System Administrator'];
      User u2 = new User(Alias = 'sysadmin', Email='saplingsysadmin@testorg.com',
      EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US',
      LocaleSidKey='en_US', ProfileId = p2.Id,
      TimeZoneSidKey='America/Los_Angeles', UserName='saplingsysadmin@testorg.com');

      test.starttest();
      System.runAs(u2) {
      
      try
           {
           Account a=new Account(Name='Test Account');
           insert a;

           Opportunity o = new Opportunity(Name='Test Opportunity',
           closedate=system.today(), stagename='Discovery',Type='Acct. Mgmt. Renewal',LeadSource = 'Marketing Mailer');
           System.runAs(u1){
           delete o;}
              // should throw an exception - the following assertion will cause an error if the code carries on
           }
           catch (Exception e)
           {
           system.debug('Error:'+e);

} 
         
        }
  test.stopTest();
      }
     
      
      static testMethod void testInsert()
    {
      Profile p = [SELECT Id FROM Profile WHERE Name='System Administrator'];
      User u = new User(Alias = 'sysadmin', Email='saplingsysadmin@testorg.com',
      EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US',
      LocaleSidKey='en_US', ProfileId = p.Id,
      TimeZoneSidKey='America/Los_Angeles', UserName='saplingsysadmin@testorg.com');

      test.starttest();
      System.runAs(u) {
      
      try
           {
           Account a=new Account(Name='Test Account');
           insert a;

           Opportunity o = new Opportunity(Name='Test Opportunity',
           closedate=system.today(), stagename='Discovery',Type='Acct. Mgmt. Renewal',LeadSource = 'Marketing Mailer');
           insert o;
           }
           catch (Exception e)
           {
           system.debug('Error:'+e);

} 
         
        }
  test.stopTest();
      }

    static testMethod void testInsertFail()
    {
      Profile p = [SELECT Id FROM Profile WHERE Name='Standard User'];
      User u1 = new User(Alias = 'standa', Email='saplingstandarduser@testorg.com',
      EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US',
      LocaleSidKey='en_US', ProfileId = p.Id,
      TimeZoneSidKey='America/Los_Angeles', UserName='saplingstandarduser@testorg.com');

      test.starttest();
      System.runAs(u1) {
      
      try
           {
           Account a=new Account(Name='Test Account');
           insert a;

           Opportunity o = new Opportunity(Name='Test Opportunity',
           closedate=system.today(), stagename='Discovery',Type='Acct. Mgmt. Renewal',LeadSource = 'Marketing Mailer');
           insert o;
              // should throw an exception - the following assertion will cause an error if the code carries on
           }
           catch (Exception e)
           {
           system.debug('Error:'+e);

} 
         
        }
  test.stopTest();
      }
      
}

 

 

 

Hello everyone.

   I am pretty sure that what I need to do is write a trigger to accomplish my goal, but I have not written one before and need some help with the code.  I will try to outline this as best I can, and any help is appreciated.

 

I have a parent Custom Object called Job__c

I have a child Custom Object called Bid__c

   On Bid__c I have a field called Status__c that is a picklist with the values "Awarded" and "Lost"

 

One Job__c can have 1 to many Bid__c

 

When one Bid__c Status__c is changed to "Awarded" I need for all remaining Bid__c Status__c to change from "Pending" to "Lost"

 

I have absolutely no idea how to accomplish this.  I have read through some of the posts about triggers in here, but I have never done anything with one before, and I am pretty lost.

 

Here is what I have so far, which is nothing, and I am already not sure if its right.  (I can't wait to get beat up on a Test Class) 

 

trigger updateBids on Bid__c(after update){
     for(Bid__c c : trigger.old) {

     }

}

 

Can someone please help me to fill in the missing blanks?


Thank you!

Hi

 can anybody help me?

  I have the following requirement. Please write a trigger for it

I have two objects Leave_Application__c and Leave__c 

Leave__c has Master Detail relationship with Leave_Application__c

There is a picklist field in Leave_Application__c  object named Status__c

Now whenever a Status__c field is updated to the value "Approved"  a record should be created in Leave__c object . Newly created record will have one field that is Leave_Application_No__c and that should be set to the trigger ID.

Hi

   Will the following trigger work ?can anybody will help me?

 

trigger tgrCounter on Mileage__c (after insert, after update) {

                List MilToupdate = new List();

                for(Mileage__c Mlg : Trigger.new){

                                Mlg.Counter__c = Mlg.Counter__c+1;

                                MilToupdate.add(Mlg);

                }

                update MilToupdate;

}

I have two objects: Opportunity and ProposalFlight__c. They are in a master-detail relationship (ProposalFlight__c being the child). I also have a picklist field on both called ApprovalStatus__c. After an update on certain types of Opportunities, I want the ApprovalStatus__c picklist on ProposalFlight__c to change to match that on Opportunity. I wrote the following trigger and it saves, but when it tries to execute if gives me this error message:

 

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 UpdatePFtoPending caused an unexpected exception, contact your administrator: UpdatePFtoPending: execution of AfterUpdate caused by: System.StringException: Invalid id: Approved: External entry point". 

 

Can anyone please explain to me what this error message means and any tips for how I can fix it? Thank you so much!

 

trigger UpdatePFtoPending on Opportunity (after update) {

//List of approved Master Terms Opportunities
List<ID> masterOpps = new List<ID> ();
    for (Opportunity opp : trigger.new){
    if (opp.VersionType__c=='Change Request'){
        masterOpps.add(opp.ApprovedPARENTOpportunity__c);}
        }

//List of Related Not Submitted Proposal Flights
List<ProposalFlight__c> pflights = [SELECT ID, ApprovalStatus__c, Opportunity__c
                                    FROM ProposalFlight__c
                                    WHERE Opportunity__c in:masterOpps AND ApprovalStatus__c  !='Approved'];
Map<id,ProposalFlight__c> mapofPFs = New Map<id, ProposalFlight__c>();

//Build map of Proposal Flights from List of IDs in trigger
    for(ProposalFlight__c pf : pflights)
    mapofPFs.put(pf.id,pf);

//for each record in this trigger
    for(Opportunity thiscropp :trigger.new){

//update approval status on Proposal Flight                                                                         
ProposalFlight__c thisPF = mapofPFs.get(thiscropp.ApprovalStatus__c);

    If(thiscropp.VersionType__c == 'Change Request'){
    thisPF.ApprovalStatus__c = thiscropp.ApprovalStatus__c;
    }}
    
    Update mapofPFs.values();                                    
                                         
}

 

So fairly new to the apex side of salesforce so hopefully this can even be done.

 

So we have a field called Title which is being used by two group. In salesforce we have it managed so depending on the record type you only see certain titles for the contact. Well our job board does not look at our logic rather it just shows all values in the title field on our job board.

 

So what i am trying to do is create a new title field that only has the 5 main titles we want displayed and have it push into our primary title field when the candidate is created from the job board.

 

i.e. title_2__c = MD >>>>>> when candidate created date is (Today) push title_2__c into Title__c so that

 

title_2__c = MD & Title__c = MD

 

Has anyone done this type of coding before. Or point me in the direction to figure this out...

 

Thanks...

Hi,


Where can I find Salesforce.com coding standards document?

 

Thanks,

So, I've got a couple of triggers that work well when working directly from tasks or events.  An issue has arisen though, where the triggers are causing this: System.ListException: List index out of bounds: 0 when someone tries to Convert a Lead.  Here is the offending code:

 

Id WhoIDCheck = trigger.new[0].WhoId;

List<Event> WhoNum = [SELECT Who.Type FROM Task WHERE WhoId = :WhoIDCheck];

 

The trigger is a Before Update trigger, I am thinking about converting the trigger to an After Update, but I really don't understand how the whole process of converting a lead works (what happens to the ID over the course of the process, it seems to be changed, but when?), so I don't know if that will work.  Any suggestions/help would be greatly appreciated.

  • November 07, 2012
  • Like
  • 0

What does the "-1" here mean, where leadCalls is a List:

 

(leadCalls.get(leadCalls.size() - 1)

I'm working on part of an account object trigger we've got and keep getting a compile error.  

 

issue is this line

 

                String rddTerritory = userToRddTerritory.get(account.BillingPostalCode);

 

trigger is below.  any ideas how to fix this?

 

 

    // ------------------------------------------------------------------------
    // RDD Territory processing
    // ------------------------------------------------------------------------

 if ((Trigger.isInsert || Trigger.isUpdate) && Trigger.isBefore) {
        
        List<Account> postalCodeAccountsToProcess = new List<Account>();
        List<Account> ownerAccountsToProcess = new List<Account>();
        Set<String> postalCodes = new Set<String>();
        Set<String> ownerIds = new Set<String>();
        
        Id accountRddRecordTypeId = CSUtils.getRecordTypeId('Account', 'RDD');
        
        for (Account account : Trigger.new) {
            if (account.BillingPostalCode != null && account.RecordTypeId != accountRddRecordTypeId) {
                if (Trigger.isInsert || (Trigger.isUpdate && Trigger.oldMap.get(account.Id).BillingPostalCode != account.BillingPostalCode)) {
                    postalCodeAccountsToProcess.add(account);
                    postalCodes.add(account.BillingPostalCode);
                }
            } else if (account.RecordTypeId == accountRddRecordTypeId) {
                if (Trigger.isInsert || (Trigger.isUpdate && Trigger.oldMap.get(account.Id).OwnerId != account.OwnerId)) {
                    ownerAccountsToProcess.add(account);
                    ownerIds.add(account.OwnerId);
                }
            }
        }

        if (postalCodeAccountsToProcess.size() > 0) {
            Map<String, RDD_Territory__c> postalCodeToRddTerritory = new Map<String, RDD_Territory__c>();
            for (RDD_Territory__c  rddTerritory : [select Zip_Code__c, Name from RDD_Territory__c where Zip_Code__c in :postalCodes]) {
                postalCodeToRddTerritory.put(rddTerritory.Zip_Code__c, rddTerritory);
            }
            
            for (Account account : postalCodeAccountsToProcess) {
                String rddTerritory = postalCodeToRddTerritory.get(account.BillingPostalCode);
                
                if (rddTerritory != null) {
                    account.RDD_Territory__c = rddTerritory;
                }
            }         
            
        }

        if (ownerAccountsToProcess.size() > 0) {
            Map<String, String> userToRddTerritory = new Map<String, String>();
            for (User  user : [select Id, RDD_Territory__c from User where Id in :ownerIds and RDD_Territory__c != null]) {
                userToRddTerritory.put(user.Id, user.RDD_Territory__c);
            }
            
            for (Account account : ownerAccountsToProcess) {
                String rddTerritory = userToRddTerritory.get(account.BillingPostalCode);

                if (rddTerritory != null) {
                    account.RDD_Territory__c = rddTerritory;
                }
            }
        }

    }

 

i was bulk testing this trigger and while it works in the ui i get this error:

 

"setParentFieldsFromChildTriggeronProgram: execution of BeforeInsert

caused by: System.ListException: Duplicate id in list: 006G000000JvcxjIAB

Trigger.setParentFieldsFromChildTriggeronProgram: line 27, column 1"

 

Here's the trigger.  

trigger setParentFieldsFromChildTriggeronProgram on Program__c (before insert, before update) 
{              
     List<Opportunity> oppList = new List<Opportunity>();
     Set<id> Ids = new Set<id>();
     for (Program__c prgm : Trigger.new) {
         Ids.add(prgm.Opportunity__c);
        }
     
     Map<id,Opportunity> oppMap = new Map<id,Opportunity>([Select Id,Product_Group__c,Product_Area__c,Product_Family__c,Product_Family_Child__c from Opportunity Where Id in :Ids]);  
     
     for (Program__c prgm : Trigger.new) 
     {
                 Opportunity o = oppMap.get(prgm.Opportunity__c);
                 o.Product_Group__c = prgm.Product_Group__c;
                 o.Product_Area__c = prgm.Product_Area__c;
                 o.Product_Family__c = prgm.Product_Family__c;
                 o.Product_Family_Child__c = prgm.Product_Family_Child__c;
                 oppList.add(o);
     }
                 update oppList;
     
}

 

We have developed an app and have a salesforce instance.

 

Will it require cyberarc access/credentials to make calls to the Salesforce api service?

Trying to figure out how to write test classes.

 

Gota simple one that just inserts a user record, then checks a list of collaborationgroupmember records to see if that inserted user record is assigned to a specific group.

 

When I run this test I get the following error.  Looke like my list is empty but not sure why.

 

"System.AssertException: Assertion Failed: Expected: 1, Actual: 0"

 

He

@isTest
private class Test_UserTrigger2 {

static testMethod void testChatterAddGroup (){
        Profile profile = [select Id from Profile where name = 'Standard User'];
        User u = new User();
            
                          u.LastName = 'TestLast45';
                          u.FirstName = 'TestFirst45';
                          u.Alias = 'Stest45';
                          u.Email = 'test45@test.com';
                          u.EmailEncodingKey = 'UTF-8';
                          u.LanguageLocaleKey = 'en_US';
                          u.LocaleSidKey = 'en_US';
                          u.CommunityNickname = 'Test45';
                          u.Primary_User_Location__c = 'Waltham';
                          u.TimeZoneSidKey = 'America/Los_Angeles';
                          u.ProfileId= profile.Id;
                          u.Username = 'rosstesterx1234@constantcontact.com';
                          

        test.startTest();        
        insert u;        
        test.stopTest();
        
        List<CollaborationGroupMember> cgm = [SELECT id FROM CollaborationGroupMember WHERE      CollaborationGroup.Name='Waltham' AND MemberId=: u.Id];
        System.assertequals(1,cgm.size());

    }
    
}

 

re's the test that results in that error:

 

 

I need to have Salesforce automatically send an email to the Primary Contact Role on an opportunity, when the opportunity is created only (not updated), when the created opportunity meets very specific criteria in 4 of its fields.

 

I can get this to work for one-off opps created in the UI with a combination of a trigger and a workflow rule with email alert, BUT, this is not a viable solution, because I'm hitting governor limits when opps are created in bulk.

 

Any code help that a dev can provide would be much appreciated.

 

Here are the requirements for this to work:

 

If:

An opportunity is created

 

And the following criteria are TRUE regarding that opportunity:

  • Opportunity Creator = “Salesforce Leads RT”
  • Opportunity Record Type = “Custom Services”
  • Opportunity field called Service_Type__c  = “Quick Start”
  • Opportunity field called Referring_Group__c = “In-Product Sale”

Then:

Send an email from Salesforce to the Contact Role on that opportunity listed as the Primary Contact on that opportunity

 

Note: the email should be sent using a custom template that is already created and saved in Salesforce with name “Test”.  If this is not possible and there is some other way to send the email subject/body, that is fine, as long as I can modify the subject/body content

I've got a trigger on account object that populates a field that counts and sums up the number of related accounts to the account being updated/inserted/deleted.  Pretty straightforward.

 

This trigger works but I need to know whether it would be considered bulkified.  If it's not, any suggestions on what ought to be changed to bulkify it would be much appreciated.

 

Here it is:

 

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



// ---------------------------------------------------------------
 // Active Managed & Unmanaged Paying Customers processing
 // ------------------------------------------------------------------

    if ((Trigger.isInsert || Trigger.isUpdate || Trigger.isDelete) && Trigger.isAfter) {    

         set<Id> AccountIds = new set<Id>();
 
             if(trigger.isInsert || trigger.isUpdate){
                 for(Account p : trigger.new){
                     AccountIds.add(p.Referring_Partner__c);
                 }
              }
 
             if(trigger.isDelete){
                for(Account  p : trigger.old){
                    AccountIds.add(p.Referring_Partner__c);
                 }
              }
 
          map<Id,Double> AccountMap1 = new map <Id,Double>();
 
              for(AggregateResult q : [select Referring_Partner__c,sum(Referring_Partner_Count__c)
                  from Account 
                  where Active_Products__c != null AND Managed_by_Partner__c !=null AND Referring_Partner__c IN :AccountIds 
                  group by Referring_Partner__c]){
                  
                  AccountMap1.put((Id)q.get('Referring_Partner__c'),(Double)q.get('expr0'));
               }
  
           map<Id,Double> AccountMap2 = new map <Id,Double>();
 
               for(AggregateResult q : [select Referring_Partner__c,sum(Referring_Partner_Count__c)
                   from Account where Active_Products__c != null AND Managed_by_Partner__c = false AND Referring_Partner__c IN :AccountIds 
                   group by Referring_Partner__c]){
          
                   AccountMap2.put((Id)q.get('Referring_Partner__c'),(Double)q.get('expr0'));
               }
 
           List <Account> AccountsToUpdate = new List<Account>();
 
               for(Account a : [Select Id, Active_Paying_M__c from Account where Id IN :AccountIds]){
   
                   Double Sum1 = AccountMap1.get(a.Id);
                   a.Active_Paying_M__c = Sum1 ;
                   Double Sum2 = AccountMap2.get(a.Id);
                   a.Active_Paying_U__c = Sum2;    
    
                   AccountsToUpdate.add(a);
                }
 
           
           update AccountsToUpdate ;
  
    }

}

 

Hi-

 

So I've got a trigger that works as intended (took me a week to write this thing, with help from the boards here, as I'm not a developer).

 

The trigger below works and the test class passes it at 95%.  The issue is that even though it's got high enough test coverage to go to prod, and even though I've used Demand Tools to insert thousands of records into a test environment where this code is live to try to hit governor limits, and I'm not hitting any limits or having any issues, I don't know for sure whether or not this trigger would be considered by a real developer as "bulkified".

 

Can someone let me know if this is a bulkified trigger, and if not, perhaps adjust the code or make some suggestions as to how I can change it to make is "bulkified".

 

Thanks a lot.

 

Trigger:

 

trigger CustomerUsage on Customer_Usage__c (before insert, before update, after insert, after update, after delete) {
   
    // ----------------------------------------------------------------
    // Partner First Gross Add & Most Recent Gross Add Processing
    // -----------------------------------------------------------

    if ((Trigger.isInsert || Trigger.isUpdate) && Trigger.isAfter) {    
     
      set<Id> AccountIds = new set<Id>();
        if(trigger.isInsert || trigger.isUpdate){    
          for(Customer_Usage__c p : trigger.new){      
              AccountIds.add(p.Account__c);
          }
        }
 
     map<Id,DateTime> AccountMap = new map <Id,Datetime>(); 
       for(Customer_Usage__c q : [select Id,First_Positive_Invoice_Date__c,Account__c
           from Customer_Usage__c 
           where Account__c IN :AccountIds  
           order by First_Positive_Invoice_Date__c asc limit 1]){       
           AccountMap.put(      
             (ID)q.get('Account__c'),
             (Datetime)q.get('First_Positive_Invoice_Date__c')
           );
       }
 
      List<String> tempLst=new List<String>();
      Map<String, String> accountid_partner_map=new Map<String, String>();
        for(Account a : [Select Id, Referring_Partner__c
            from Account
            where Id IN :AccountIds]){
    
            tempLst.add(a.Referring_Partner__c);
            accountid_partner_map.put(a.Referring_Partner__c, a.id);
        }

       List <Account> AccountsToUpdate = new List <Account>();
         for(Account a : [Select Id,Referring_Partner__c,Partner_First_Gross_Add__c,Partner_Most_Recent_Gross_Add__c
             from Account 
             where Id IN :tempLst]){
             Datetime FPID = AccountMap.get(accountid_partner_map.get(a.Id));
    
           if(a.Partner_First_Gross_Add__c==null && a.Partner_Most_Recent_Gross_Add__c ==null){            
              a.Partner_First_Gross_Add__c = FPID ;  
              a.Partner_Most_Recent_Gross_Add__c = FPID;           
           }else {           
           if((a.Partner_Most_Recent_Gross_Add__c == a.Partner_First_Gross_Add__c && a.Partner_Most_Recent_Gross_Add__c < FPID) ||   a.Partner_Most_Recent_Gross_Add__c < FPID )
              a.Partner_Most_Recent_Gross_Add__c = FPID ;
           }
              AccountsToUpdate.add(a);
              update AccountsToUpdate; 
         } 
    }
}

 

 

 

Test Class:

 

@isTest
private class Test_PFGA {

  static testMethod void Test_PFGA() {
  

        Account a = new Account ();
        a.Name = 'TEST_PartnerAccount';
        a.Partner_First_Gross_Add__c = null;
        a.Partner_Most_Recent_Gross_Add__c = null;


        insert a;
    
        System.assertEquals(
        null, 
        a.Partner_First_Gross_Add__c);
        
        System.assertEquals(
        null, 
        a.Partner_Most_Recent_Gross_Add__c );
    
    
        Account a2 = new Account ();
        a2.Name = 'TEST_SalesAccount';
        a2.Referring_Partner__c = a.Id;

        insert a2;

        Customer_Usage__c cu = new Customer_Usage__c();
        cu.Account__c = a2.Id;
        cu.First_Positive_Invoice_Date__c =  datetime.newInstance(2008, 12, 1);

        insert cu;

        System.assertEquals(
        cu.First_Positive_Invoice_Date__c,
        a.Partner_First_Gross_Add__c);
        
        System.assertEquals(
        a.Partner_First_Gross_Add__c, 
        a.Partner_Most_Recent_Gross_Add__c);
    
        Customer_Usage__c cu2 = new Customer_Usage__c();
        cu2.Account__c = a2.Id;
        cu2.First_Positive_Invoice_Date__c =  datetime.newInstance(2010, 12, 1);

        insert cu2;    
        
        System.assertEquals(
        cu2.First_Positive_Invoice_Date__c,
        a.Partner_First_Gross_Add__c);
    
    
  }
  

  
  
  

}

 

I've got a trigger that should just sum up the number of child records on a field in the parent.

 

Trigger below compiles but the aggregattion in the map doesn't seem to be working right.  Basically what should happen is that, anytime there is an account record  x of record type partner, any customer usage records created from accounts where the referrring partner is x should update the account field Active_Paying_M__c with that new add.

 

Example:

 

Partner = x

Sales account where referring partner is x = y 

Sales account where referring partner is x = r

customer usage record on y = z

customer usage record on r = p

 

If the above are true, the field value in Active_Paying_M__c on record x should be "2".  Trigger below keeps setting the value to 1 in testing.

 

Any ideas?  I suspect the issue is with the first map but not sure

 

trigger CustomerUsage on Customer_Usage__c (before insert, before update, after insert, after update, after delete) {

// ------------------------------------------------------
//test
// ------------------------------------------------------

if ((Trigger.isInsert || Trigger.isUpdate) && Trigger.isAfter) {    
     
set<Id> AccountIds = new set<Id>();
 
  if(trigger.isInsert || trigger.isUpdate){
    for(Customer_Usage__c p : trigger.new){
      AccountIds.add(p.Account__c);
    }
  }
 
  map<Id,Double> AccountMap = new map <Id,Double>();
 
  for(AggregateResult  q : [select Account__c,sum(FPID_Value__c)
    from Customer_Usage__c where Account__c IN :AccountIds group by Account__c ]){
      AccountMap.put(
      
      (ID)q.get('Account__c'),
      (Double)q.get('expr0')
      
      
      );
  }
 
//stage 1 - find the lookup records id's
List<String> tempLst=new List<String>();
Map<String, String> accountid_partner_map=new Map<String, String>();

for(Account a : [Select Id, Referring_Partner__c
        from Account
        where Id IN :AccountIds]){
    tempLst.add(a.Referring_Partner__c);
    accountid_partner_map.put(a.Referring_Partner__c, a.id);
}

//stage 2 - retreive the lookup records + update their dates.
List <Account> AccountsToUpdate = new List <Account>();
 
  for(Account a : [Select Id,Referring_Partner__c,Partner_Most_Recent_Gross_Add__c from Account where Id IN :tempLst]){
    Double FPID = AccountMap.get(accountid_partner_map.get(a.Id));
     
     a.Active_Paying_M__c = FPID ;
     
     
    
     AccountsToUpdate.add(a);
 
  update AccountsToUpdate;
 
  }
  
}
}

 

 

 

I've got a trigger on a custom object that is not working.

 

Here's how it should work:

 

A user goes into a standard sales-record type Account record.  User creates from that account a record on a custom object called Customer Usage.  Once that record is created the cu record is associated to the account with a simple lookup field to the account record to which it belongs.  What's important to know here is that the account object has a lookup field called Referring_Partner__c.  This lookup field is a lookup to the account object itself, and is used to hold the value of a partner-record type account name.

 

What I want my trigger to do is, when a customer usage record is created or updated with a value in its First Positive Invoice Date field (it's a datetime field), I want that datetime to populate in field on the related account record Partner First Gross Add field. 

 

The problem is that I want the trigger to update the Partner First Gross Add field on the account that is related to the account from which the customer usage record was created, in other words, the trigger should update the partner account record that is related to the sales account from which the cu record was created.

 

Example:

 

Account X = Partner Account record

Account Y = Sales Account record

Customer Usage Z = Customer Usage record

 

User creates a customer usage record called Z with Account__c field value of Y and First Positive Invoice Date of 6/2/2011.

 

Upon insert of Z, record X should be updated with a value of 6/2/2011 in the Partner First Gross Add field.

 

The trigger below does the above, but, what it does is update record Y with 6/2/2011 in the Partner First Gross Add field.  What I want the trigger to do is update record X with 6/2/2011 in the Partner First Gross Add field.

 

How do I do this?  Please help.  I've spent probably 15 hours on this and can't figure it out.

 

trigger CustomerUsage on Customer_Usage__c (before insert, before update, after insert, after update, after delete) {

//-----
// Account Updates Processing
//------

if ((Trigger.isInsert || Trigger.isUpdate || Trigger.isDelete) && Trigger.isAfter) {    
     
set<Id> AccountIds = new set<Id>();
 
  if(trigger.isInsert || trigger.isUpdate){
    for(Customer_Usage__c p : trigger.new){
      AccountIds.add(p.Account__c);
    }
  }
 
  if(trigger.isDelete){
    for(Customer_Usage__c p : trigger.old){
      AccountIds.add(p.Account__c);
    }
  }
 
  map<Id,DateTime> AccountMap = new map <Id,Datetime>();
 
  for(Customer_Usage__c q : [select Id,First_Positive_Invoice_Date__c
    from Customer_Usage__c where Account__r.Referring_Partner__c IN :AccountIds  order by First_Positive_Invoice_Date__c asc limit 1]){
      AccountMap.put(
      
      (ID)q.get('Account__c'),
      (Datetime)q.get('First_Positive_Invoice_Date__c')
      
      
      );
  }
 
  List <Account> AccountsToUpdate = new List <Account>();
 
  for(Account a : [Select Id,Referring_Partner__c,Partner_First_Gross_Add__c from Account where Id IN :AccountIds]){
    Datetime FPID = AccountMap.get(a.Referring_Partner__r.Id);
    a.Partner_First_Gross_Add__c = FPID ;
    AccountsToUpdate.add(a);
    

  }
 
  update AccountsToUpdate;



}

 

 

 

I've got a map in a trigger on a custom object.  Custom object is called Customer_Usage__c, and Account__c is a lookup field on that object to the standard Account object.

 

AccountMap.put((ID)q.get('Account__c')

 

so that is putting in the ID of the account record to which that customer usage record belongs

 

Can I access a related record on the  Account object here?  In other words I want something like

 

AccountMap.put((ID)q.get('Account__r.Referring_Partner__c')

 

where Referring_Partner__c is a a lookup field on the account object itself.  So I'd be putting in the ID of the value in the referring partner on the account to which the customer usage record belongs.

 

Trigger saves but throws an error in testing saying the field does not exist.  Is this syntax error or am I doing something dumb?

 

 

 

I've got a trigger that inserts a new sObject record on a custom object when another custom object is created.  It works but the only thing that does not work is populating the Account lookup field.  Here's the code.  The problem has got to be around the line                  "newAN.Account__c = insertedCSBI.Account__c;"

 

I know this is an Id field.  Not sure if I need to be dealing with apex map or set or both here.  All I know is that this trigger creates a new record successfully, but that new record is not associating the new record to an Account.

 

Any ideas?

 

trigger CustomServicesBillingInvoice on Custom_Services_Billing_Invoice__c (after insert, before update, after update) {

    ///Account Note Insert for new Billing Records
    
    if (Trigger.isInsert && Trigger.isAfter) {
           
            //Declare a new List of type Account_Note__c.  Name of List is newANlist 
            List<Account_Note__c> newANlist = new List<Account_Note__c>();     
            
                 //Loop over all of the Custom_Services_Billing_Invoice__c values in Trigger.new
                 for(Custom_Services_Billing_Invoice__c insertedCSBI:Trigger.new){
        
                 //Declare a new Account_Note__c and name it newAN 
                 Account_Note__c newAN = new Account_Note__c();
    
                 //Assign the Custom_Services_Billing_Invoice__c record's values to the fields on the newAN record
                 newAN.Account__c = insertedCSBI.Account__c;
                 newAN.Note__c = insertedCSBI.Billing_Notes__c;
                 newAN.Note_Function__c  = 'Finance';
                 newAN.Note_Status__c = 'Resolved';

          
                 //Add newAN to newANlist for any insertedCSBI records that have some text in the Billing_Notes__c field. 
                 //Exclude CSBI records that are null for this field
                 if(insertedCSBI.Billing_Notes__c !=null){
                 newANlist.add(newAN);
                 }
                 }
    
                 //Insert newANlist 
                 Database.insert(newANlist);

    }

}

 

I get 80% test coverage but want 100.  Any ideas how I can get this class to pass 100%.  Class below, followed by the 2 test methods.  The failure is on the execute method in the class.  Tests won't cover it and I can't figure out why

 

CLASS

global class deleteAccounts implements  Database.Batchable<sObject>, Schedulable {
String query = 'SELECT id from Account WHERE Name=test';
global deleteAccounts ()
{
}
  global void execute(SchedulableContext SC) {
      deleteAccounts x = new deleteAccounts(); 
      database.executebatch(x);
   }
global Database.QueryLocator start(Database.BatchableContext BC){
   return Database.getQueryLocator([SELECT id FROM Account WHERE Name ='test']);
}
global void execute(Database.BatchableContext BC, List<sObject> scope){
  delete scope;
}
global void finish(Database.BatchableContext BC){

 }}

 TEST METHODS:

public class TEST_deleteAccounts{
public static testMethod void testBatch() {

   List <Account> accns = new List<Account>();
      for(integer i = 0; i<200; i++){
         Account a = new Account(Name='test'+'i'); 
         accns.add(a);
      }
   
   insert accns;
   
   Test.StartTest();
   deleteAccounts  x = new deleteAccounts();
   ID batchprocessid = Database.executeBatch(x);
   Test.StopTest();

   System.AssertEquals(
           database.countquery('SELECT COUNT()'
              +' FROM Account WHERE Name=test'),
           0);  
   
   }
}
public class TEST_deleteAccountsschedjob{
public static testMethod void testBatch() {
   deleteAccounts a = new deleteAccounts();
   String sch = '0 0 23 * * ?';
  
   Test.startTest();
   Id jobId = System.schedule('a', sch, a);
  
   // Get the CronTrigger info prior to the run
CronTrigger cronTrigger1 = [SELECT Id, CronExpression, TimesTriggered, NextFireTime FROM CronTrigger WHERE Id = :jobId];

// Assert that the expressions are the same
System.assertEquals(sch, cronTrigger1.CronExpression);

// Assert that the cron job has not started
System.assertEquals(0, cronTrigger1.TimesTriggered);

   Test.stopTest(); // will execute the asynchronous Apex
  
   // Get the CronTrigger info prior to the run
CronTrigger cronTrigger_after = [SELECT Id, CronExpression, TimesTriggered, NextFireTime FROM CronTrigger WHERE Id = :jobId];

   // Assert that the cron job has run once
System.assertEquals(1, cronTrigger_after.TimesTriggered);
  }
}

 

can someone help me with a test class for the class below (scheduled apex job that works fine in testing...i just need test coverage for it)

 

global class deleteAccounts implements  Database.Batchable<sObject>, Schedulable {
String query = 'SELECT id from Account WHERE Name=test';
global deleteAccounts ()
{
}
  global void execute(SchedulableContext SC) {
      deleteAccounts x = new deleteAccounts(); 
      database.executebatch(x);
   }
global Database.QueryLocator start(Database.BatchableContext BC){
   return Database.getQueryLocator([SELECT id FROM Account WHERE Name ='test']);
}
global void execute(Database.BatchableContext BC, List<sObject> scope){
  delete scope;
}
global void finish(Database.BatchableContext BC){

 }}

 

Hi-

 

I've got a batch class that works the way I want it to here, but I can't get the schedulable class that I need to schedule this job to run to work.  The batch class works, but when I try to save the schedulable class, I can't and get this error "Constructor Not Defined".  Any idea what I need to do to fix this?

 

Batch class

global class deleteAccounts implements  Database.Batchable<sObject> {
global final string query;
global deleteAccounts (String q)
{
   query = q;
}
global Database.QueryLocator start(Database.BatchableContext BC){
   return Database.getQueryLocator([SELECT id FROM Account WHERE Name ='test']);
}
global void execute(Database.BatchableContext BC, List<sObject> scope){
  delete scope;
}
global void finish(Database.BatchableContext BC){
  // Get the ID of the AsyncApexJob representing this batch job  
  // from Database.BatchableContext.    
  // Query the AsyncApexJob object to retrieve the current job's information.  
 }}

 Schedulable class that won't save (I get Contructor Not Defined error):

 

global class scheduledBatchable implements Schedulable{
   global void execute(SchedulableContext sc) {
      deleteAccounts x = new deleteAccounts(); 
      database.executebatch(x);
   }
}

 Thanks!

I can get a text are long type field top display as an output field on a visualforce page, but for some reason, it doesn't display in an iframe within a webpage. 

 

has anyone seen this before?

 

here's the code:

 

<apex:outputPanel layout="none" >                                <h3>Cost</h3>                                {!listing.Pricing__c}                                                   
</apex:outputpanel><br></br>

 

I know there are a lot of autoconvert triggers out there for leads that flip it into an account, opp, and contact upon lead creation.  But...I need a trigger that autoconverts a lead (based on the value in one field) into JUST an opportunity, and assigns that opportunity to an existing account.

 

I know for these leads that come in, that there will ALWAYS be an account already in Salesforce.  So I just want the trigger to search contacts based on email address, and when a contact is found whose email matches the new lead email, autoconvert the lead to an opportunity, and assign it to the account to which that contact that was matched to the lead email belongs.

 

Any code help here is much appreciated.

 

Thanks

Anyone ever seen this before?  I've got a user attaching a photoshop file and word file to an email from SFDC, but Salesforce puts a .html extension onto the file when sent from Salesforce as an email attachment.  No idea what causes this or how to prevent it.

 

Anyone seen this before?

Hi-

 

Is there a simple trigger that will delete an opportunity record when it's created with 3 fields not filled in?  This is a workaround fix to a known code issue that would be a lot quicker than fixing the original problem.

 

All I need is a trigger that deletes an opp after it's created when the opp was created with no value in three fields.  Thanks

hi-

 

i have a custom button on accounts that creates a new opportunity.  i'm able to pre-populate a bunch of fields on the opp by modifying the button's code.  however, i can't seem to modify the button code so that the new opp record gets assigned by default to a specific user.

 

is this possible?  if so, what's the code?  or, is there something else I can do to set that.  I am currently using workflow to update the owner after record creation, but i'd like the owner to be set by default to a specific user before record save

Anyone ever seen this before?  I've got a user attaching a photoshop file and word file to an email from SFDC, but Salesforce puts a .html extension onto the file when sent from Salesforce as an email attachment.  No idea what causes this or how to prevent it.

 

Anyone seen this before?

i want to delete a child record when parent record is delete after a trigger fires........example plzzzzzzz

This is on the sandbox and I can't figure out why this trigger test isn't firing. All system debug get hit and have the correct data, System.debug('@@@ trgInsertNote');

 

trigger trgInsertNote on Note (after insert) {
    
    System.debug('@@@ trgInsertNote');
    BMCServiceDesk__Incident__c toUpdate = new BMCServiceDesk__Incident__c();
    
    for(Note n : Trigger.New){
        String nName = n.ParentId;
        String iName = Schema.getGlobalDescribe().get('BMCServiceDesk__Incident__c').getDescribe().getKeyPrefix();
        
        if ( nName.startsWith(iName) && !n.IsPrivate ) {
            
            toUpdate = [SELECT X3Ci_Last_Note__c FROM BMCServiceDesk__Incident__c WHERE Id = :nName][0];
            if ( n.Body == '' || n.body == null )
                toUpdate.X3Ci_Last_Note__c = n.Title;
            else
                toUpdate.X3Ci_Last_Note__c = n.Title + ': ' + n.Body;
        }
    }
    
    if ( toUpdate != null)
        update toUpdate;
}

 

@isTest(SeeAllData=true) 
public with sharing class TestTrgInsertNote{
    private static TestMethod void testInsertNoteMethod(){
        
        Profile cvProfile = [select id from profile where name = 'Standard User' limit 1];
        User usrCV = new User();
        usrCV.LastName='Test Client Value';
        usrCV.Username='dsfg@gmail.com23453245';
        usrCV.Alias='tesy07';
        usrCV.Email='sdfg@sdfg.com';
        usrCV.CommunityNickname='Test CV Contact';
        usrCV.TimeZoneSidKey='America/Los_Angeles';
        usrCV.localesidkey='en_US';
        usrCV.EmailEncodingKey='ISO-8859-1';
        usrCV.LanguageLocaleKey ='en_US';
        usrCV.ProfileId=cvProfile.id;
        usrCV.IsActive = true;
        Insert usrCV;
        System.debug('@@@ TestTrgInsertNote.usrCV: ' + usrCV);
        
        BMCServiceDesk__Incident__c testIncident = new BMCServiceDesk__Incident__c();
        testIncident.Subject__c = 'Test Incident';
        testIncident.BMCServiceDesk__FKClient__c = usrCV.Id;
        insert testIncident;
        System.debug('@@@ TestTrgInsertNote.testIncident: ' + testIncident);
        
        Note newNote = new Note(Title='Test title', Body='Test body', ParentId = testIncident.Id, IsPrivate = false);
        System.debug('@@@ TestTrgInsertNote.newNote: ' + newNote);
    }
}

 

  • December 31, 2013
  • Like
  • 0

Hi,
I need 2 custom button in Event object 1) Lock 2) Audit ( Unlock)
whenever the Event is create for account record type  event will be coped in all child records attachments in the form of PDF and name with event.<AccountRecordType>

When same record is updated, previous record must be lock and <audit> button should be populated. Event should be copied in child record in the form of PDF with version like Event.<account record type>.v1.1

 

PDF:

PDF file code is working properly. But it;s showing every field in the given object. But I need only 6 field Event in the object. How to filter these 6 field and I need 3 more from the other object how to add these fields please sagest me I need to submit today

In Event object 6 fields: 1) Subject 2) Description 3) CreatedBy 4) StartDateTime 5) EndDateTime 6) What
in  Portfolio__c object 3 fields 1) Suitability 2) DMS_Folder__c 3) DMS_Sub_Folder__c

 

-----------

Trigger:

------------

trigger AfterUpdateEventTrigger on Event(after insert, after update) {

 

    if(Trigger.isInsert){        

Set<ID> accountIdSet = new Set<ID>();

        for(Event e : Trigger.New){

            accountIdSet.add(e.WhatId);  

          }         Map<Id,List<Portfolio__c>> portfolioMap = new Map<Id,List<Portfolio__c>>();    

     List<Account> orgList = [select Id, Name from Account where Id in :accountIdSet];

        if(orgList != null && orgList.size()>0){    

         for(Account org : orgList){       

          List<Portfolio__c> portfolioList = [Select ID, Mandate__r.Mandate_Owner__c from Portfolio__c where Mandate__r.Mandate_Owner__c=:org.Id];    

             if(portfolioList != null && portfolioList.size()>0)       

              portfolioMap.put(org.Id,portfolioList);             }         }   

      for(Event e : Trigger.New){          

   List<Portfolio__c> tempList = portfolioMap.get(e.WhatId);     

        List<ID> portfolioIdList = new List<ID>();        

     if(tempList != null && tempList.size()>0){           

      for(Portfolio__c temp : tempList){           

          portfolioIdList.add(temp.Id);               

  }          

       if(portfolioIdList != null && portfolioIdList.size()>0)         

            PDFGenerator.generatePDF(e,portfolioIdList);         

    }     }        }

 

    if(Trigger.isupdate){        

Set<ID> accountIdSet = new Set<ID>();      

   for(Event e : Trigger.old){    

         accountIdSet.add(e.WhatId);     

      }    

     Map<Id,List<Portfolio__c>> portfolioMap = new Map<Id,List<Portfolio__c>>();      

   List<Account> orgList = [select Id, Name from Account where Id in :accountIdSet];     

    if(orgList != null && orgList.size()>0){       

      for(Account org : orgList){         

        List<Portfolio__c> portfolioList = [Select ID, Mandate__r.Mandate_Owner__c from Portfolio__c where Mandate__r.Mandate_Owner__c=:org.Id];        

         if(portfolioList != null && portfolioList.size()>0)              

       portfolioMap.put(org.Id,portfolioList);             }         }

        for(Event e : Trigger.old){      

       List<Portfolio__c> tempList = portfolioMap.get(e.WhatId);     

        List<ID> portfolioIdList = new List<ID>();    

         if(tempList != null && tempList.size()>0){        

         for(Portfolio__c temp : tempList){                    

portfolioIdList.add(temp.Id);                 }         

        if(portfolioIdList != null && portfolioIdList.size()>0)        

             PDFGenerator.generatePDF(e,portfolioIdList);          

   }         }     }      

-------------------

pdf:

--------------------

public with sharing class PDFGenerator {        

public static final String FORM_HTML_START = '<HTML><BODY>';    

public static final String FORM_HTML_END = '</BODY></HTML>';

public static void generatePDF(Event orgEvent, List<Id> parentIdList)     {

String pdfContent = '' + FORM_HTML_START;         String pdfName = '';  

 try         {

pdfContent = '' + FORM_HTML_START;

pdfContent = pdfContent + '<CENTER><H2>Event Information</H2></CENTER>';

pdfContent = pdfContent + '<P>' + ' ' + '</P>';            

pdfContent = pdfContent + '<P>' + 'Hi ' + '</P>';                      

pdfContent = pdfContent + '<P>' + 'New event is created please note that the following details ' + '</P>';                         //Dynamically grab all the fields to store in the PDF     

Map<String, Schema.SObjectType> sobjectSchemaMap = Schema.getGlobalDescribe();             Schema.DescribeSObjectResult objDescribe = sobjectSchemaMap.get('Event').getDescribe();  

Map<String, Schema.SObjectField> fieldMap = objDescribe.fields.getMap();                        

            //Append each Field to the PDF            

for(Schema.SObjectField fieldDef : fieldMap.values()  )             {

Schema.Describefieldresult fieldDescResult = fieldDef.getDescribe();                

String name = fieldDescResult.getName();                

pdfContent = pdfContent + '<P>' + name + ': ' + orgEvent.get(name) + '</P>';                    

}

 pdfContent = pdfContent + FORM_HTML_END;            

pdfName = 'org_event';         }catch(Exception e)        

{            

pdfContent = '' + FORM_HTML_START;            

pdfContent = pdfContent + '<P>THERE WAS AN ERROR GENERATING PDF: ' + e.getMessage() + '</P>';             pdfContent = pdfContent + FORM_HTML_END;       

}         attachPDF(parentIdList,pdfName,pdfContent);    

}        

private static void attachPDF(List<ID> parentIdList, String pdfName, String pdfContent)     {         try         {             if(parentIdList != null && parentIdList.size()>0){            

List<Attachment> attachmentList = new List<Attachment>();                

for(ID parentId : parentIdList){                    

Attachment attachmentPDF = new Attachment();                    

attachmentPDF.parentId = parentId;                    

attachmentPDF.Name = pdfName+ '.pdf';                    

attachmentPDF.body = Blob.toPDF(pdfContent);

//This creates the PDF content                    

attachmentList.add(attachmentPDF);                

}                

if(attachmentList != null && attachmentList.size()>0)                    

insert attachmentList;            

}         }catch(Exception e)        

{             system.debug('--- got error while creating pdf ---'+e.getMessage());    

}     }     }

  • November 28, 2012
  • Like
  • 0

I'm hoping someone can help. I'm writing a test class for a simple Line Item trigger (totally new at this). I am getting an error that the PriceBookEntryId can't be blank, but every time I try to pull in an ID, I get the error that my query returned no rows. 

 

Original trigger:

 

1
2
3
4

trigger OpportunityLineItemBeforeDelete on OpportunityLineItem (before delete) {
for (OpportunityLineItem li: Trigger.old)
    li.addError('Cannot remove a property once added. Contact support');
}

 

 

Test class that gives me the error: System.DmlException: Insert failed. First exception on row 0; first error: FIELD_INTEGRITY_EXCEPTION, field integrity exception: PricebookEntryId, unknown (versions 3.0 and higher must specify pricebook entry id; others must specify product id): [PricebookEntryId, unknown]

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
@IsTest
public class LIDeleteClass{
    static TestMethod void InsertOppty()
    {Date myDate = date.newinstance(2014, 12, 17);
    Opportunity oppty = new Opportunity(Name='Test', StageName='IO Signed', CloseDate=myDate);
      insert oppty;
    Opportunity oppty1 = [select id, Name, Stagename, Closedate 
                          from Opportunity 
                          where Name = :'Test' LIMIT 1];

     //PricebookEntry pbe = [select Id 
       //                    from PricebookEntry
         //                  where Product2.Name = :'Amazon Ad Platform (AAP)' 
     
            //               and Pricebook2.Name = :'Standard Price Book' LIMIT 1];
    OpportunityLineItem li = new OpportunityLineItem(OpportunityId=oppty1.id, Quantity=12000,TotalPrice=12000);

      insert li;
    Test.starttest();
       try
           {
              delete li;
            
              System.assert(false);
           }
           catch (DMLException e)
           {
          
           }
    Test.stoptest();
    }}

 

When I uncomment the pbe variable, I get the error System.QueryException: List has no rows for assignment to SObject.

 

Any help would be appreciated.

I have a class that updates a custom field on quote line item on after insert and after update. The sort order of the quote line items factor into the logic but it seems like the after update trigger for quote line items does not trigger if all the user does is change the sort order of the quote line items. If this is in fact the case, is there a workaround so I can execute my class when the sort order of the quote line items change? 

  • November 28, 2012
  • Like
  • 0

Hi Everyone,

 

Can someone please help.

 

I have a custom object called Student and has associated tasks with it. 

 

when a student is not active, I want all the tasks to be automatically marked as completed. can someone please help with the trigger and test class.

 

Many many thanks in advance.

Hi Friends,

 

Is it possible to send multiple records to printer directly by clicking a button in salesforce?

 

Thanks,

Logesh

  • November 28, 2012
  • Like
  • 0

I am just getting started with my Salesforce education. I have around 14 years of IT experience. Currently, I am a Sr. project manager and solution architect for database applications. Prior technical background includes Oracle, Developer 2000, PL/SQL, DBA, SQL Server, Business Objects, database design, datawarehouse, data migration etc. I have done some Java but not much. I have front end development experience in Oracle Developer 2000. I am able to pick up Salesforce fairly quick so far. I may need some effort with Apex programming.

 

I was wondering if this is the right time to get into Salesforce. Currently, the Salesforce job market is good but some people say that the in a couple of years, there will be no demand for Salesforce because there are too many Salesforce professionals. Is that true? Is Salesforce a good long term career?

 

I know this is a Salesforce forum but please give me some honest feedback about long term career with Salesforce. Any suggestions are greatly appreciated...

  • November 28, 2012
  • Like
  • 0

Hi,

 

We have a trigger which submits an oportunity automatically for approval if the 'Stage' is changed to either 'Won' or 'Lost' from some other stage status.

This part of the trigger works fine.

 

What we would like to implement as well is that when an opportunity is entered with the Stage set to 'Lost' (or 'Won') directly the submission to approval should also be triggered. So on creation the trigger should check if Stage equals 'Won' or 'Lost'

 

I am not sure how to write the IF statement for this instance.

It would need to include something like the ISNEW( ) function which however is only available in formulas.

 

Ideally if possible both functionalities, the existing and the check on record entry would be dealt with in one trigger.

 

Any help is appreciated!

Many thanks...

 

 

Trigger OpportunitySubmitForOrderListApproval on Opportunity (after update) {
 
    for(Integer i = 0; i < Trigger.new.size(); i++) 
    
     {
  if((Trigger.new[i].StageName == 'Won' && Trigger.old[i].StageName <> 'Won') ||

     (Trigger.new[i].StageName == 'Lost' && Trigger.old[i].StageName <> 'Lost'))

        {
 
            Approval.ProcessSubmitRequest req = new Approval.ProcessSubmitRequest();
            req.setComments('Submitted for approval. Please approve.');
            req.setObjectId(Trigger.new[i].Id);
            Approval.ProcessResult result = Approval.process(req);
            System.assert(result.isSuccess());  
 
        }
       
    }
 }

 

I have a situation when ever I insert a record a work flow fires and creates two tasks. What my question is... If I'm asked to insert those records using a data loader will workflow also fires then?  Cos right now for testing purpose I am manually entering the fields in the record and saving.. Just wanted to know if it works for bulk uploads. I tried doing one record using dataloader and it fired. But Just wanted to confirm that with 100 records

Hi Team,

 

I want to create a validation that only current year and next year values can be created on a object,

 

I am trying in with below way, but it is showing error Missig )'

 

OR (
YEAR(Sales_Plan__c ) <> YEAR (today().year() ),
YEAR(Sales_Plan__c ) <> YEAR (today().year() + 1 )
)

 

Can any one help me on the same

  • November 20, 2012
  • Like
  • 0

Hey there first post and thanks in advance for your help.

 

Can anyone let me know what their best practise is when shifting users about.

What do you do when a user goes on maternity leave, is there a way to freeze the user without having to pay X dollars per month for the privilege.

We have many users on a full license but it appears that they actually only need a chatter free license but I can't see an easy way of switching them over.

 

Thanks again for your help

 

Paul

I have this trigger defined:

 

trigger convertLeadToImplementationOpportunity on Lead (before update) {
    for (Lead lead : Trigger.new){

      if(lead.Status == 'Qualified' && !lead.isConverted && lead.isApproved__c == true){
          Database.LeadConvert leadConvert = new database.LeadConvert();
          LeadStatus convertStatus = [SELECT Id, MasterLabel FROM LeadStatus WHERE IsConverted=true LIMIT 1];

          leadConvert.setConvertedStatus(convertStatus.MasterLabel); // ("Closed - Converted");
          leadConvert.setLeadId(lead.id);

          Database.LeadConvertResult leadConvertResult = Database.convertLead(leadConvert);
          System.assert(leadConvertResult.isSuccess());
      }
    }
}

 

When I execute the main trigger code anonymously via the IDE, it succeeds.


I have this (failing) test defined for the trigger:

 

@isTest
privateclass tests {
static testMethod void approvedLeadShouldConvertToImplementationOpportunity() {

      Lead testLead = new Lead(FirstName='John', LastName='Smith', Status='Qualified');
      insert testLead;

      test.startTest();

       testlead.isApproved__c = true;
       update testlead;  //trigger convertLeadToImplementationOpportunity

       test.stopTest();

       Lead isConverted = [SELECT id, isConverted FROM Lead WHERE Id=:testlead.id];
       System.assert(isConverted.isConverted);    // fails - i.e. isConverted == false
    }
}

 

Can anyone please tell me why the assert is failing? I'm quite new to Apex, so forgive any obvious stupidity.


Thanks!

Adam Breen

 

I need to create very complex Salesforce report. The standard report builder doesn't support that way of complexity. But it should be the SalesForce report by requirements.
I need to be able to use custom SQL requests and some APEX code.

 

Could you please share with me, how do developers create complex Salesforce reports? 

I am trying to deploy a new trigger and can't because the test below is failing. It is failing with the following error:

 

16:04:51.566 (566509000)|EXCEPTION_THROWN|[37]|System.DmlException: ConvertLead failed. First exception on row 0; first error: INVALID_STATUS, invalid convertedStatus: Qualified: []

 

Yet when I run the query specified in teh following line:

 

LeadStatus convertStatus = [SELECT Id, MasterLabel FROM LeadStatus WHERE IsConverted = true LIMIT 1];

 

The status returned is 'Qualified' which is a valid status. Could anyone shed light on what may be going on... Thank you in advance.

 

private class TestPopulateCloseDateOnOppOnLeadConvert {

static testMethod void PopulateCloseDateOnOppOnLeadConversion() {

//Create
Lead lead = new Lead(LastName='Test', Company='Test', Business_Unit__c='EPS', CurrencyISOCode='USD', Status='Unqualified');
insert lead;

//Invoke
test.startTest();
Database.LeadConvert lc = new Database.LeadConvert();
lc.setLeadId(lead.Id);
LeadStatus convertStatus = [SELECT Id, MasterLabel FROM LeadStatus WHERE IsConverted = true LIMIT 1];
lc.setConvertedStatus(convertStatus.MasterLabel);
Database.LeadConvertResult lcr = Database.convertLead(lc);
system.assert(lcr.isSuccess());
test.stopTest();

//Check
id oppId = lcr.getOpportunityId();
Opportunity opp = [SELECT Id, CloseDate FROM Opportunity WHERE Id = :oppId];
system.assertEquals(system.today().addDays(3), opp.CloseDate);

}
}

trigger CaseCloseNoOpen on Case (Before update) 
{
    


    List<Id> caseIds = new List<Id>();
    
        Id caseRecordTypeId = [SELECT Id FROM RecordType WHERE Name = 'PM Case' AND SObjectType = 'Case'].Id;

        Id TaskRecordTypeId = [SELECT Id FROM RecordType WHERE Name = 'PM Task' AND SObjectType = 'Task'].Id;

    for(Case c : Trigger.New)
    {
           if(c.RecordTypeId == caseRecordTypeId && (c.Status == 'Completed' || c.Status == 'Closed'))
       {
            caseIds.add(c.Id);
       }
      
    }
    
       
       for(Training_Information__c customobj : [Select Id, Status__c,Case__c From Training_Information__c Where Case__c in: caseIds])
        {
            if(customobj.Status__c == 'Pending' || customobj.Status__c == 'Scheduled')
            {
                Trigger.newMap.get(customobj.Case__c).addError('Training has not been completed.');
            }
        }

    for(Development_Request__c customobj : [Select Id, Stage__c,Case__c From Development_Request__c Where Case__c in: caseIds])
        {
            if(customobj.Stage__c != 'Completed' && customobj.Stage__c != 'Cancelled DR/ VOID' && customobj.Stage__c != 'Draft')
            {
                Trigger.newMap.get(customobj.Case__c).addError('There are open Development Request associated with this Case.');
            }
        }  

    for(Task T : [Select Id, Status, WhatId, RecordTypeId From Task Where WhatId in: caseIds])
        {
            if(T.RecordTypeId == TaskRecordTypeId && (T.Status != 'Completed' && T.Status != 'Discarded'))
            {
                Trigger.newMap.get(T.WhatId).addError('There are still open PM Task on this Case.');
            }
        }
              
}

 How can we make this trigger better?  It is a trigger made to do the validation of no open task, training information records or development request records, so that a case which is being used for project management can't be closed until all of these three LOOKUP related objects are all resolved/Completed.

 

The above code works but I have questions like would it make sense to use a trigger to pass the newmap + oldmap into a class to do all of the heavy lifting?

 

Also, when evaluating please consider which approach would be easier to get code coverage on and why?

 

Please help if you can.

 

Thank you,

Steve Laycock

 

 

I have recently created a trigger that validates that 3 LOOKUP Field related objects have completed status before allowing a user to complete a case the is being used for project management.

 

What I need to know is what is the benefit of using a Trigger and a Class Vs. just a trigger, if there is any?

 

Which is easier normally to do unit test on for code coverage?

 

Please let me know what you think.

 

Thank you,

Steve Laycock