• carlo
  • NEWBIE
  • 85 Points
  • Member since 2011

  • Chatter
    Feed
  • 3
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 8
    Questions
  • 114
    Replies

Surprise surprise...after hacking a trigger together I am struggling with the test class...

 

The trigger is pretty simple - it creates a Case when an Account is created with certain criteria (may be worth pointing out our org uses PersonAccounts)

 

Here is the trigger:

 

//define trigger and when it fires
trigger CreateCase on Account (after insert) {
  
  //create list for cases to be inserted
  List<Case> newcase = new List<Case>();

  //find the ID of the correct record type
  Id rtId = [select Id, name from RecordType where name ='My Record Type' and   SObjectType='Case' limit 1].Id;

  //find contact ID which relates to the Account created to attach to the to case
  Id personContact = [select id, Name from Contact where Contact.AccountId in : Trigger.New].Id;

  //define criteria when the trigger fires
  for (Account acc: Trigger.New) {
    if (acc.Corporate_Account_Link_Text__c == 'My Corporate Account') {
      

      //define what values to put against the new case
      newcase.add(new Case(
            AccountId = acc.Id,
            ContactId = personContact,
            RecordTypeId = rtId,
            Type='My Type',
            Origin='My Origin',
            Status='My Status',
            Call_Attempt__c='1'
          )
      
        );
        }
    
      //insert the new case(s)
      insert newcase;  
    }
}

 

 

 

Have had a go with the test class, but not come up with much useful...any pointers appreciated!

 

Thanks

Hi All,

 

Can someone please help me finish this test class for the apex trigger below. 

 

