• eric_wc
  • NEWBIE
  • 0 Points
  • Member since 2010

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 10
    Questions
  • 15
    Replies

I managed to get my code to send out a mass email awhile back but now would like to enhance it to send another email with a different template at the same time.  (user clicks send both emails go out).  below is my code but it will not compile.  I get the error message:

"Save error: Method does not exist or incorrect signature: [Messaging.MassEmailMessage].setWhatIds(Id)"

 

Thanks for any help, maybe I am going about this the wrong way, I am not a developer...

 

Eric

 

public class MNEmail2 {
public String Template = [select MN_Email_Template__c from Case where id = :ApexPages.currentPage().getParameters().get('id') limit 1].MN_Email_Template__c;
public list <Contact> Test;
Contact[] contactList = new Contact[]{};
Id[] targetObjectIds = new Id[] {};
Id[] whatids = new Id[] {}; 
public id mn = [select ID from Case where id = :ApexPages.currentPage().getParameters().get('id')].id; 
public String custaff = [select MN_Customers_Affected__c from Case where id = :ApexPages.currentPage().getParameters().get('id') limit 1].MN_Customers_Affected__c;
String[] actnames = new List<String>();

public MNEmail2() {
	actnames = custaff.split(';');
	//System.debug ('***** List: ' + actnames + ', size: ' + actnames.size ());
         //Loop thrugh the whole ist of contacts an their emails
          for (Contact c : [Select account.name, name, email from Contact where Contact.Account.name = :actnames and Receive_support_notifications__c = True]) {
            targetObjectIds.add(c.Id);
            contactlist.add(c);
            whatIds.add(mn);
           }
}

//public Account getAccount() {
//return account;
//}
public string getTemplate() {
    return Template;
}
public id getmn() {
    return mn;
} 
 public list<Contact> getcontacts(){ 
        return ContactList;  
}

//cancel button action
public PageReference cancel() {
    PageReference pageRef = new PageReference('/'+ mn);
    pageRef.setRedirect(true);
    return pageRef;
}

//send button action
public PageReference send() {
// Define the email
Messaging.MassEmailMessage email1 = new Messaging.MassEmailMessage();
// Sets the paramaters of the email
	email1.setTargetObjectIds (targetObjectIds);
	email1.setWhatIds (whatids);
	email1.setTemplateId ([select id from EmailTemplate where Name = :template].id);
	email1.setreplyto ('noreply@demandtec.com');
	email1.setSenderDisplayName ('DemandTec Support No-Reply');
	//email.setSubject( subject );
	//email.setToAddresses( toAddresses );
	//email.setPlainTextBody( body );
// Sends the email 1
Messaging.SendEmailResult [] r1 =
Messaging.sendEmail(new Messaging.MassEmailMessage[] {email1});

// Define the second email
Messaging.massEmailMessage emaili = new Messaging.massEmailMessage();
// Sets the paramaters of the email
	emaili.setTargetObjectIds ([select id from Contact where email = 'support@gmail.com'].id);
	emaili.setWhatIds (mn);
	emaili.setTemplateId ([select id from EmailTemplate where Name = 'Internal Maintenance Notification'].id);
	emaili.setreplyto ('noreply@demandtec.com');
	emaili.setSenderDisplayName ('DemandTec Support No-Reply');
// Sends the email 2
Messaging.SendEmailResult [] ri =
Messaging.sendEmail(new Messaging.massEmailMessage[] {emaili});

//add case comment indicating email was sent.
CaseComment cmt1 = new CaseComment(
            ParentId = (mn),
            IsPublished = false,
            CommentBody = (custaff +'Were sent'+ Template +'email on '+ system.today()));
      Insert cmt1; 
//return to case page
PageReference pageRef = new PageReference('/'+ mn);
    pageRef.setRedirect(true);
    return pageRef;
return null;
}
static testMethod void testMNEmail2(){
   
        //make test data
        Account a = new Account(Name = 'Testing');
        Insert a;
        Contact con = new Contact(Firstname = 'testing',lastname = 'test',email = 'support@gmail.com',Receive_support_notifications__c = True,Account = a);
        Insert con;
        Case c = new Case(Subject = 'Test case',MN_Email_Template__c = 'Scheduled Maintenance',MN_Customers_Affected__c = 'Testing');
        Insert c;
       
        CaseComment cmt1 = new CaseComment(
            ParentId = c.id,
            IsPublished = false,
            CommentBody = 'A private comment from a user.'
        );
        CaseComment cmt2 = new CaseComment(
            ParentId = c.id,
            IsPublished = true,
            CommentBody = 'A public comment from a client.'
        );
        Insert cmt1;
        Insert cmt2;
       
         // Initiate class createOpsTicketClass with reference to created Support Case
             System.currentPageReference().getParameters().put('id', c.id);

             MNemail2 ee = new MNemail2();
             ee.targetObjectIds.add(con.Id);
             ee.whatIds.add(c.id);
             String nextPage = ee.send().getUrl();
             nextPage = ee.cancel().getUrl();
             System.assert(ee.mn == c.id);
}

}

 

Jake Gmerek helped me here on the boards with this trigger so I wanted to post it for others to use.  As an admin that ends up doing some dev projects I offten come to the boards looking for code samples to use in my projects.  

The trigger has 2 sections, the top is commented out and needs to be rewritten to handle bulk inserts that can happen with a trigger to avoid governer limits but it does work.  My project requirements changed so I did not rewrite it I just left it there for reference.

 

The bottom is the actual trigger that updates a new invoice (custom object) with an opportuity id.

 

I have also included the Test class which has been the hardest thing to wrap my head around how to do but I am now getting the hang of it for simple unit test.

 

I hope these code samples can help other admin/rookie developers.

Thanks again to Jake for his help and answering all my questions with code examples.

Eric

 

trigger InvoiceCreated on Invoice__c (before insert) {

 //***********************************************************************************************

/*
//update opp with new invoice custom obj id
//***this code needs to be changed to move the query out of the for loop!***
Opportunity[] updateOpportunity = new Opportunity[]{};
   
    //Loop over every invoice passed in. 
    for(Invoice__c inv : Trigger.new)
    {
       string PC = inv.EPICOR_Project_Code__c;  
       System.debug('>>>>>Project code: '+PC);
       ID opp = [select ID from Opportunity where EPICOR_Project_Code__c = :PC].id;
        System.debug('>>>>>Update Opp: '+opp);
        
             //Add them to list to update. 
            Opportunity thisOpportunity = new Opportunity(ID = opp);
                thisOpportunity.InvoiceID__c = inv.ID;
                updateOpportunity.add(thisOpportunity);
                update updateOpportunity; 
       
    }
*/

//***************************************************************************************************

//insert corresponding opp id into invoice custom object
//invoice list 
Invoice__c[] updateInvoices = new Invoice__c[]{};
	//list to store all epicor project codes from invoices
	List <string> pcode = new List<string>();
	//loop throgh invoices adding the projects codes to the list above
	For (Invoice__c inv : Trigger.new){
		pcode.add(inv.EPICOR_Project_Code__c);
	}
	//list to store all the opportunitys with matching project codes
	Opportunity[] opps = [select ID, EPICOR_Project_Code__c from Opportunity where EPICOR_Project_Code__c IN :pcode];
	
	For (Opportunity o: opps){
	//Loop through invoices updating them with the opp id with matching project code
		For (Invoice__c invoice : Trigger.new){
			if (invoice.EPICOR_Project_Code__c != null)
				if (o.EPICOR_Project_Code__c == invoice.EPICOR_Project_Code__c ){
					invoice.Opportunity__c = o.Id;
					updateInvoices.add(invoice);
				}
			}
	}
//only needed if using after insert
//update updateInvoices;
}

 

/**
 * This class contains unit tests for validating the behavior of Apex classes
 * and triggers.
 *
 * Unit tests are class methods that verify whether a particular piece
 * of code is working properly. Unit test methods take no arguments,
 * commit no data to the database, and are flagged with the testMethod
 * keyword in the method definition.
 *
 * All test methods in an organization are executed whenever Apex code is deployed
 * to a production organization to confirm correctness, ensure code
 * coverage, and prevent regressions. All Apex classes are
 * required to have at least 75% code coverage in order to be deployed
 * to a production organization. In addition, all triggers must have some code coverage.
 * 
 * The @isTest class annotation indicates this class only contains test
 * methods. Classes defined with the @isTest annotation do not count against
 * the organization size limit for all Apex scripts.
 *
 * See the Apex Language Reference for more information about Testing and Code Coverage.
 */
@isTest
private class TestInvoice {

    //get recordTypes
	public RecordType getRecordTypes(){		
		RecordType[] arRT = [select Id, Name from RecordType where SobjectType = :sObjectType.Opportunity.getName() limit 1];
		if(arRt.size() != 1)
			System.assertEquals(1,2, 'CommonTestUtil: CANNOT FIND RECORD TYPE!');
		
		return arRT[0];
	}
    
    static testMethod void myUnitTest() {
        // TO DO: implement unit test
        Account account = new Account (Name = 'testa');
        insert account;
        
        
        Opportunity[] opportunitys = new Opportunity[]{
        		new Opportunity (name = 'testo', 
        						account = account, 
        						EPICOR_Project_Code__c = 'TEST', 
        						stagename = 'Renew', 
        						closedate = system.today()+91),
        						
        		new Opportunity (name = 'testo2', 
        						account = account, 
        						EPICOR_Project_Code__c = 'TEST2', 
        						stagename = 'Renew', 
        						closedate = system.today()+91)
        };
        insert opportunitys;
        opportunitys[0].EPICOR_Project_Code__c = 'TEST';
        opportunitys[1].EPICOR_Project_Code__c = 'TEST2';
        update opportunitys;
        
       Opportunity opportunityTest = [Select EPICOR_Project_Code__c, stagename, closedate From Opportunity where id =: Opportunitys[0].id];
        system.debug (' Opportunity Object : '+ opportunityTest.EPICOR_Project_Code__c + opportunityTest.StageName + opportunityTest.CloseDate );  
       Opportunity opportunityTest2 = [Select EPICOR_Project_Code__c, stagename, closedate From Opportunity where id =: Opportunitys[1].id];
        system.debug (' Opportunity Object : '+ opportunityTest2.EPICOR_Project_Code__c + opportunityTest2.StageName + opportunityTest2.CloseDate );
         
        Invoice__c[] invoices = new Invoice__c[]{
        	new Invoice__c(name = 'testi', 
        			EPICOR_Project_Code__c = 'TEST', 
        			account__c = account.id
        			),
        			
        	new Invoice__c(name = 'testi2', 
        			EPICOR_Project_Code__c = 'TEST2', 
        			account__c = account.id
        			),
        			
        	new Invoice__c(name = 'testi3', 
        			EPICOR_Project_Code__c = 'TEST2', 
        			account__c = account.id
        			),
        			
        	new Invoice__c(name = 'testi4', 
        			EPICOR_Project_Code__c = 'TEST', 
        			account__c = account.id
        			),
        	new Invoice__c(name = 'testi5', 
        			//EPICOR_Project_Code__c = 'TEST', 
        			account__c = account.id
        			)
        };
        //test InvoiceCreated trigger
        insert invoices;
        
        Invoice__c invoiceTest = [Select EPICOR_Project_Code__c, name, opportunity__c From Invoice__c where id =: Invoices[0].id];
        system.debug (' Invoice Object : '+ invoiceTest.EPICOR_Project_Code__c + invoiceTest.name + invoiceTest.opportunity__c );  
       Invoice__c invoiceTest2 = [Select EPICOR_Project_Code__c, name, opportunity__c From Invoice__c where id =: Invoices[1].id];
        system.debug (' Invoice Object : '+ invoiceTest2.EPICOR_Project_Code__c + invoiceTest2.name + invoiceTest2.opportunity__c );
        Invoice__c invoiceTest3 = [Select EPICOR_Project_Code__c, name, opportunity__c From Invoice__c where id =: Invoices[2].id];
        system.debug (' Invoice Object : '+ invoiceTest3.EPICOR_Project_Code__c + invoiceTest3.name + invoiceTest3.opportunity__c );
        Invoice__c invoiceTest4 = [Select EPICOR_Project_Code__c, name, opportunity__c From Invoice__c where id =: Invoices[3].id];
        system.debug (' Invoice Object : '+ invoiceTest4.EPICOR_Project_Code__c + invoiceTest4.name + invoiceTest4.opportunity__c );
        Invoice__c invoiceTest5 = [Select EPICOR_Project_Code__c, name, opportunity__c From Invoice__c where id =: Invoices[4].id];
        system.debug (' Invoice Object : '+ invoiceTest5.EPICOR_Project_Code__c + invoiceTest5.name + invoiceTest5.opportunity__c );
        
        System.assert(invoiceTest.opportunity__c == opportunitytest.id);
        System.assert(invoiceTest2.opportunity__c == opportunitytest2.id);
        System.assert(invoiceTest3.opportunity__c == opportunitytest2.id);
        System.assert(invoiceTest4.opportunity__c == opportunitytest.id);
        System.assert(invoiceTest5.opportunity__c == null);
        
    }
}

 

 