//Trigger will execute only when a Technical Query is created or updated
trigger UpdateWarranty on Case (before insert, before update) {   
    
    //Run a loop through each query that was created or updated  
    for(Case c : Trigger.new){
        
        //Only execute the following statements if Technical query is created else do nothing 
        If(c.RecordTypeId == '012D0000000AoAZ' && c.Serial_Number_New__C != null){
        
            //Store the value of Serial Number which was entered by the user in variable cid
            String cid = c.Serial_Number_New__c; 
            //Run a query on the Warranty__c table and find the associated fields
            List<Warranty__c> Serials = [SELECT Id, Engine_Number__c, Model_Number__c FROM Warranty__c WHERE Id = :cid] ;
            //Store the fields 
            c.Engine_s_n__c = Serials.get(0).Engine_Number__c; 
            c.Model_Number__c = Serials.get(0).Model_Number__c;
           }
           
     }
}

 This is what i have done so far:

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
	@isTest        

    private class TestUpdateWarranty {
    
        public static testMethod void testUpdateWarranty() {
        
        Warranty__c Warranty = new Warranty__c(Name = 'Test11',Model_Number__c = 'MF100',Engine_Number__c = 'ENG100' );
        insert Warranty;  
        
        Warranty__c Warranty1 = [select Id, Name, Model_Number__c, Engine_Number__c FROM Warranty__c where Id =:Warranty.Id];
        Warranty1.Engine_Number__c = 'ENG200';
        update Warranty1;   
        
        System.assertEquals('Test11',Warranty1.Name);
        System.assertEquals('MF100',Warranty1.Model_Number__c);
        System.assertEquals('ENG200',Warranty1.Engine_Number__c);
        
        Case Warranty2 = new Case(Serial_Number_New__c = 'Test11');
        System.assertEquals('MF100',Warranty2.Model_Number__c);
        System.assertEquals('ENG200',Warranty2.Engine_s_n__c);

 

  • March 16, 2012
  • Like
  • 0

hi

 

what is difference between standard and custom controller in salesforce.I am getting confusation.

thanks.

 

Hello

 

I want to setup a web based area where our customers can update their information.  I assume they would need to login to get update permission.  Can CMSForce handle this - login page and secure update page/s?

 

Thanks

 

Carlo

  • August 29, 2012
  • Like
  • 0

Hello

 

I'm just about to start using Action Plans and thought I would ask some Quick Questions on here first:

 

1.  Should I leave the original code from the package unchanged - so I can update the package to future releases if necessary?

2.  Can I assign to Tasks to different users?  So for new client onboarding we want to assign tasks to different departments like accounts and installations.

 

Thats it for now.

 

Thanks

 

Carlo

  • August 27, 2012
  • Like
  • 0

Hello

 

I want to build a web based editor for our customers.  They would use this to view the information we have stored for them and also edit this.  This would involve some form of password authentication.

 

Obviously this info is stored in SF now.

 

I know there are hundreds of ways to do this but thought I would ask on here if there is a common path most people are using or would recommend.

 

Thanks

 

Carlo

  • August 24, 2012
  • Like
  • 0

Hello

 

I am trying to send an email to a Lead using a Template.  I want to store the email as an activity.

 

I have created a template.  It is a VF template with recipientType Lead and relatedToType Campaign.  When I Send Test and Verify Merge Fields this works fine.  It asks me for the Lead/LeadId and the Campaign/CampaignID.  Then if I send the email using Apex if Save as Activity is false it works fine but if Save as Activity is true it does not.  I want to Save the Activity so I can see which Leads were sent which emails - standard CRM stuff.

 

This works fine:

 

mail.setTargetObjectId(LeadId);

mail.setSaveAsActivity(false);

mail.setTemplateID(TemplateId);

mail.setWhatID(CampaignId);

 

This throws the error:

 

mail.setTargetObjectId(LeadId);

mail.setSaveAsActivity(true);

mail.setTemplateID(TemplateId);

mail.setWhatID(CampaignId);

 

Error is:

 

System.EmailException: SendEmail failed. First exception on row 0; first error: INVALID_ID_FIELD, WhatId is not available with saveAsActivity for sending emails to Leads.

 

So the error is pretty self explanatory.  I don't need an explanation of this error.  I want to know how I can work around this if possible.  

 

Simply I want to send an email to a Lead which is related to a campaign [uses merge fields] and save this as an activity.

 

Thanks

 

Carlo

 

 

  • June 15, 2012
  • Like
  • 0

Hello

 

Is the attachment object a master detail relationship with its parent?

 

If I delete the parent will it delete the attachment?

 

I want to share an attachment across 2 objects.  So we have a paper contract which is scanned and attached as an image.  This is usually attached as an attachment to the contract object.  I want to show this in the Account attachments.  Do I need to copy the attachment to the Account or can I just show the attachments of the Contract records under the parent Account?

  • April 10, 2012
  • Like
  • 0

Hello

 

I have 3 Dashboards which display key metrics for the 3 main departments in our organisation.  I want to display these on a large screen in our Head Office.  Ideally I want the screen to show Dashboard 1 for say 30 seconds and then Dashboard 2 for 30 seconds and then Dashboard 3 etc...

 

Is this possible?

 

Thanks

  • April 05, 2012
  • Like
  • 0

Hello

 

I am writing an extension to add an extra line to a Long Text Area field so it can show Created by and Last Modified by just like a Case Comment.

 

Created by Me | Last Modified by Me

Long Text Area line 1
Long Text Area line 2
Long Text Area line 3

 

What should I use for new line?  

 

If I use /r, /n or /r/n then the first line is displayed but the rest of the field is not.  I just get this

 

Created by Me | Last Modified by Me

 

Thanks

  • March 16, 2012
  • Like
  • 0

Hello

 

I am exporting data from SF to a third party system using XML.  I have setup a VF Page with a Controller to collect the data required and format this into XML using the Dom Document and XMLNode objects. This was working fine until I started getting the occasional Time Limit Exceeded on the VF Page. I presume I am hitting some kind of limit as the volume of data required in this export has increased as we have been using SF and adding more data.

 

I have identified that the problem is the Dom.XMLNode object because I created a copy of my controller without it and instead built the XML as a string.  This works fine.

 

The VF page just contains one line which outputs the string to the screen.

 

My Dom.XMLNode Controller gets data from a Master Object and 3 Children.  It uses a List for the Master Object and then 3 Maps for the Children.  I am confident this is not causing me any problems because this is replicated in my String based controller which works fine.

 

Once I have the data loaded I then set up my Dom.Document and XMLNode root element.

 

I then enter a Loop through my Master Object List:

 

Dom.XMLNode Master = root.addChildElement('Master', null, null);

Master.addChildElement('MasterDataField1', null, null).addTextNode('DataValue1');
  Master.addChildElement('MasterDataField2', null, null).addTextNode('DataValue2');
  Master.addChildElement('MasterDataField3', null, null).addTextNode('DataValue3');

 

I then have a Loop to go through Child1 Map for this Master record

 

Dom.XMLNode Child1 = Master.addChildElement('Child1', null, null);

Child1.addChildElement('Child1DataField1', null, null).addTextNode('Child1Value1');
  Child1.addChildElement('Child1DataField2', null, null).addTextNode('Child1Value2');
  Child1.addChildElement('Child1DataField3', null, null).addTextNode('Child1Value3');

 

I then have another Loop to go through Child2 Map for this Master record

 

Dom.XMLNode Child2 = Master.addChildElement('Child2', null, null);

  Child1.addChildElement('Child2DataField1', null, null).addTextNode('Child2Value1');
   Child1.addChildElement('Child2DataField2', null, null).addTextNode('Child2Value2');
   Child1.addChildElement('Child2DataField3', null, null).addTextNode('Child2Value3');

 

  I then have another Loop to go through Child3 Map for this Master record

 

  Dom.XMLNode Child2 = Master.addChildElement('Child2', null, null);

Child3.addChildElement('Child3DataField1', null, null).addTextNode('Child3Value1');
Child3.addChildElement('Child3DataField2', null, null).addTextNode('Child3Value2');
    Child3.addChildElement('Child3DataField3', null, null).addTextNode('Child3Value3');

 

I then return master.toXMLString() 

 

So does anyone see any problems with my code or where it might be inefficient?

 

Thanks

 

Carlo

  • March 04, 2011
  • Like
  • 0

The class posted below is fed a set of Contact Ids that comes from a trigger on the Task object. We use particular Task record type to track what we call 'Market Development'. A Market Development task contributes towards a total Market Development score for the contact. Therefore we have this class which will add or subtract MD points for a Contact as MD tasks are added or deleted. 

 

My issue is that Total Points are not being subtracted when an MD task is deleted. As I said the class receives a set of contact ids and processes MD points from there by using SOQL to select the Contacts and their MD Tasks. What I have found is that, in after delete trigger context only, the SOQL query that is supposed to get the Contact fails to find the contact. And this where I get stuck. I have put comments in the code below to hopefully help you understand how I am trying to debug this.

 

Any thoughts on why this is happening or a different debugging technique would be great.

public class MarketDevelopmentScorecard {

    public static void updateMarketDevelopmentScorecard(Set<Id> contactIds) {
    	RecordType mdRecordType = RecordTypeUtil.getRecordType('Task', 'Market Development');
    	if (mdRecordType != null) {
            Date recentActivityDate = System.today().addDays(-1095); // 3 years ago
	        
	        List<Task> mdTasks =
	            [select Id,
	                    ActivityDate,
	                    MD_Activity_Type__c,
	                    WhoId
	            from    Task
	            where   WhoId in :contactIds
	                and RecordTypeId = :mdRecordType.Id
	                and ActivityDate >= :recentActivityDate];
	                
            Map<Id, Set<String>> contactMarketDevelopmentActivities = new Map<Id, Set<String>>();
	        for (Task t : mdTasks) {
	        	if (t.MD_Activity_Type__c != null && t.MD_Activity_Type__c != '') {
	                Set<String> mdActivities = contactMarketDevelopmentActivities.get(t.WhoId);
	                if (mdActivities == null) {
	                    mdActivities = new Set<String>();
	                    contactMarketDevelopmentActivities.put(t.WhoId, mdActivities);
	                }
	                mdActivities.add(t.MD_Activity_Type__c);
	        	}
	        }

            List<Market_Development_Rating__c> marketDevelopmentRatings = Market_Development_Rating__c.getAll().values();
            
            for (Id cId : contactIds) {
            	System.debug('JJB contactId: ' + cId);
            }
            
            List<Contact> contacts = 
                [select Id,
                        MD_Total_Points__c,
                        MD_Activities__c
                from    Contact
                where   Id in :contactIds];
            //this system assert shows that I am receiving a contact from the trigger, but that the SOQL query doesn't find it
            //system.assert(false, 'Contacts from Trigger '+contactIds.size()+'Contacts found in database '+contacts.size());
            for (Contact c : contacts) {
            	Decimal totalPoints = 0.0;
            	String activities = '';
                //in after delete context this system assert never gets hit because this for loop never starts because there is nothing in the List contacts
            	//system.assert(false, 'hello!! ');            	
            	Set<String> mdActivities = contactMarketDevelopmentActivities.get(c.Id);
            	if (mdActivities == null) {
            		mdActivities = new Set<String>();
            	}
            	
            	for (Market_Development_Rating__c mdr : marketDevelopmentRatings) {
            		if (mdActivities.contains(mdr.Name)) {
            			totalPoints += mdr.MD_Points__c;
            			if (mdr.Contact_Field_Name__c != null && mdr.Contact_Field_Name__c != '') {
            				c.put(mdr.Contact_Field_Name__c, mdr.MD_Points__c);
            				//system.assert(false, 'the total points are: '+mdr.MD_Points__c);
            			}
            		} else {
                        if (mdr.Contact_Field_Name__c != null && mdr.Contact_Field_Name__c != '') {
                            c.put(mdr.Contact_Field_Name__c, 0.00);
                        }
            		}
            	}

 

 

 

Very new to Salesforce here.

 

I have 2 multi-select fields in my Lead object called "States Worked" and "States Licensed".

 

I want to create a third field called "All States" which will include all options chosen for both "States Worked" and "States Licensed".

 

I was thinking I could create a trigger that would update "All States" with the data selected for the other two fields.

 

Can anyone help me get started with this?

 

Thanks!

I have the following trigger I need to deploy to production but have only been able to get 66% test coverage. 

 

trigger createworkorder on Opportunity (after update)
{
if(trigger.new[0].StageName=='closed won'&&(trigger.old[0].StageName<>'closed won'))
{
Work_Order__c obj=new                               Work_Order__c(Opportunity__c=trigger.new[0].id,Stage__c='New',Account__c=trigger.new[0].AccountId);

insert obj;
List<Case> ll=new List<Case>();
for(OpportunityLineItem la : [SELECT PricebookEntry.Product2.Name from OpportunityLineItem where opportunityId =: Trigger.new])
{
String ss= String.ValueOf(la.PricebookEntry.Product2.Name);
case c1=new case(Status='new',Subject='Fulfillment for'+' '+ss,Work_Order__c=obj.id);
ll.add(c1);
}
insert ll;
}
}

 

Can someone help me with this test code?

Hi i am new to salesforce. my code is not working, the where condition in query is not filtering data and when i am using groupby its showing the error

Field must be grouped or aggregated..even when i use WHERE its throwing error.

 

here is the class

 

public List<Policy__c> getMyPolicy() {
List<Policy__c> temp =[SELECT name,AVG(Sum_Of_Premium__c),Channel_Name__r.Target__c from Policy__c GROUP BY CreatedDate];
return temp;

 

In this i need average of custom field sum of premium.

 

any idea on this why it is not working???

Surprise surprise...after hacking a trigger together I am struggling with the test class...

 

The trigger is pretty simple - it creates a Case when an Account is created with certain criteria (may be worth pointing out our org uses PersonAccounts)

 

Here is the trigger:

 

//define trigger and when it fires
trigger CreateCase on Account (after insert) {
  
  //create list for cases to be inserted
  List<Case> newcase = new List<Case>();

  //find the ID of the correct record type
  Id rtId = [select Id, name from RecordType where name ='My Record Type' and   SObjectType='Case' limit 1].Id;

  //find contact ID which relates to the Account created to attach to the to case
  Id personContact = [select id, Name from Contact where Contact.AccountId in : Trigger.New].Id;

  //define criteria when the trigger fires
  for (Account acc: Trigger.New) {
    if (acc.Corporate_Account_Link_Text__c == 'My Corporate Account') {
      

      //define what values to put against the new case
      newcase.add(new Case(
            AccountId = acc.Id,
            ContactId = personContact,
            RecordTypeId = rtId,
            Type='My Type',
            Origin='My Origin',
            Status='My Status',
            Call_Attempt__c='1'
          )
      
        );
        }
    
      //insert the new case(s)
      insert newcase;  
    }
}

 

 

 

Have had a go with the test class, but not come up with much useful...any pointers appreciated!

 

Thanks

Hi, I'm wondering how I can write an assertion in a test method that shows that an email was sent.  I have code that sends an email if certain criteria are met, but does not do any updates to the object in question.  If the only outcome from the code firing is that an email is sent, how can I verify that the email was sent?

 

I understand that if I wrap the test like so:

 

test.startTest();
insert aCase;
test.stopTest();

Then the stopTest() should make all asynchronous tasks run - including sendEmail.  My question is, how do I query the send email log in a test method to assert it sent the email?

 

Thanks in advance!

 

I have already created a VF Page and a controlller to upload an image.

Once uploaded I want to provide an abitity to crop and edit the image and then save it. I am new to salesforce...

PLease help...

 

Thanks in advance

 

Neha

  • December 27, 2011
  • Like
  • 0