My trigger is failing below because I am not able to return an id for some reason in my query.  Any ideas see code, unit test and error  below.

Thank You for any help/ideas

 

trigger InvoiceCreated on Invoice__c (before insert) {

Opportunity[] updateOpportunity = new Opportunity[]{};
   
    //Loop over every invoice passed in. 
    for(Invoice__c inv : Trigger.new)
    {
       string PC = inv.EPICOR_Project_Code__c;  
       System.debug('>>>>>Project code: '+PC);
       ID opp = [select ID from Opportunity where EPICOR_Project_Code__c = :PC].id;
        System.debug('>>>>>Update Opp: '+opp);
        //if (inv.InvoiceID__c == null) 
         //if (in.Status == 'Closed') 
          //if (in.Survey_Sent__c == True)
        //{   
             //Add them to list to update. 
            Opportunity thisOpportunity = new Opportunity(ID = opp);
                thisOpportunity.InvoiceID__c = inv.ID;
                updateOpportunity.add(thisOpportunity);
                update updateOpportunity; 
       // }
    }
}

 

@isTest
private class TestInvoice {

    static testMethod void myUnitTest() {
        // TO DO: implement unit test
        Account account = new Account (Name = 'testa');
        insert account;
        Opportunity opportunity = new Opportunity (name = 'testo', account = account, EPICOR_Project_Code__c = 'TEST', stagename = 'Renew', closedate = system.today());
        insert Opportunity;
        Invoice__c[] invoices = new Invoice__c[]{
        	new Invoice__c(name = 'testi', 
        			EPICOR_Project_Code__c = 'TEST', 
        			account__c = account.id
        			)
        	
        };
        //test InvoiceCreated trigger
        insert invoices;
        //cases[0].Survey_Sent__c = True;
        //cases[0].Status = 'Closed';
        //Test.startTest();
        //update cases;
        //Test.stopTest();
    }
}

 

 

Method Name

Total Time (ms)

Message

Stack Trace

TestInvoice.myUnitTest

596.0

System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, InvoiceCreated: execution of BeforeInsert caused by: System.QueryException: List has no rows for assignment to SObject Trigger.InvoiceCreated: line 10, column 17: []

Class.TestInvoice.myUnitTest: line 39, column 9 External entry point

 

10:55:38.826 (826535000)|DML_BEGIN|[39]|Op:Insert|Type:Invoice__c|Rows:1
10:55:38.829 (829252000)|CODE_UNIT_STARTED|[EXTERNAL]|01qS00000008dsp|InvoiceCreated on Invoice trigger event BeforeInsert for [new]
10:55:38.829 (829511000)|USER_DEBUG|[9]|DEBUG|>>>>>Project code: TEST
10:55:38.829 (829607000)|SOQL_EXECUTE_BEGIN|[10]|Aggregations:0|select ID from Opportunity where EPICOR_Project_Code__c = :PC
10:55:38.841 (841883000)|SOQL_EXECUTE_END|[10]|Rows:0
10:55:38.841 (841960000)|EXCEPTION_THROWN|[10]|System.QueryException: List has no rows for assignment to SObject
10:55:38.842 (842031000)|FATAL_ERROR|System.QueryException: List has no rows for assignment to SObject

Trigger.InvoiceCreated: line 10, column 17
10:55:39.350 (842131000)|CUMULATIVE_LIMIT_USAGE
10:55:39.350|LIMIT_USAGE_FOR_NS|(default)|
Number of SOQL queries: 6 out of 100
Number of query rows: 1 out of 50000
Number of SOSL queries: 0 out of 20
Number of DML statements: 3 out of 150
Number of DML rows: 3 out of 10000
Number of script statements: 77 out of 200000
Maximum heap size: 0 out of 3000000
Number of callouts: 0 out of 10
Number of Email Invocations: 0 out of 10
Number of fields describes: 0 out of 100
Number of record type describes: 0 out of 100
Number of child relationships describes: 0 out of 100
Number of picklist describes: 0 out of 100
Number of future calls: 0 out of 10

10:55:39.350|TOTAL_EMAIL_RECIPIENTS_QUEUED|0
10:55:39.350|STATIC_VARIABLE_LIST|
InvoiceCreated:updateOpportunity:4
RenewalOpportunityClass:gd:0
RenewalOpportunityClass:renewalSetup:1002
RenewalOpportunityClass:testUtils:4
TestUtils:EMAIL_SUFFIX:12
TestUtils:URL_PREFIX:23
TestUtils:gd:8697

10:55:39.350 (842131000)|CUMULATIVE_LIMIT_USAGE_END

10:55:38.842 (842484000)|CODE_UNIT_FINISHED|InvoiceCreated on Invoice trigger event BeforeInsert for [new]
10:55:38.843 (843529000)|DML_END|[39]
10:55:38.843 (843644000)|EXCEPTION_THROWN|[39]|System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, InvoiceCreated: execution of BeforeInsert

caused by: System.QueryException: List has no rows for assignment to SObject

Trigger.InvoiceCreated: line 10, column 17: []
10:55:38.846 (846422000)|FATAL_ERROR|System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, InvoiceCreated: execution of BeforeInsert

caused by: System.QueryException: List has no rows for assignment to SObject

Trigger.InvoiceCreated: line 10, column 17: []

Class.TestInvoice.myUnitTest: line 39, column 9
External entry point
10:55:39.355 (846470000)|CUMULATIVE_LIMIT_USAGE
10:55:39.355|LIMIT_USAGE_FOR_NS|(default)|
Number of SOQL queries: 5 out of 100
Number of query rows: 1 out of 50000
Number of SOSL queries: 0 out of 20
Number of DML statements: 3 out of 150
Number of DML rows: 3 out of 10000
Number of script statements: 73 out of 200000
Maximum heap size: 0 out of 3000000
Number of callouts: 0 out of 10
Number of Email Invocations: 0 out of 10
Number of fields describes: 0 out of 100
Number of record type describes: 0 out of 100
Number of child relationships describes: 0 out of 100
Number of picklist describes: 0 out of 100
Number of future calls: 0 out of 10

 

I am not a developer but I was trying to create a simple vf page for a report I need that I could not create using standard reports.  Using a Group By sql query I am able to get the results I am looking for but to display it in a vf page I had to use some apex code I found on a blog that was linked to on the boards.  It works great but first I don't fully understand the code and because I am not creating or inserting any records I am not sure how to write unit test to get the required 75% code coverage.  I have searched the boards and have read the links that people point everyone to when they ask test questions and I understand the concepts but I have yet to find a simple example of how to test code that just query's the db.  I am sure it can't be hard but with no development back ground I haven't got a clue.  

Thanks for any help you can provide.

Eric

 

public class casemorethan10
{
public list<AggregateResult> lstAR = new list<AggregateResult>();
/*
Note that any query that includes an aggregate function returns its results in an array of AggregateResult objects. AggregateResult is a read-only sObject and is only used for query results.
Aggregate functions become a more powerful tool to generate reports when you use them with a GROUP BY clause. For example, you could find the count of all opportunities for a CloseDate.

*/
public casemorethan10()
{
lstAR = [Select c.account.name name, count(c.casenumber) total from Case c where status = 'Open' and c.recordtype.name <> 'Opperations Case' and c.recordtype.name <> 'Maintenance Notifications' group by c.account.name Having count(c.casenumber) > 15];
}

public list<OppClass> getResults()
{
list<OppClass> lstResult = new list<OppClass>();
for (AggregateResult ar: lstAR)
{
oppClass objOppClass = new oppClass(ar);
lstResult.add(objOppClass);
}
return lstResult;
}

class oppClass
{
public Integer total
{ get;set; }

public String name
{ get;set; }

public oppClass(AggregateResult ar)
{
//Note that ar returns objects as results, so you need type conversion here
total = (Integer)ar.get('total');
name = (String)ar.get('name');
}
}
}

 

<apex:page controller="casemorethan10">
    <apex:outputPanel layout="block" style="overflow:auto;width:380px;height:600px" >
    <apex:dataTable value="{!Results}" var="r" border="2" cellpadding="1" >
        <apex:column headerValue="Name" value="{!r.name}"/>
        <apex:column headerValue="# cases" value="{!r.total}"/>
    </apex:dataTable>
    </apex:outputPanel>
</apex:page>

 

Please help I am not a developer but am trying to learn.  After taking code samples from the board and manuals I was able to get this apex class do what I wanted but then I ran into the issue of unit test.  I had a hard enough time figuring out how to get the class to work.  I feel like I am banging my head against a wall with the unit test process it just does not make sense to me.  But I have figured out how to get 80% coverage but it is failing and I am not sure how to fix it.  Any help would be appreciated.

Thanks

Eric

 

Message: System.EmailException: SendEmail failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING, Missing target object ids (contact, lead or user): []

stack trace: Class.MNEmail2.send: line 56, column 1 Class.MNEmail2.testMNEmail2: line 89, column 32 External entry point

 

 

public class MNEmail2 {
public String Template = [select MN_Email_Template__c from Case where id = :ApexPages.currentPage().getParameters().get('id') limit 1].MN_Email_Template__c;
public list <Contact> Test;
Contact[] contactList = new Contact[]{};
Id[] targetObjectIds = new Id[] {};
Id[] whatids = new Id[] {}; 
public id mn = [select ID from Case where id = :ApexPages.currentPage().getParameters().get('id')].id; 
public String custaff = [select MN_Customers_Affected__c from Case where id = :ApexPages.currentPage().getParameters().get('id') limit 1].MN_Customers_Affected__c;
String[] actnames = new List<String>();

public MNEmail2() {
actnames = custaff.split(';');
//System.debug ('***** List: ' + actnames + ', size: ' + actnames.size ());
         //Loop thrugh the whole ist of contacts an their emails
          for (Contact c : [Select account.name, name, email from Contact where Contact.Account.name = :actnames and Receive_support_notifications__c = True]) {
            targetObjectIds.add(c.Id);
            contactlist.add(c);
            whatIds.add(mn);
           }
}

//public Account getAccount() {
//return account;
//}
public string getTemplate() {
    return Template;
}
public id getmn() {
    return mn;
} 
 public list<Contact> getcontacts(){ 
        return ContactList;  
}


public PageReference cancel() {
    PageReference pageRef = new PageReference('/'+ mn);
    pageRef.setRedirect(true);
    return pageRef;
}

public PageReference send() {
// Define the email
Messaging.MassEmailMessage email = new Messaging.MassEmailMessage();
// Sets the paramaters of the email
email.setTargetObjectIds (targetObjectIds);
email.setWhatIds (whatids);
email.setTemplateId ([select id from EmailTemplate where Name = :template].id);
email.setreplyto ('noreply@demandtec.com');
email.setSenderDisplayName ('DemandTec Support No-Reply');
//email.setSubject( subject );
//email.setToAddresses( toAddresses );
//email.setPlainTextBody( body );
// Sends the email
Messaging.SendEmailResult [] r =
Messaging.sendEmail(new Messaging.MassEmailMessage[] {email});
PageReference pageRef = new PageReference('/'+ mn);
    pageRef.setRedirect(true);
    return pageRef;
return null;
}
static testMethod void testMNEmail2(){
   
        //make test data
        Account a = new Account(Name = 'Testing');
        Insert a;
        Contact con = new Contact(Firstname = 'testing',lastname = 'test',email = 'eric.wc@gmail.com',Receive_support_notifications__c = True,Account = a);
        Insert con;
        Case c = new Case(Subject = 'Test case',MN_Email_Template__c = 'Scheduled Maintenance',MN_Customers_Affected__c = 'Testing');
        Insert c;
       
        CaseComment cmt1 = new CaseComment(
            ParentId = c.id,
            IsPublished = false,
            CommentBody = 'A private comment from a user.'
        );
        CaseComment cmt2 = new CaseComment(
            ParentId = c.id,
            IsPublished = true,
            CommentBody = 'A public comment from a client.'
        );
        Insert cmt1;
        Insert cmt2;
       
         // Initiate class createOpsTicketClass with reference to created Support Case
             System.currentPageReference().getParameters().put('id', c.id);

             MNemail2 ee = new MNemail2();
             String nextPage = ee.send().getUrl();
             nextPage = ee.cancel().getUrl();
             System.assert(ee.mn == c.id);
}

}

 

 

 

I am trying to figure out how to load a multi-select field values in to a list variable so I can loop through the list using the values in a query.

 

For example multi-select list contains a,b,c,d,e

b and d are selected so if I query the field i get back b;d

how do I get b;d loaded in to a list var  x  so I can use each of them in a query

 

for ...

select * from sobject where name =  x

 

 

I know this has to be possible but not being a developer I have not been able to figure out how.

Any help would be much appreciated

Thanks

Eric

 

 

I am still learning apex and vf but I know this cannot be hard but I cannot figure it out.  I have a custom object that has a mutli-select picklist that contains some account names.  I need to create a page that will list out all the contacts associated to the accounts selected in that multi-select picklist.

 

Thanks for any help you can provide.

 

Eric

I am trying to create a custom case creation page but I am stuck on how to get the contact and account lookup fields values on the VF page saved with the case.  Here is my vf and apex code:

 

 

<apex:page controller="newcaseController" tabStyle="Case">
  <!-- Begin Default Content REMOVE THIS -->
  <h1>Congratulations</h1>
  This is your new Page
  
  <script>
  function confirmCancel() {
      var isCancel = confirm("Are you sure you wish to cancel?");
      if (isCancel) return true;
      return false;
  }
  </script>
  <apex:sectionHeader title="new case"/>
      <apex:form >
          <apex:pageBlock title="Case info" mode="edit">
          <apex:pageBlockButtons >
              <apex:commandButton action="{!save}" value="Save"/>
              <apex:commandButton action="{!cancel}" value="Cancel"
                                          onclick="return confirmCancel()" immediate="true"/>
          </apex:pageBlockButtons>
          <apex:pageblocksection title="Contact and Account info info">
              <apex:inputField id="contactName" value="{!case.contactid}"/>
              <apex:inputField id="accountName" value="{!case.accountid}"/>
              <apex:inputField id="rootcause" value="{!case.root_cause__c}"/>
              
              
              
          </apex:pageblocksection>
          </apex:pageblock>
      </apex:form>
         
  <!-- End Default Content REMOVE THIS -->
</apex:page>

 

 

 

public class newcaseController {

Case case1;


public Case getCase() {
    if(case1 == null) case1 = new Case();
    return case1;
    
}

    


public PageReference step1() {
    return Page.casestep1;
}

public PageReference cancel() {
    PageReference casePage = new ApexPages.StandardController(case1).view();
    casePage.setRedirect(true);
    return casePage;
}

public PageReference save() {
    case1.subject = 'popup blocker issue';
    
    insert case1;
    
    PageReference casePage = new ApexPages.StandardController(case1).view();
    casePage.setRedirect(true);
    
    return casePage;
}
}

 I am very new to this and have been going through the VF and Apex developers guides but cannot figure his out.

 

Thanks

Eric

 

 

I am still learning visual force and I cannot for the life of me figure out how to order the results of the below code by the createddate field? 
 

 

 

<apex:page standardController="Case">

<!-- ALL COMMENTS -->

<apex:pageBlock title="Case Comments" id="allCommentsPB">

<apex:pageBlockSection title=" " columns="1" id="allCommentsPBS">

<apex:pageBlockTable value="{!case.CaseComments}" var="comment" >

<apex:column value="{!comment.IsPublished}"/>

<apex:column value="{!comment.CreatedDate}"/>

<apex:column value="{!comment.CreatedById}"/>

<apex:column value="{!comment.CommentBody}"/>

</apex:pageBlockTable>

</apex:pageBlockSection>

</apex:pageBlock>

</apex:page>

 


 

 
 
Thanks in advance.
 
Eric 
Message Edited by eric_wc on 02-03-2010 03:23 AM
Message Edited by eric_wc on 02-03-2010 03:24 AM

What is the best way to add a predefined case team to a case not using assignment rules.  We need to assign predefined case teams to a case based on the account but we do not assign all of our cases based on account so assignment rules will not always work...

 

Thanks

Eric 

I managed to get my code to send out a mass email awhile back but now would like to enhance it to send another email with a different template at the same time.  (user clicks send both emails go out).  below is my code but it will not compile.  I get the error message:

"Save error: Method does not exist or incorrect signature: [Messaging.MassEmailMessage].setWhatIds(Id)"

 

Thanks for any help, maybe I am going about this the wrong way, I am not a developer...

 

Eric

 

public class MNEmail2 {
public String Template = [select MN_Email_Template__c from Case where id = :ApexPages.currentPage().getParameters().get('id') limit 1].MN_Email_Template__c;
public list <Contact> Test;
Contact[] contactList = new Contact[]{};
Id[] targetObjectIds = new Id[] {};
Id[] whatids = new Id[] {}; 
public id mn = [select ID from Case where id = :ApexPages.currentPage().getParameters().get('id')].id; 
public String custaff = [select MN_Customers_Affected__c from Case where id = :ApexPages.currentPage().getParameters().get('id') limit 1].MN_Customers_Affected__c;
String[] actnames = new List<String>();

public MNEmail2() {
	actnames = custaff.split(';');
	//System.debug ('***** List: ' + actnames + ', size: ' + actnames.size ());
         //Loop thrugh the whole ist of contacts an their emails
          for (Contact c : [Select account.name, name, email from Contact where Contact.Account.name = :actnames and Receive_support_notifications__c = True]) {
            targetObjectIds.add(c.Id);
            contactlist.add(c);
            whatIds.add(mn);
           }
}

//public Account getAccount() {
//return account;
//}
public string getTemplate() {
    return Template;
}
public id getmn() {
    return mn;
} 
 public list<Contact> getcontacts(){ 
        return ContactList;  
}

//cancel button action
public PageReference cancel() {
    PageReference pageRef = new PageReference('/'+ mn);
    pageRef.setRedirect(true);
    return pageRef;
}

//send button action
public PageReference send() {
// Define the email
Messaging.MassEmailMessage email1 = new Messaging.MassEmailMessage();
// Sets the paramaters of the email
	email1.setTargetObjectIds (targetObjectIds);
	email1.setWhatIds (whatids);
	email1.setTemplateId ([select id from EmailTemplate where Name = :template].id);
	email1.setreplyto ('noreply@demandtec.com');
	email1.setSenderDisplayName ('DemandTec Support No-Reply');
	//email.setSubject( subject );
	//email.setToAddresses( toAddresses );
	//email.setPlainTextBody( body );
// Sends the email 1
Messaging.SendEmailResult [] r1 =
Messaging.sendEmail(new Messaging.MassEmailMessage[] {email1});

// Define the second email
Messaging.massEmailMessage emaili = new Messaging.massEmailMessage();
// Sets the paramaters of the email
	emaili.setTargetObjectIds ([select id from Contact where email = 'support@gmail.com'].id);
	emaili.setWhatIds (mn);
	emaili.setTemplateId ([select id from EmailTemplate where Name = 'Internal Maintenance Notification'].id);
	emaili.setreplyto ('noreply@demandtec.com');
	emaili.setSenderDisplayName ('DemandTec Support No-Reply');
// Sends the email 2
Messaging.SendEmailResult [] ri =
Messaging.sendEmail(new Messaging.massEmailMessage[] {emaili});

//add case comment indicating email was sent.
CaseComment cmt1 = new CaseComment(
            ParentId = (mn),
            IsPublished = false,
            CommentBody = (custaff +'Were sent'+ Template +'email on '+ system.today()));
      Insert cmt1; 
//return to case page
PageReference pageRef = new PageReference('/'+ mn);
    pageRef.setRedirect(true);
    return pageRef;
return null;
}
static testMethod void testMNEmail2(){
   
        //make test data
        Account a = new Account(Name = 'Testing');
        Insert a;
        Contact con = new Contact(Firstname = 'testing',lastname = 'test',email = 'support@gmail.com',Receive_support_notifications__c = True,Account = a);
        Insert con;
        Case c = new Case(Subject = 'Test case',MN_Email_Template__c = 'Scheduled Maintenance',MN_Customers_Affected__c = 'Testing');
        Insert c;
       
        CaseComment cmt1 = new CaseComment(
            ParentId = c.id,
            IsPublished = false,
            CommentBody = 'A private comment from a user.'
        );
        CaseComment cmt2 = new CaseComment(
            ParentId = c.id,
            IsPublished = true,
            CommentBody = 'A public comment from a client.'
        );
        Insert cmt1;
        Insert cmt2;
       
         // Initiate class createOpsTicketClass with reference to created Support Case
             System.currentPageReference().getParameters().put('id', c.id);

             MNemail2 ee = new MNemail2();
             ee.targetObjectIds.add(con.Id);
             ee.whatIds.add(c.id);
             String nextPage = ee.send().getUrl();
             nextPage = ee.cancel().getUrl();
             System.assert(ee.mn == c.id);
}

}

 

 

My trigger is failing below because I am not able to return an id for some reason in my query.  Any ideas see code, unit test and error  below.

Thank You for any help/ideas

 

trigger InvoiceCreated on Invoice__c (before insert) {

Opportunity[] updateOpportunity = new Opportunity[]{};
   
    //Loop over every invoice passed in. 
    for(Invoice__c inv : Trigger.new)
    {
       string PC = inv.EPICOR_Project_Code__c;  
       System.debug('>>>>>Project code: '+PC);
       ID opp = [select ID from Opportunity where EPICOR_Project_Code__c = :PC].id;
        System.debug('>>>>>Update Opp: '+opp);
        //if (inv.InvoiceID__c == null) 
         //if (in.Status == 'Closed') 
          //if (in.Survey_Sent__c == True)
        //{   
             //Add them to list to update. 
            Opportunity thisOpportunity = new Opportunity(ID = opp);
                thisOpportunity.InvoiceID__c = inv.ID;
                updateOpportunity.add(thisOpportunity);
                update updateOpportunity; 
       // }
    }
}

 

@isTest
private class TestInvoice {

    static testMethod void myUnitTest() {
        // TO DO: implement unit test
        Account account = new Account (Name = 'testa');
        insert account;
        Opportunity opportunity = new Opportunity (name = 'testo', account = account, EPICOR_Project_Code__c = 'TEST', stagename = 'Renew', closedate = system.today());
        insert Opportunity;
        Invoice__c[] invoices = new Invoice__c[]{
        	new Invoice__c(name = 'testi', 
        			EPICOR_Project_Code__c = 'TEST', 
        			account__c = account.id
        			)
        	
        };
        //test InvoiceCreated trigger
        insert invoices;
        //cases[0].Survey_Sent__c = True;
        //cases[0].Status = 'Closed';
        //Test.startTest();
        //update cases;
        //Test.stopTest();
    }
}

 

 

Method Name

Total Time (ms)

Message

Stack Trace

TestInvoice.myUnitTest

596.0

System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, InvoiceCreated: execution of BeforeInsert caused by: System.QueryException: List has no rows for assignment to SObject Trigger.InvoiceCreated: line 10, column 17: []

Class.TestInvoice.myUnitTest: line 39, column 9 External entry point

 

10:55:38.826 (826535000)|DML_BEGIN|[39]|Op:Insert|Type:Invoice__c|Rows:1
10:55:38.829 (829252000)|CODE_UNIT_STARTED|[EXTERNAL]|01qS00000008dsp|InvoiceCreated on Invoice trigger event BeforeInsert for [new]
10:55:38.829 (829511000)|USER_DEBUG|[9]|DEBUG|>>>>>Project code: TEST
10:55:38.829 (829607000)|SOQL_EXECUTE_BEGIN|[10]|Aggregations:0|select ID from Opportunity where EPICOR_Project_Code__c = :PC
10:55:38.841 (841883000)|SOQL_EXECUTE_END|[10]|Rows:0
10:55:38.841 (841960000)|EXCEPTION_THROWN|[10]|System.QueryException: List has no rows for assignment to SObject
10:55:38.842 (842031000)|FATAL_ERROR|System.QueryException: List has no rows for assignment to SObject

Trigger.InvoiceCreated: line 10, column 17
10:55:39.350 (842131000)|CUMULATIVE_LIMIT_USAGE
10:55:39.350|LIMIT_USAGE_FOR_NS|(default)|
Number of SOQL queries: 6 out of 100
Number of query rows: 1 out of 50000
Number of SOSL queries: 0 out of 20
Number of DML statements: 3 out of 150
Number of DML rows: 3 out of 10000
Number of script statements: 77 out of 200000
Maximum heap size: 0 out of 3000000
Number of callouts: 0 out of 10
Number of Email Invocations: 0 out of 10
Number of fields describes: 0 out of 100
Number of record type describes: 0 out of 100
Number of child relationships describes: 0 out of 100
Number of picklist describes: 0 out of 100
Number of future calls: 0 out of 10

10:55:39.350|TOTAL_EMAIL_RECIPIENTS_QUEUED|0
10:55:39.350|STATIC_VARIABLE_LIST|
InvoiceCreated:updateOpportunity:4
RenewalOpportunityClass:gd:0
RenewalOpportunityClass:renewalSetup:1002
RenewalOpportunityClass:testUtils:4
TestUtils:EMAIL_SUFFIX:12
TestUtils:URL_PREFIX:23
TestUtils:gd:8697

10:55:39.350 (842131000)|CUMULATIVE_LIMIT_USAGE_END

10:55:38.842 (842484000)|CODE_UNIT_FINISHED|InvoiceCreated on Invoice trigger event BeforeInsert for [new]
10:55:38.843 (843529000)|DML_END|[39]
10:55:38.843 (843644000)|EXCEPTION_THROWN|[39]|System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, InvoiceCreated: execution of BeforeInsert

caused by: System.QueryException: List has no rows for assignment to SObject

Trigger.InvoiceCreated: line 10, column 17: []
10:55:38.846 (846422000)|FATAL_ERROR|System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, InvoiceCreated: execution of BeforeInsert

caused by: System.QueryException: List has no rows for assignment to SObject

Trigger.InvoiceCreated: line 10, column 17: []

Class.TestInvoice.myUnitTest: line 39, column 9
External entry point
10:55:39.355 (846470000)|CUMULATIVE_LIMIT_USAGE
10:55:39.355|LIMIT_USAGE_FOR_NS|(default)|
Number of SOQL queries: 5 out of 100
Number of query rows: 1 out of 50000
Number of SOSL queries: 0 out of 20
Number of DML statements: 3 out of 150
Number of DML rows: 3 out of 10000
Number of script statements: 73 out of 200000
Maximum heap size: 0 out of 3000000
Number of callouts: 0 out of 10
Number of Email Invocations: 0 out of 10
Number of fields describes: 0 out of 100
Number of record type describes: 0 out of 100
Number of child relationships describes: 0 out of 100
Number of picklist describes: 0 out of 100
Number of future calls: 0 out of 10

 

Hello -

 

I am trying to add a visualforce page to my custom object that will show the related products.

 

So my "Sales Checklist" object is housed on the opportunity, sales fills all the information out then the object is sent to a queue.

 

But to save time i want to pull in the opportunityLineItems in to the sales checklist?

 

Is this possable? I know very little visualforce.

 

This is as far as I have gotten:

 

<apex:page StandardController="Sales_Checklist__c">
<apex:relatedList list="Opportunity__r" />

<apex:pageBlock title="{!Sales_Checklist__c.Opportunity__r.Name}"/>

  <apex:dataTable value="{!Sales_Checklist__c.Opportunity__r}" var="opp" cellPadding="4" border="1">
                
           <apex:column ><apex:facet name="header">Product Name</apex:facet></apex:column>
                
                
           <apex:column><apex:facet name="header">Quantity</apex:facet></apex:column>
                
                
           <apex:column ><apex:facet name="header">Unit Price</apex:facet></apex:column>
                
              
           <apex:column ><apex:facet name="header">Total Price</apex:facet></apex:column>
  </apex:dataTable>
</apex:page>

 

 

any help would be greatlt appriciated

 

Thanks,

Niki

Please help I am not a developer but am trying to learn.  After taking code samples from the board and manuals I was able to get this apex class do what I wanted but then I ran into the issue of unit test.  I had a hard enough time figuring out how to get the class to work.  I feel like I am banging my head against a wall with the unit test process it just does not make sense to me.  But I have figured out how to get 80% coverage but it is failing and I am not sure how to fix it.  Any help would be appreciated.

Thanks

Eric

 

Message: System.EmailException: SendEmail failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING, Missing target object ids (contact, lead or user): []

stack trace: Class.MNEmail2.send: line 56, column 1 Class.MNEmail2.testMNEmail2: line 89, column 32 External entry point

 

 

public class MNEmail2 {
public String Template = [select MN_Email_Template__c from Case where id = :ApexPages.currentPage().getParameters().get('id') limit 1].MN_Email_Template__c;
public list <Contact> Test;
Contact[] contactList = new Contact[]{};
Id[] targetObjectIds = new Id[] {};
Id[] whatids = new Id[] {}; 
public id mn = [select ID from Case where id = :ApexPages.currentPage().getParameters().get('id')].id; 
public String custaff = [select MN_Customers_Affected__c from Case where id = :ApexPages.currentPage().getParameters().get('id') limit 1].MN_Customers_Affected__c;
String[] actnames = new List<String>();

public MNEmail2() {
actnames = custaff.split(';');
//System.debug ('***** List: ' + actnames + ', size: ' + actnames.size ());
         //Loop thrugh the whole ist of contacts an their emails
          for (Contact c : [Select account.name, name, email from Contact where Contact.Account.name = :actnames and Receive_support_notifications__c = True]) {
            targetObjectIds.add(c.Id);
            contactlist.add(c);
            whatIds.add(mn);
           }
}

//public Account getAccount() {
//return account;
//}
public string getTemplate() {
    return Template;
}
public id getmn() {
    return mn;
} 
 public list<Contact> getcontacts(){ 
        return ContactList;  
}


public PageReference cancel() {
    PageReference pageRef = new PageReference('/'+ mn);
    pageRef.setRedirect(true);
    return pageRef;
}

public PageReference send() {
// Define the email
Messaging.MassEmailMessage email = new Messaging.MassEmailMessage();
// Sets the paramaters of the email
email.setTargetObjectIds (targetObjectIds);
email.setWhatIds (whatids);
email.setTemplateId ([select id from EmailTemplate where Name = :template].id);
email.setreplyto ('noreply@demandtec.com');
email.setSenderDisplayName ('DemandTec Support No-Reply');
//email.setSubject( subject );
//email.setToAddresses( toAddresses );
//email.setPlainTextBody( body );
// Sends the email
Messaging.SendEmailResult [] r =
Messaging.sendEmail(new Messaging.MassEmailMessage[] {email});
PageReference pageRef = new PageReference('/'+ mn);
    pageRef.setRedirect(true);
    return pageRef;
return null;
}
static testMethod void testMNEmail2(){
   
        //make test data
        Account a = new Account(Name = 'Testing');
        Insert a;
        Contact con = new Contact(Firstname = 'testing',lastname = 'test',email = 'eric.wc@gmail.com',Receive_support_notifications__c = True,Account = a);
        Insert con;
        Case c = new Case(Subject = 'Test case',MN_Email_Template__c = 'Scheduled Maintenance',MN_Customers_Affected__c = 'Testing');
        Insert c;
       
        CaseComment cmt1 = new CaseComment(
            ParentId = c.id,
            IsPublished = false,
            CommentBody = 'A private comment from a user.'
        );
        CaseComment cmt2 = new CaseComment(
            ParentId = c.id,
            IsPublished = true,
            CommentBody = 'A public comment from a client.'
        );
        Insert cmt1;
        Insert cmt2;
       
         // Initiate class createOpsTicketClass with reference to created Support Case
             System.currentPageReference().getParameters().put('id', c.id);

             MNemail2 ee = new MNemail2();
             String nextPage = ee.send().getUrl();
             nextPage = ee.cancel().getUrl();
             System.assert(ee.mn == c.id);
}

}

 

 

 

I am trying to figure out how to load a multi-select field values in to a list variable so I can loop through the list using the values in a query.

 

For example multi-select list contains a,b,c,d,e

b and d are selected so if I query the field i get back b;d

how do I get b;d loaded in to a list var  x  so I can use each of them in a query

 

for ...

select * from sobject where name =  x

 

 

I know this has to be possible but not being a developer I have not been able to figure out how.

Any help would be much appreciated

Thanks

Eric

 

 

I am still learning apex and vf but I know this cannot be hard but I cannot figure it out.  I have a custom object that has a mutli-select picklist that contains some account names.  I need to create a page that will list out all the contacts associated to the accounts selected in that multi-select picklist.

 

Thanks for any help you can provide.

 

Eric

I am trying to create a custom case creation page but I am stuck on how to get the contact and account lookup fields values on the VF page saved with the case.  Here is my vf and apex code:

 

 

<apex:page controller="newcaseController" tabStyle="Case">
  <!-- Begin Default Content REMOVE THIS -->
  <h1>Congratulations</h1>
  This is your new Page
  
  <script>
  function confirmCancel() {
      var isCancel = confirm("Are you sure you wish to cancel?");
      if (isCancel) return true;
      return false;
  }
  </script>
  <apex:sectionHeader title="new case"/>
      <apex:form >
          <apex:pageBlock title="Case info" mode="edit">
          <apex:pageBlockButtons >
              <apex:commandButton action="{!save}" value="Save"/>
              <apex:commandButton action="{!cancel}" value="Cancel"
                                          onclick="return confirmCancel()" immediate="true"/>
          </apex:pageBlockButtons>
          <apex:pageblocksection title="Contact and Account info info">
              <apex:inputField id="contactName" value="{!case.contactid}"/>
              <apex:inputField id="accountName" value="{!case.accountid}"/>
              <apex:inputField id="rootcause" value="{!case.root_cause__c}"/>
              
              
              
          </apex:pageblocksection>
          </apex:pageblock>
      </apex:form>
         
  <!-- End Default Content REMOVE THIS -->
</apex:page>

 

 

 

public class newcaseController {

Case case1;


public Case getCase() {
    if(case1 == null) case1 = new Case();
    return case1;
    
}

    


public PageReference step1() {
    return Page.casestep1;
}

public PageReference cancel() {
    PageReference casePage = new ApexPages.StandardController(case1).view();
    casePage.setRedirect(true);
    return casePage;
}

public PageReference save() {
    case1.subject = 'popup blocker issue';
    
    insert case1;
    
    PageReference casePage = new ApexPages.StandardController(case1).view();
    casePage.setRedirect(true);
    
    return casePage;
}
}

 I am very new to this and have been going through the VF and Apex developers guides but cannot figure his out.

 

Thanks

Eric

 

 

What is the best way to add a predefined case team to a case not using assignment rules.  We need to assign predefined case teams to a case based on the account but we do not assign all of our cases based on account so assignment rules will not always work...

 

Thanks

Eric 

I've installed the round robin case assignment and it works great.  I just can't figure out how to notify the new case owner after it's done.  My workflow doesn't send the message because the case isn't assigned until after the workflows have fired.  After that the after update portion assigns the case, and the user never gets the email.

 

The question could also be how can I get an email out to the user when a trigger assigns it after the workflows have run their course.

 

Any ideas? 

  • July 27, 2009
  • Like
  • 0