• 3421
  • NEWBIE
  • 10 Points
  • Member since 2015

  • Chatter
    Feed
  • 0
    Best Answers
  • 1
    Likes Received
  • 0
    Likes Given
  • 31
    Questions
  • 36
    Replies
The child elements in the xml are not being covered in the test class. Since the childelements are not identified, the datamap is coming as null and that in turn is not covering the rest of the lines. I did look at all the possible links in all communities, but I am not sure how I could get the child elements in test class
Here is the sample xml
<Response> 
<XMLRootNode xmlns="http://www.how.com/Services/CustomReport/v1"> 
<ResponseHeader/>
 <CustomReport Name="Order" ID="69"> 
<DataRow>
 <DataColumn Name="PaymentID">634</DataColumn> 
<DataColumn Name="Company Number">0011N00001LoAVw</DataColumn> <DataColumn Name="Companyname">Inventory</DataColumn> 
<DataColumn Name="ContactFName">ane</DataColumn> 
<DataColumn Name="ContactLName">Pratt</DataColumn> 
<DataColumn Name="Mode">Online Credit Card</DataColumn>
 <DataColumn Name="Amount">8900.0000</DataColumn> 
<DataColumn Name="Card Type">Visa</DataColumn>
 <DataColumn Name="OrderID">714</DataColumn>
 <DataColumn Name="OrderAmtPaid">8900.0000</DataColumn> 
<DataColumn Name="Item">Networking</DataColumn> 
</DataRow>

Here is the code for the handler class that is returning null
public Static Void loadChilds(DOM.XMLNode xmlnode){ 
for (Dom.XMLNode child: xmlnode.getChildElements()) { 

If (child.getName()=='CustomReport') { 

for (DOM.XMLNode grandchild: child.getChildElements()) { 
datalst.add(grandchild); 
} 
PerformOperations(datalst); 
} 
else{ loadChilds(child); 
} } } 

public Static Void PerformOperations(List<DOM.XMLNode> xmlnodes){ system.debug('xmlnodes list size'+xmlnodes.size()); 
for (DOM.XMLNode grandchild: xmlnodes) { 
for (DOM.XMLNode node: grandchild.getChildElements()) { 
String paymentid = node.getAttributeValue('Name', '');

 if(paymentid=='OrderID') 
dataelementmap.put(node.getText(), grandchild); 
} }

 If(!dataelementmap.isEmpty()){ 

for(String str:dataelementmap.keyset()){ 
for (DOM.XMLNode node: dataelementmap.get(str).getChildElements()) {
Since the dataelementmap is null, anything is not getting covered.
Here is my test class that I started
Test.startTest(); 

comdataservicesdomhandler AP = new comdataservicesdomhandler(); 

String endPoint ='end'; String soapmessage = 'message';
 Integer timeout = 10; 
SingleRequestMock fakeResponse = new SingleRequestMock(200,'Complete','[{"Name":"sForceTest1"}]',null); 

Test.setMock(HttpCalloutMock.class, fakeResponse); comdataservicesdomhandler.SendRequest(); comdataservicesdomhandler.CallProcessRequest(); 

Http h = new Http();

 HttpRequest req = new HttpRequest(); 
req.setMethod('POST'); 
HttpResponse res = new HttpResponse(); 
res.setHeader('Content-Type', 'XML'); 
res.setBody('<?xml version="1.0"?><CustomReport Name="Order Payment" ID="69"><DataRow><DataColumn Name="PaymentID">634</DataColumn><DataColumn Name="Company Number">0011N00001LoAVw</DataColumn><DataColumn Name="Companyname">Z5 Inventory</DataColumn><DataColumn Name="ContactFName">ane</DataColumn><DataColumn Name="ContactLName">ratt</DataColumn><DataColumn Name="Mode">Online Credit Card</DataColumn><DataColumn Name="Amount">8900.0000</DataColumn><DataColumn Name="Card Type">Visa</DataColumn><DataColumn Name="PaymentDate">11/20/2019 11:56:42 AM</DataColumn><DataColumn Name="OrderID">714</DataColumn><DataColumn Name="OrderAmtPaid">8900.0000</DataColumn><DataColumn Name="Item">Networking</DataColumn></DataRow></CustomReport>'); 

Dom.Document doc = res.getBodyDocument(); 
Dom.XMLNode CustomReport1 = doc.getRootElement(); 
Dom.XmlNode CustomReport2 = doc.getRootElement(); 
List<Dom.XmlNode> creport = new List<Dom.XmlNode>(); creport.add(CustomReport1); 
creport.add(CustomReport2); 
String ResponseXml = 'cia'; comdataservicesdomhandler.Processresponse('<?xml version="1.0"?><CustomReport Name="Order Payment" ID="69"><DataRow><DataColumn Name="PaymentID">634</DataColumn><DataColumn Name="Company Number">0011N00001LoAVw</DataColumn><DataColumn Name="Companyname">Z5 Inventory</DataColumn><DataColumn Name="ContactFName">ane</DataColumn><DataColumn Name="ContactLName">ratt</DataColumn><DataColumn Name="Mode">Online Credit Card</DataColumn><DataColumn Name="Amount">8900.0000</DataColumn><DataColumn Name="Card Type">Visa</DataColumn><DataColumn Name="PaymentDate">11/20/2019 11:56:42 AM</DataColumn><DataColumn Name="OrderID">714</DataColumn><DataColumn Name="OrderAmtPaid">8900.0000</DataColumn><DataColumn Name="Item">Networking</DataColumn></DataRow></CustomReport>'); comdataservicedomhandler.loadChilds(CustomReport1);

 
  • February 13, 2020
  • Like
  • 0
I am new to Integration Projects. I have an Apex class generated from the WSDL of a third party. I would like to utilize the methods of that Apex class and write a batch class that utilizes the response.
Here is the error that I received when testing the code below
Web service callout failed: WebService returned a SOAP Fault: System.Web.Services.Protocols.SoapException: Server was unable to process request. ---> System.NullReferenceException: Object reference not set to an instance of an object. at DataServices.a2zService.GetCustomSqlReport(XmlNode request) in D:\inetpub\wwwroot\027112\Partners.a2zinc.net\DataServices\App_Code\Public\a2zService.vb:line 176 --- End of inner exception stack trace --- faultcode=soap:Server faultactor=
Can someone help me on how I could test the response in Anonymous window? I can then use the same parameters in batch class as well
Here is the code that I tried executing anonymously
Request.request_element req = new request.request_element();
Dataservices.ServiceSoap service = new Dataservices.ServiceSoap();

Response.response_element res = service.GetReport(req);
system.debug('response'+res);
Here is my Apex class
public class Service {
    public class AuthenticationHeader {
        public String Key;
        public String UserName;
        public String Password;
        private String[] Key_type_info = new String[]{'Key','http://www.show.com/Services/Service/v1',null,'0','1','false'};
        private String[] UserName_type_info = new String[]{'UserName','http://www.show.com/Services/Service/v1',null,'0','1','false'};
        private String[] Password_type_info = new String[]{'Password','http://www.show.com/Services/Service/v1',null,'0','1','false'};
        private String[] apex_schema_type_info = new String[]{'http://www.show.com/Services/Service/v1','true','false'};
        private String[] field_order_type_info = new String[]{'Key','Source','UserName','Password','InstallName'};
    }
    public class ServiceSoap {
        public String endpoint_x = 'http://partners.inc.net/services/public/Service.asmx';
        public Map<String,String> inputHttpHeaders_x;
        public Map<String,String> outputHttpHeaders_x;
        public String clientCertName_x;
        public String clientCert_x;
        public String clientCertPasswd_x;
        public Integer timeout_x;
        public Service.AuthenticationHeader AuthenticationHeader;
        private String AuthenticationHeader_hns = 'AuthenticationHeader=http://www.show.com/Services/Service/v1';
        private String[] ns_map_type_info = new String[]{'http://www.show.com/Services/ReportRequest/v1', 'Request', 'http://www.show.com/Services/ReportResponse/v1', 'Response', 'http://www.show.com/Services/Service/v1', 'Service'};
        public Response.Response_element GetReport(Request.request_element request) {
            Request.DataService_element request_x = new Request.Service_element();
The Request class:
//Generated by wsdl2apex

public class Request {
    public class Service_element {
        public Request.request_element request;
        private String[] request_type_info = new String[]{'request','http://www.show.com/Services/ReportRequest/v1',null,'0','1','false'};
        private String[] apex_schema_type_info = new String[]{'http://www.show.com/Services/ReportRequest/v1','true','false'};
        private String[] field_order_type_info = new String[]{'request'};
    }
    public class request_element {
        private String[] apex_schema_type_info = new String[]{'http://www.show.com/Services/ReportRequest/v1','true','false'};
        private String[] field_order_type_info = new String[]{};
    }
}

Response Class:
/Generated by wsdl2apex

public class Response {
    public class Response_element {
        private String[] apex_schema_type_info = new String[]{'http://www.show.com/Services/ReportResponse/v1','true','false'};
        private String[] field_order_type_info = new String[]{};
    }
    public class Service_element {
        public Response.Response_element Response;
        private String[] Response_type_info = new String[]{'Response','http://www.show.com/Services/ReportResponse/v1',null,'0','1','false'};
        private String[] apex_schema_type_info = new String[]{'http://www.show.com/Services/ReportResponse/v1','true','false'};
        private String[] field_order_type_info = new String[]{'Response'};
    }
}

Here are the request parameters that I use to test in SOAP UI

User-added image



 
  • October 16, 2019
  • Like
  • 0
I have a wsdl to Apex generated. The below is the method from the service that I could see
public DataserviceReport.Response_element GetCustomReport(Dataservices.request_element request) {
        Dataservices.DataService_element request_x = new Dataservices.DataService_element();

Here are the classes that is called in the method above
 
public class DataserviceReport {
    public class Response_element {
        private String[] apex_schema_type_info = new String[]{'http://www.show.com/DataServices/CustomReportResponse/v1','true','false'};
        private String[] field_order_type_info = new String[]{};
    }
    public class DataService_element {
        public DataserviceReport.Response_element Response;
        private String[] Response_type_info = new String[]{'Response','http://www.show.com/DataServices/CustomReportResponse/v1',null,'0','1','false'};
        private String[] apex_schema_type_info = new String[]{'http://www.show.com/DataServices/CustomReportResponse/v1','true','false'};
        private String[] field_order_type_info = new String[]{'Response'};
    }
}

//Generated by wsdl2apex

public class Dataservices {
    public class DataService_element {
        public Dataservices.request_element request;
        private String[] request_type_info = new String[]{'request','http://www.show.com/DataServices/CustomReportRequest/v1',null,'0','1','false'};
        private String[] apex_schema_type_info = new String[]{'http://www.show.com/DataServices/CustomReportRequest/v1','true','false'};
        private String[] field_order_type_info = new String[]{'request'};
    }
    public class request_element {
        private String[] apex_schema_type_info = new String[]{'http://www.show.com/DataServices/CustomReportRequest/v1','true','false'};
        private String[] field_order_type_info = new String[]{};
    }
}

I did test the above wsdl in soap UI and here are the parameters that it is requring to see the response
User-added image
  • September 23, 2019
  • Like
  • 0
I have an apex class which looks for the old and new values of contacthistory. I am writing a test class for this, but could not write data to Oldvalue and Newvalue. I also tried updating the field which is tracked in history, but that gives null value when I tried assert statement. Here is my class
for(ContactHistory ct: scope){ if((ct.NewValue =='Test Data' && ct.OldValue =='Old Data')|| (ct.NewValue == 'New Test Data' && ct.OldValue =='Old Data Listing'){ //do something }}


How do I cover this if condition?
Here is my test class:
Test.startTest();
 Contact c = new contact(lastname = 'test', email='email@email.com'); 
c.TrackedField__c ='OldData'; 
c.AccountId = acc.Id; 
insert c; 
c.TrackedField__c ='Test Data';
 update c; 
Test.stopTest(); 
ContactHostory ch =[select contactid, OldValue, NewValue from ContactHistory where ContactId=: c.id and Field ='TrackedField__c' limit1];   //this is returning zero results

 
  • August 28, 2019
  • Like
  • 0
I have a lookup relationship between Order Line and Contact Objects where Contact is the parent. I am writing a batch class which looks for certain criteria on Order Line and send email to Contacts excluding the duplicates. 

Right now I have  2 duplicate Order Lines for the Contact and the batch is supposed to send 1 email. But in this code, there are 3 emails sent out. Can someone help with this?
 
global class BatchSendEmails implements Database.Batchable<SObject>
{
global Database.QueryLocator start(Database.BatchableContext BC){
	return Database.getQueryLocator([select id,Contact__r.Email,Contact__c,Account__c from Order_Line__c 
                                     where Order__r.OrderApi__Date__c = LAST_N_DAYS:3]);
}
      
    global void execute (Database.BatchableContext BC, List<Order_Line__c> scope){
         List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();
                                 List<String> email = new List<String>(); 
      
       List<Order_Line__c> sollist = [SELECT Id, Item__c, Contact__c,Order__c ,Contact__r.Email FROM Order_Line__c
        WHERE Order__r.Date__c = LAST_N_DAYS:3 AND Item__r.Name = 'Test'];
       
        Set<Id> solids = new Set<Id>();
        for(Order_Line__c ol : ollist){
            if(ol.id != null){
               olids.add(ol.Contact__c);
                system.debug('Added Contacts'+olids);
            }
        }
        
        AggregateResult[] groupedResults = [
        SELECT COUNT(Id) dups, Item__c, Contact__c,Order__c,Contact__r.Email
        FROM Order_Line__c
        WHERE Contact__c =:solids and Sales_Order__r.Date__c = LAST_N_DAYS:3 
        AND Item__r.Name = 'Test'    
        GROUP BY Item__c,Contact__c,Contact__r.Email,Order__c
         HAVING COUNT(Id) = 1];

        for(AggregateResult ar:groupedResults){
            String custid = (ID)ar.get('OrderApi__Contact__c');
            
          //	email.add(custid);
            
        List<Order_Line__c> sollist1 = [select id, Contact__r.Email,Order__c from Order_Line__c where id=: ar.Id limit 1];
            email.clear();
                email.add(ollist[0].OrderApi__Contact__r.Email); */
                                 List<String> ccemail = new List<String>();                                 
                                 ccemail.add('test@test.com');
    							 Contact c = [select id, Email from Contact where email <> null limit 1];
            try{                             
EmailTemplate templateId = [Select id from EmailTemplate where name = 'Email'];                                                   
                    system.debug(email);
                Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
                 OrgWideEmailAddress owa = [select id, DisplayName, Address from OrgWideEmailAddress where address = 'testing@test.org' limit 1];
                                            system.debug(email.size());
                                            mail.setToAddresses(email);
                                            mail.setccAddresses(ccemail);
                                            mail.setOrgWideEmailAddressId(owa.id);
                                            mail.setTargetObjectId(c.Id);
           									mail.setTreatTargetObjectAsRecipient(false);
                                            mail.setTemplateID(templateId.Id); 
                                            mail.setSaveAsActivity(false); 
                                            mails.add(mail);
                                            system.debug(mail);
											
                          
                                 Messaging.sendEmail(mails);
            }catch(Exception e){
                system.debug('Exception occured' +e);
            }
                
    }
    }
        
    global void finish(Database.BatchableContext BC){
        
    }
}

 
  • November 28, 2018
  • Like
  • 1
I am unable to insert opportunity line item schedule record in the test class. Can anyone let me know the fields and criteria for inserting schedule record in test class
 
  • May 20, 2018
  • Like
  • 0
I have a Batch Class where I am looking for Contact matches to Account and would like to update Contact with associating Account.

How do I write update outside the loop? I want to update the Account in the map to the contact from initial loop

Here is the code
 
Set<String> emailDomains = new Set<String>();
 Set<String> emailDomains001 = new Set<String>();
        Set<Id> ctId = new Set<Id>();

    List<Contact> ctlist = [select Id, FirstName,LastName,Email,Business_Name__c,Member_Type__c from Contact where Email <> null and LastModifiedDate = N_DAYS_AGO:5];    

        for (Contact ct : ctlist){
     
     if(ct.Type__c == 'Test'){
                ct.AccountId = '0015467Dvbg';
                update ct;
            }
     else if(ct.Account.Name == ct.Name__c && ct.Type__c <> 'Test'){
         
            emailDomains.add(ct.Email.split('@').get(1));

            } 
  
     else if (ct.Account.Name <> ct.Name__c && ct.Type__c <> 'Test' ){
          
                emailDomains001.add(ct.Email.split('@').get(1));

            }

        Map<String,Account> emailDomainToAccountMap = new Map<String,Account>();

        List<Account> acclist = [select Id, Name,Domain__c from Account where Domain__c <> null and Domain__c IN :emailDomains];
        List<Account> acclist1 = [select Id, Name,Domain__c from Account where Domain__c <> null and Domain__c IN :emailDomains001];

            
        if(!emailDomains.isEmpty() && (!emailDomains.contains('gmail.com') || !emailDomains.contains('yahoo.com') || !emailDomains.contains('outlook.com') || !emailDomains.contains('hotmail.com'))){
            
            for (Account a : acclist){
                emailDomainToAccountMap.put(a.Domain__c,a);
            }
        }
            
        }

 
  • May 16, 2018
  • Like
  • 0
I am trying to use a string search in SOQL. I am getting error saying 

System.QueryException: expecting a colon, found 'tempInput'
string tempInput = '%' + 'GH' + '%';

       String qryStr = 'SELECT Id, Name';
 		qryStr += ', Receipt__c';
        qryStr += ', Class__c,'; 
        qryStr += ' FROM Line__c';
        qryStr += ' WHERE Receipt__r.Posted__c = true';
        qryStr += ' AND Receipt__r.Description__c like tempInput' ;
        qryStr += ' AND Receipt__r.OPayment__c = null';

 
  • May 04, 2018
  • Like
  • 0
I am trying to change the Opportunity Line Item schedule when a custom field is changed. The schedule works fine when the field is eneterd, but when I edit the custom field it throws the exception

Here is the trigger and the class

Trigger
 
trigger OpportunityReScheduling on Opportunity (after update, before update, after insert) 
    {
        for (Opportunity o: Trigger.new)
        {
            if (Trigger.isBefore)
            {
                if(o.Category__c == 'Solutions'){
                Opportunity prevOpportunity = Trigger.oldMap.get(o.ID);
                    if(o.Effective_Date__c <> null){
                if (o.Effective_Date__c != prevOpportunity.Effective_Date__c) 
                {
                    Integer DayDiff = prevOpportunity.Effective_Date__c.daysBetween(o.Effective_Date__c);

                    OpportunitySchedulingHandler.ScheduleDateUpdate(o.id, DayDiff);
                }
            }
            }
            }
        }
    }

CLass
public with sharing class OpportunitySchedulingHandler {

     //Update LineItemSchedule dates for all scheduling dates

    public static void ScheduleDateUpdate(String oppid, Integer DayDiff) 
    {
       List<OpportunityLineItem> idval = [SELECT id FROM OpportunityLineItem WHERE OpportunityId=:oppid];
       List<OpportunityLineItemSchedule> datelist = new List<OpportunityLineItemSchedule>();
       for (Integer i = 0; i < idval.size(); i++)
       {
           datelist = [SELECT ScheduleDate FROM OpportunityLineItemSchedule WHERE OpportunityLineItemId =:idval[i].id];
           Date firstDate = datelist[0].ScheduleDate.addDays(DayDiff);
           datelist[0].ScheduleDate = firstDate;

           Integer day = firstDate.day();
           Integer month = firstDate.month();
           Integer year = firstDate.year();

           for (Integer k = 1; k < datelist.size(); k++)
           {
               Integer nYear = year;
               Integer nMonth = month + k;
               Integer nDay = day;

               if (nMonth > 12) {
                   nMonth = nMonth - 12;
                   nYear = nYear + 1;
               }

               Set<Integer> longMonths = new Set<Integer> {1,3,5,7,8,10,12};

               if (nDay == 31 && ! longMonths.contains(nMonth)) {
                   nDay = 30;
               }

               if (nDay > 28 && nMonth == 2) {
                   nDay = 28;
               }

               Date mydate = date.newInstance(nYear,nMonth,nDay);
               datelist[k].ScheduleDate = mydate;
           }
           if(!datelist.isEmpty())
           {
                update datelist;
           }
        }
    }    
}
I did try null check for list but that is messing up the schedules
  • March 27, 2018
  • Like
  • 0

I have a process builder which invokes the Apex class. This Apex sends out an email to the Contact. The attachment of the Email is a VF page which gets the list of line items.
The issue here is that I would like to capture the record id of the record invoked by Process Builder and pass it on all the way to the VF page.
Any sample code or ideas would greatly help
  • March 26, 2018
  • Like
  • 0
I have an Invoice Object which had a package of differerent line items. I ahve one line item which says credit which needs to be subtracted from the actual sale of product.

I have 2 issues with this
1. The credit line item is duplicated
2. The sale price is showing up as the total price after discounted on all the line items
 
<td class="text-center">

 <apex:outputField value="{!line.Sale_Price__c}" rendered="{!!line.Item__r.Ignore_Items _on_Inv__c}"/> 

<apex:outputText value="{0, number, $#,###,###.00}" rendered="{!line.Item__r.Ignore_Items_on_Inv__c}">

 <apex:param value="{!totalSalePricePackageItems}" />

 </apex:outputText> <apex:outputField value="{!line.Sale_Price__c}" rendered="{!line.Description__c =='Credit '}"/> 

<apex:outputText value="{0, number, $#,###,###.00}" rendered="{!line.Description__c == 'Credit'}"> <apex:param value ="{!totalPackageItem}"/>

 </apex:outputText> 
</td>
Controller
for(Line__c LineRec : LineList) { 

if(LineRec.Subtotal__c != null) 

FilteredSubTotal += LineRec.Subtotal__c;

 if (LineRec.Item__r.Ignore_tems_on_Inv__c) { 

if(LineRec.Description__c != 'Credit' && LineRec.Description__c != 'Solutions'){ 

tempInvoiceLineList.add(LineRec); totalSalePricePackageItems += LineRec.Sale_Price__c; 
} 

else if(LineRec.OrderApi__Line_Description__c == 'Solutions'){ tempInvoiceLineList.add(LineRec); 
totalSalePricePackageItems = LineRec.Sale_Price__c; 
} 

if (LineRec.Description__c == 'Credit ')
{
 if(LineRec.Sale_Price__c!= 0.00)
{ 
tempInvoiceLineList.add(LineRec); totalPackageItem = LineRec.Sale_Price__c; 
} } } }
​​

 
  • March 22, 2018
  • Like
  • 0
I am trying to insert portal user records and receiving this error


System.DmlException: Insert failed. First exception on row 0; first error: PORTAL_USER_ALREADY_EXISTS_FOR_CONTACT, portal user already exists for contact: []

Here is the code
 
@IsTest static void testRegFormWithNewUserAddress11() {
    
             
        Contact con = new Contact();
          con.Firstname = 'test';
          con.LastName ='test';
         con.OtherPhone = '8765432167';
         con.Organization_Type__c = 'test';
          con.Email ='Sitetestg466@hotmail.com';
        insert con; 
             Order__c ordr = new Order__c();
          ordr.Contact__c = con.Id;
          ordr.Account__c = a.Id;
          insert ordr;
          
       Order_Line__c ordrline = new Order_Line__c();
          ordrline.Order__c = ordr.id;
          insert ordrline;
             
    ControllerTest controller = new ControllerTest();        
controller.con = con;
        controller.acc = a;

       	controller.Password= 'testpass123';
        controller.checkIfContactExists();
        controller.checkIfAccountExists();
          
         controller.setTab();
 
          
             Profile p = [select Name, id From Profile where UserLicense.Name like '%Customer Community%' limit 1];
      
    		
           User u = new User ();
          u.FirstName = 'test';
          u.LastName ='test';
          u.Email ='testemail'+Math.round(Math.random()*Math.pow(10, 7))+'@testemail.com';
          u.Username = 'testemail'+Math.round(Math.random()*Math.pow(10, 8))+'@testemai.com';
          u.Alias ='test';
          u.CommunityNickname ='tst';
          u.ContactId =con.Id;
          u.LanguageLocaleKey = 'en_US';
                    u.LocaleSidKey ='en_CA';
                    u.TimeZoneSidKey ='America/Chicago';
         			u.ProfileId = p.Id;
                    u.EmailEncodingKey = 'UTF-8';
                 insert u; 
         
   
     }

The Controller code is below
 
List<User> existalready = [select id,Contact.FirstName,Username,Contact.LastName from user where username =:Email and IsActive = true LIMIT 1];
                if(existalready.size()<0){
                    for(User u: existalready){
insert u ;
insert con;

Can someone help in this scenario​
  • March 09, 2018
  • Like
  • 0
I am writing a batch class to send the emails based on certian criteria. I see that the parameters are passed right, no errors, but I end up receiving multiple duplicate emails when I run it. Here is the code

Two issues that I am trying to resolve

1. When there are less than 10 emails to be sent out, the code works fine, but sends duplicate emails
2. When there are more than more than 10 emails in the list that I am sending to, I get an error saying 'FATAL_ERROR|System.LimitException: Too many Email Invocations: 11'
 
global void execute(Database.BatchableContext BC, List<OrderApi__Badge__c> scope){
     
		system.debug('scope'+scope.size());  
     for(Order_c fbdge : [select Id,Description__c,Type__c,Contact__c,
 			ontact__r.Date__c,Contact__r.FirstName,Contact__r.LastName,
        	Contact__r.Years__c,Contact__r.Email,Active__c,Type__r.Name
From Order__c where (Type__r.Name ='A' or Type__r.Name ='B') and OrderApi__Is_Active__c =true 
                                and Date__c = 2017-06-30
        			  			and Contact__r.Date__c = 2017-06-30 and Contact__r.Years__c<10.00
                                and (Contact__r.Cat__c <> ' Life')]){
                                          system.debug('create list');
                                     bge.add(fbdge);
                                     system.debug('Bge' +bge.add(fbdge));
                                     contact.put(fbdge.Contact__c, fbdge.Contact__r.Email);
                                  
                                      }
     if(contact.size()>0){
         
     			 List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();
                                 List<String> email = new List<String>();
                                 List<String> ccemail = new List<String>();
          Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage(); 	
         try{
             for(Id ids : contact.keyset()){

          email.clear();
                 for(Order__c bdg :[select id,Contact__r.Email from Order__c where Contact__r.Email=:contact.get(ids) LIMIT 1]){
                     email.add(bdg.Contact__r.Email);
                     system.debug('size of emails' +email.size());
                 }
                                                                           
    Contact c = [select id, Email from Contact where email <> null limit 1];
     							
     EmailTemplate templateId = [Select id from EmailTemplate where name = 'Test'];
                                                            
                                            system.debug(email);
                                            system.debug(email.size());
                                            mail.setToAddresses(email);
                                            mail.setccAddresses(ccemail);
                                       
                                           	mail.setTargetObjectId(c.Id);
           									mail.setTreatTargetObjectAsRecipient(false);
                                           	mail.setTemplateID(templateId.Id); 
                                            mail.setSaveAsActivity(false); 
                                            mails.add(mail);
                                            system.debug(mail);
                         
     							//	messages.add(mail);
    if(mails.size())>0{                        
     Messaging.sendEmail(mails);
        						system.debug('mails');
        system.debug(mails.size());
           
 }        
}         
         } catch(exception ex){
             system.debug('Exception occured'+ex.getMessage());
         }
     }
 }
 global void finish(Database.BatchableContext BC){
    }
}

 
  • February 16, 2018
  • Like
  • 0
Hi I have a batch class below. Upon executing I found the following execution error. Can anyone help me with this?
List<Orde__cr> ordr = new List<Order__c>();
 global void execute(Database.BatchableContext BC, List<Order__c> scope){
     
		system.debug('scope'+scope.size());  
     List<Order__c> fbdge = [select Id,Description__c,Type__c,Contact__c,
 			Contact__r.Expiration_Date__c,Contact__r.FirstName,Contact__r.LastName,
        	Contact__r.Years__c,OrderApi__Contact__r.Email
   From Order__c where (Type__r.Name ='AAA' or Type__r.Name ='BBB') and Active__c =true];
        			
     if (fbdge!=null){
 
        
for(Order__c bd: fbdge)
{
    
 if(bd.Contact__r.Years__c>=10.00 && (bd.Contact__r.Expiration_Date__c<=Date.newInstance( 2017, 6, 30 )) ){  
   						 
     			 List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();
                                 List<String> email = new List<String>();
                                 List<String> ccemail = new List<String>();                                 
                              
   			 Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
     						
     							email.add(bd.Contact__r.Email);
    							 Contact c = [select id, Email from Contact where email <> null limit 1];
     							
     EmailTemplate templateId = [Select id from EmailTemplate where name = 'Test1'];
    
                                            mail.setToAddresses(email);
                                          
                                           	mail.setTargetObjectId(c.Id);
           									mail.setTreatTargetObjectAsRecipient(false);
                                           	mail.setTemplateID(templateId.Id); 
                                            mail.setSaveAsActivity(false); 
                                            mails.add(mail);
                                            system.debug(mail);
									
     Messaging.sendEmail(mails);
        						system.debug('mails');
        system.debug(mails.size());
                                
 } else if (bd.Contact__r.Years__c>10 && (bd.Contact__r.Expiration_Date__c<=Date.newInstance( 2017, 6, 30 )) ){
       
     							email.add(bd.Contact__r.Email);
                                
    							 Contact c = [select id, Email from Contact where email <> null limit 1];
     	
     EmailTemplate templateId = [Select id from EmailTemplate where name = 'Test2'];
     
                                            mail.setToAddresses(email);
                                            mail.setccAddresses(ccemail);
                                          
                                           	mail.setTargetObjectId(c.Id);
           									mail.setTreatTargetObjectAsRecipient(false);
                                           	mail.setTemplateID(templateId.Id); 
                                            mail.setSaveAsActivity(false); 
                                            mails.add(mail);
                                            system.debug(mail);

                            
 } else if (bd.Contact__r.Years__c<10 && (bd.Contact__r.Expiration_Date__c > Date.newInstance( 2017, 6, 30 )) ){
    

     							email.add(bd.Contact__r.Email);
                                
    							 Contact c = [select id, Email from Contact where email <> null limit 1];
     
     EmailTemplate templateId = [Select id from EmailTemplate where name = 'Test3'];
     
                                            mail.setToAddresses(email);
                                          
                                          
                                           	mail.setTargetObjectId(c.Id);
           									mail.setTreatTargetObjectAsRecipient(false);
                                           	mail.setTemplateID(templateId.Id); 
                                            mail.setSaveAsActivity(false); 
                                            mails.add(mail);
                                          
 

                                
 }
     Messaging.sendEmail(mails);
        						system.debug('mails');
        system.debug(mails.size());
     }

 
  • February 14, 2018
  • Like
  • 0
Hi,

I have the Opportunity record which has a date and frequency fields. I would like to insert child records based on the frequency.

For example: If the stage is Closed/Signed and if the frequncy is 24 Months starting from a date field, I would like to have 24 child records to be inserted based on the start date and amount be distributed accordingly

ANy sample code on how I acheive this?
  • February 05, 2018
  • Like
  • 0
Hi,

I am using the lightning:inputrichtext, but nable to get thye layout as I am looking for
<lightning:inputRichText class="slds-input" aura:id="nam" value="{!v.orr.Message__c}" />
Here is the layout that I am looking for. The Font Family will have list of fonts and the Words should give the count of characters. Can someone help me on this 
User-added image
  • January 23, 2018
  • Like
  • 0
I am having fits with lightning aura iteration, it doesn't do anything just puts in a blank row, no errors .Having zero luck here is my lightning component
Component:
 
<table class="slds-table slds-table--bordered slds-table--cell-buffer">

                            <tr class="slds-text-title--caps">
                            <th scope ="col">
                                <div class="slds-truncate" title="Cart">Cart</div>
                            </th>
                            <th scope="col">
                                <div class="slds-truncate" title="QT">QT</div>
                            </th>
                            <th scope="col">
                                <div class="slds-truncate" title=""></div>
                            </th>
                        </tr>

                    <tbody>
                            <aura:iteration items="{!v.orderItemList}" var="ct">

                                    <tr>
                                <th scope="row" data-label="Cart">
                                    <div class="slds-truncate" title="{!ct.Description__c}">{!ct.Description__c }</div>
                                </th>
                                <td data-label="QTY">
                                    <div class="slds-truncate" title="{!ct.Quantity__c}">{!ct.Quantity__c}</div>
                                </td>
                                <td data-label="">
                                    <div class="slds-truncate" title="{!ct.Price__c}">{!ct.Price__c}</div>
                                </td>
                            </tr>  
                        </aura:iteration>
                    </tbody>
                        </table>
Here is the JS:
 
({
    doInit : function(component, event, helper) {
        var action = component.get("c.getOrder");
        action.setParams({
            "recordId":component.get("v.recordId")
            //"recordId":"8010K0000026d6Y"

        });

        action.setCallback(this,function(response){

            var state = response.getState();
            if(state === "SUCCESS"){
               component.set("v.order",response.getReturnValue()); 
               console.log(response.getReturnValue());

            }
        });

        $A.enqueueAction(action);

    },

    sendE : function(component, event, helper) {

        var email = component.get("v.order.Email__c");
        var subject = component.get("v.order.Subject__c");
        var action2 = component.get("c.sendEmail");
        var getallitems = component.get("c.orderItem")['ct'];
        var ItemList =[];

        for (var key in getallitems){
           ItemList.push(key+ '=' +getallitems[key]); 
        }
        component.set("v.ItemList", orderItemList);
        console.log(orderItemList);
        action2.setParams({

            "email":email,
            "rId":component.get("v.recordId"),
            "subject":subject

        });
        action2.setCallback(this,function(res){

            var state = res.getState();
            if(state === "SUCCESS"){
                alert("win");
               //component.set("v.order",response.getReturnValue()); 
               console.log(res.getReturnValue());

            }
            else{

                console.log("failed");
            }
        });
        $A.enqueueAction(action2);

    }


})
Controller:
 
public  static Line__c orderItem {get;set;}
     @AuraEnabled
    public static Line__c getOrderLines(string recordId) {
     orderItem = [select Id,Quantity__c,Price__c,Price__c,
                 Description__c,Order__r.Total__c
                 from Line__c where Order__c=:recordId];
        system.debug('Order rows'+orderItem);
        return orderItem;   
    }



 
  • January 22, 2018
  • Like
  • 0
Hi,

I have a lightning component which invokes from a visualforce page, which inturn gets triggered on click of a button. Now, the issue is I see that the loading screen doesnt stop but does invoke the component too

Here is the code 
<apex:page standardController="Order__c" standardStylesheets="false" sidebar="false">
     <apex:includeLightning />
 <link rel="stylesheet" media="screen" href="{!URLFOR($Resource.Framework__SDLS_Base,'css/styles.css')}"/>
<div id="lightning" />
    <div class="slds slds-loading-layout" id="mainWrapper1">
        <div class="slds-grid slds-loading-layout slds-theme--shade">
            <div class="slds-col slds-text-align--center slds-align-middle" >
              <img src="{!URLFOR($Resource.Framework__SLDS_Base,'/img/spinners/slds_spinner_brand.gif')}" alt="saving" width="50" height="50" />&nbsp;
                <span class="slds-text-heading--medium">Loading...</span>
            </div>
        </div>
    </div>
    <!-- <apex:slds /> -->
    
 <script>
    function componentLoaded() {
          document.getElementById('mainWrapper12').classList.add('hidden');
  }
 $Lightning.use("c:OrderApp", function() {
 $Lightning.createComponent("c:Order",
 { 
 "recordId" : "{!$CurrentPage.parameters.Id}",
  },
 "lightning",
 function(cmp) {
 console.log('Component created, do something cool here');
     $A.eventService.addHandler({ "event": "ComponentLoadedEvent", "handler" : componentLoaded});
 });
 });
 </script>
 
</apex:page>
On click of button, the VF page is called and the loading screen shows up for a fraction of sec, then the lightning component fields show up and the loading moves to the bottom. How do I make sure that the loading stops before component starts?
loading screencomponent and loading
  • January 17, 2018
  • Like
  • 0
I have apex:commandbutton with action called to a method of controller. This VF page is being invoked by a different JS which autopopulates VF page, I see that the apex:commandbutton sets action refurl as the same VF page. How do i remove that?
<form id="p_id1:j_id10" name="p_id1:j_id11" method="post" action="https://force.com/Test?refURL=http%10A%10F%10Fforce.com%2FTest"

 
  • January 08, 2018
  • Like
  • 0
I have a VF page on site where I am creating a user and a contact. Upon logging the user in, I wanted the user to be re-directed to an external website instead of site page

I did try this code
 
PageReference pf = Site.login(u.username,password,'custom_login?startURL=%2Fidp%2Flogin%3Fapp%4D0spo000120005Dkg');
                return pf;
          PageReference redirectPage = new PageReference('https%1A%1D%1test.com%1Finteg%1Fsso%1Fgfd.aspx%30%37');
            return redirectPage;

I also tried using start url with ref url as parameter too, but either of them did not work.
Thoughts on this 
  • January 08, 2018
  • Like
  • 0
I have a lookup relationship between Order Line and Contact Objects where Contact is the parent. I am writing a batch class which looks for certain criteria on Order Line and send email to Contacts excluding the duplicates. 

Right now I have  2 duplicate Order Lines for the Contact and the batch is supposed to send 1 email. But in this code, there are 3 emails sent out. Can someone help with this?
 
global class BatchSendEmails implements Database.Batchable<SObject>
{
global Database.QueryLocator start(Database.BatchableContext BC){
	return Database.getQueryLocator([select id,Contact__r.Email,Contact__c,Account__c from Order_Line__c 
                                     where Order__r.OrderApi__Date__c = LAST_N_DAYS:3]);
}
      
    global void execute (Database.BatchableContext BC, List<Order_Line__c> scope){
         List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();
                                 List<String> email = new List<String>(); 
      
       List<Order_Line__c> sollist = [SELECT Id, Item__c, Contact__c,Order__c ,Contact__r.Email FROM Order_Line__c
        WHERE Order__r.Date__c = LAST_N_DAYS:3 AND Item__r.Name = 'Test'];
       
        Set<Id> solids = new Set<Id>();
        for(Order_Line__c ol : ollist){
            if(ol.id != null){
               olids.add(ol.Contact__c);
                system.debug('Added Contacts'+olids);
            }
        }
        
        AggregateResult[] groupedResults = [
        SELECT COUNT(Id) dups, Item__c, Contact__c,Order__c,Contact__r.Email
        FROM Order_Line__c
        WHERE Contact__c =:solids and Sales_Order__r.Date__c = LAST_N_DAYS:3 
        AND Item__r.Name = 'Test'    
        GROUP BY Item__c,Contact__c,Contact__r.Email,Order__c
         HAVING COUNT(Id) = 1];

        for(AggregateResult ar:groupedResults){
            String custid = (ID)ar.get('OrderApi__Contact__c');
            
          //	email.add(custid);
            
        List<Order_Line__c> sollist1 = [select id, Contact__r.Email,Order__c from Order_Line__c where id=: ar.Id limit 1];
            email.clear();
                email.add(ollist[0].OrderApi__Contact__r.Email); */
                                 List<String> ccemail = new List<String>();                                 
                                 ccemail.add('test@test.com');
    							 Contact c = [select id, Email from Contact where email <> null limit 1];
            try{                             
EmailTemplate templateId = [Select id from EmailTemplate where name = 'Email'];                                                   
                    system.debug(email);
                Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
                 OrgWideEmailAddress owa = [select id, DisplayName, Address from OrgWideEmailAddress where address = 'testing@test.org' limit 1];
                                            system.debug(email.size());
                                            mail.setToAddresses(email);
                                            mail.setccAddresses(ccemail);
                                            mail.setOrgWideEmailAddressId(owa.id);
                                            mail.setTargetObjectId(c.Id);
           									mail.setTreatTargetObjectAsRecipient(false);
                                            mail.setTemplateID(templateId.Id); 
                                            mail.setSaveAsActivity(false); 
                                            mails.add(mail);
                                            system.debug(mail);
											
                          
                                 Messaging.sendEmail(mails);
            }catch(Exception e){
                system.debug('Exception occured' +e);
            }
                
    }
    }
        
    global void finish(Database.BatchableContext BC){
        
    }
}

 
  • November 28, 2018
  • Like
  • 1
I have an apex class which looks for the old and new values of contacthistory. I am writing a test class for this, but could not write data to Oldvalue and Newvalue. I also tried updating the field which is tracked in history, but that gives null value when I tried assert statement. Here is my class
for(ContactHistory ct: scope){ if((ct.NewValue =='Test Data' && ct.OldValue =='Old Data')|| (ct.NewValue == 'New Test Data' && ct.OldValue =='Old Data Listing'){ //do something }}


How do I cover this if condition?
Here is my test class:
Test.startTest();
 Contact c = new contact(lastname = 'test', email='email@email.com'); 
c.TrackedField__c ='OldData'; 
c.AccountId = acc.Id; 
insert c; 
c.TrackedField__c ='Test Data';
 update c; 
Test.stopTest(); 
ContactHostory ch =[select contactid, OldValue, NewValue from ContactHistory where ContactId=: c.id and Field ='TrackedField__c' limit1];   //this is returning zero results

 
  • August 28, 2019
  • Like
  • 0
I am unable to insert opportunity line item schedule record in the test class. Can anyone let me know the fields and criteria for inserting schedule record in test class
 
  • May 20, 2018
  • Like
  • 0
I have a Batch Class where I am looking for Contact matches to Account and would like to update Contact with associating Account.

How do I write update outside the loop? I want to update the Account in the map to the contact from initial loop

Here is the code
 
Set<String> emailDomains = new Set<String>();
 Set<String> emailDomains001 = new Set<String>();
        Set<Id> ctId = new Set<Id>();

    List<Contact> ctlist = [select Id, FirstName,LastName,Email,Business_Name__c,Member_Type__c from Contact where Email <> null and LastModifiedDate = N_DAYS_AGO:5];    

        for (Contact ct : ctlist){
     
     if(ct.Type__c == 'Test'){
                ct.AccountId = '0015467Dvbg';
                update ct;
            }
     else if(ct.Account.Name == ct.Name__c && ct.Type__c <> 'Test'){
         
            emailDomains.add(ct.Email.split('@').get(1));

            } 
  
     else if (ct.Account.Name <> ct.Name__c && ct.Type__c <> 'Test' ){
          
                emailDomains001.add(ct.Email.split('@').get(1));

            }

        Map<String,Account> emailDomainToAccountMap = new Map<String,Account>();

        List<Account> acclist = [select Id, Name,Domain__c from Account where Domain__c <> null and Domain__c IN :emailDomains];
        List<Account> acclist1 = [select Id, Name,Domain__c from Account where Domain__c <> null and Domain__c IN :emailDomains001];

            
        if(!emailDomains.isEmpty() && (!emailDomains.contains('gmail.com') || !emailDomains.contains('yahoo.com') || !emailDomains.contains('outlook.com') || !emailDomains.contains('hotmail.com'))){
            
            for (Account a : acclist){
                emailDomainToAccountMap.put(a.Domain__c,a);
            }
        }
            
        }

 
  • May 16, 2018
  • Like
  • 0

I have a process builder which invokes the Apex class. This Apex sends out an email to the Contact. The attachment of the Email is a VF page which gets the list of line items.
The issue here is that I would like to capture the record id of the record invoked by Process Builder and pass it on all the way to the VF page.
Any sample code or ideas would greatly help
  • March 26, 2018
  • Like
  • 0
I am trying to insert portal user records and receiving this error


System.DmlException: Insert failed. First exception on row 0; first error: PORTAL_USER_ALREADY_EXISTS_FOR_CONTACT, portal user already exists for contact: []

Here is the code
 
@IsTest static void testRegFormWithNewUserAddress11() {
    
             
        Contact con = new Contact();
          con.Firstname = 'test';
          con.LastName ='test';
         con.OtherPhone = '8765432167';
         con.Organization_Type__c = 'test';
          con.Email ='Sitetestg466@hotmail.com';
        insert con; 
             Order__c ordr = new Order__c();
          ordr.Contact__c = con.Id;
          ordr.Account__c = a.Id;
          insert ordr;
          
       Order_Line__c ordrline = new Order_Line__c();
          ordrline.Order__c = ordr.id;
          insert ordrline;
             
    ControllerTest controller = new ControllerTest();        
controller.con = con;
        controller.acc = a;

       	controller.Password= 'testpass123';
        controller.checkIfContactExists();
        controller.checkIfAccountExists();
          
         controller.setTab();
 
          
             Profile p = [select Name, id From Profile where UserLicense.Name like '%Customer Community%' limit 1];
      
    		
           User u = new User ();
          u.FirstName = 'test';
          u.LastName ='test';
          u.Email ='testemail'+Math.round(Math.random()*Math.pow(10, 7))+'@testemail.com';
          u.Username = 'testemail'+Math.round(Math.random()*Math.pow(10, 8))+'@testemai.com';
          u.Alias ='test';
          u.CommunityNickname ='tst';
          u.ContactId =con.Id;
          u.LanguageLocaleKey = 'en_US';
                    u.LocaleSidKey ='en_CA';
                    u.TimeZoneSidKey ='America/Chicago';
         			u.ProfileId = p.Id;
                    u.EmailEncodingKey = 'UTF-8';
                 insert u; 
         
   
     }

The Controller code is below
 
List<User> existalready = [select id,Contact.FirstName,Username,Contact.LastName from user where username =:Email and IsActive = true LIMIT 1];
                if(existalready.size()<0){
                    for(User u: existalready){
insert u ;
insert con;

Can someone help in this scenario​
  • March 09, 2018
  • Like
  • 0
I am writing a batch class to send the emails based on certian criteria. I see that the parameters are passed right, no errors, but I end up receiving multiple duplicate emails when I run it. Here is the code

Two issues that I am trying to resolve

1. When there are less than 10 emails to be sent out, the code works fine, but sends duplicate emails
2. When there are more than more than 10 emails in the list that I am sending to, I get an error saying 'FATAL_ERROR|System.LimitException: Too many Email Invocations: 11'
 
global void execute(Database.BatchableContext BC, List<OrderApi__Badge__c> scope){
     
		system.debug('scope'+scope.size());  
     for(Order_c fbdge : [select Id,Description__c,Type__c,Contact__c,
 			ontact__r.Date__c,Contact__r.FirstName,Contact__r.LastName,
        	Contact__r.Years__c,Contact__r.Email,Active__c,Type__r.Name
From Order__c where (Type__r.Name ='A' or Type__r.Name ='B') and OrderApi__Is_Active__c =true 
                                and Date__c = 2017-06-30
        			  			and Contact__r.Date__c = 2017-06-30 and Contact__r.Years__c<10.00
                                and (Contact__r.Cat__c <> ' Life')]){
                                          system.debug('create list');
                                     bge.add(fbdge);
                                     system.debug('Bge' +bge.add(fbdge));
                                     contact.put(fbdge.Contact__c, fbdge.Contact__r.Email);
                                  
                                      }
     if(contact.size()>0){
         
     			 List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();
                                 List<String> email = new List<String>();
                                 List<String> ccemail = new List<String>();
          Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage(); 	
         try{
             for(Id ids : contact.keyset()){

          email.clear();
                 for(Order__c bdg :[select id,Contact__r.Email from Order__c where Contact__r.Email=:contact.get(ids) LIMIT 1]){
                     email.add(bdg.Contact__r.Email);
                     system.debug('size of emails' +email.size());
                 }
                                                                           
    Contact c = [select id, Email from Contact where email <> null limit 1];
     							
     EmailTemplate templateId = [Select id from EmailTemplate where name = 'Test'];
                                                            
                                            system.debug(email);
                                            system.debug(email.size());
                                            mail.setToAddresses(email);
                                            mail.setccAddresses(ccemail);
                                       
                                           	mail.setTargetObjectId(c.Id);
           									mail.setTreatTargetObjectAsRecipient(false);
                                           	mail.setTemplateID(templateId.Id); 
                                            mail.setSaveAsActivity(false); 
                                            mails.add(mail);
                                            system.debug(mail);
                         
     							//	messages.add(mail);
    if(mails.size())>0{                        
     Messaging.sendEmail(mails);
        						system.debug('mails');
        system.debug(mails.size());
           
 }        
}         
         } catch(exception ex){
             system.debug('Exception occured'+ex.getMessage());
         }
     }
 }
 global void finish(Database.BatchableContext BC){
    }
}

 
  • February 16, 2018
  • Like
  • 0
Hi I have a batch class below. Upon executing I found the following execution error. Can anyone help me with this?
List<Orde__cr> ordr = new List<Order__c>();
 global void execute(Database.BatchableContext BC, List<Order__c> scope){
     
		system.debug('scope'+scope.size());  
     List<Order__c> fbdge = [select Id,Description__c,Type__c,Contact__c,
 			Contact__r.Expiration_Date__c,Contact__r.FirstName,Contact__r.LastName,
        	Contact__r.Years__c,OrderApi__Contact__r.Email
   From Order__c where (Type__r.Name ='AAA' or Type__r.Name ='BBB') and Active__c =true];
        			
     if (fbdge!=null){
 
        
for(Order__c bd: fbdge)
{
    
 if(bd.Contact__r.Years__c>=10.00 && (bd.Contact__r.Expiration_Date__c<=Date.newInstance( 2017, 6, 30 )) ){  
   						 
     			 List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();
                                 List<String> email = new List<String>();
                                 List<String> ccemail = new List<String>();                                 
                              
   			 Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
     						
     							email.add(bd.Contact__r.Email);
    							 Contact c = [select id, Email from Contact where email <> null limit 1];
     							
     EmailTemplate templateId = [Select id from EmailTemplate where name = 'Test1'];
    
                                            mail.setToAddresses(email);
                                          
                                           	mail.setTargetObjectId(c.Id);
           									mail.setTreatTargetObjectAsRecipient(false);
                                           	mail.setTemplateID(templateId.Id); 
                                            mail.setSaveAsActivity(false); 
                                            mails.add(mail);
                                            system.debug(mail);
									
     Messaging.sendEmail(mails);
        						system.debug('mails');
        system.debug(mails.size());
                                
 } else if (bd.Contact__r.Years__c>10 && (bd.Contact__r.Expiration_Date__c<=Date.newInstance( 2017, 6, 30 )) ){
       
     							email.add(bd.Contact__r.Email);
                                
    							 Contact c = [select id, Email from Contact where email <> null limit 1];
     	
     EmailTemplate templateId = [Select id from EmailTemplate where name = 'Test2'];
     
                                            mail.setToAddresses(email);
                                            mail.setccAddresses(ccemail);
                                          
                                           	mail.setTargetObjectId(c.Id);
           									mail.setTreatTargetObjectAsRecipient(false);
                                           	mail.setTemplateID(templateId.Id); 
                                            mail.setSaveAsActivity(false); 
                                            mails.add(mail);
                                            system.debug(mail);

                            
 } else if (bd.Contact__r.Years__c<10 && (bd.Contact__r.Expiration_Date__c > Date.newInstance( 2017, 6, 30 )) ){
    

     							email.add(bd.Contact__r.Email);
                                
    							 Contact c = [select id, Email from Contact where email <> null limit 1];
     
     EmailTemplate templateId = [Select id from EmailTemplate where name = 'Test3'];
     
                                            mail.setToAddresses(email);
                                          
                                          
                                           	mail.setTargetObjectId(c.Id);
           									mail.setTreatTargetObjectAsRecipient(false);
                                           	mail.setTemplateID(templateId.Id); 
                                            mail.setSaveAsActivity(false); 
                                            mails.add(mail);
                                          
 

                                
 }
     Messaging.sendEmail(mails);
        						system.debug('mails');
        system.debug(mails.size());
     }

 
  • February 14, 2018
  • Like
  • 0
Hi,

I am using the lightning:inputrichtext, but nable to get thye layout as I am looking for
<lightning:inputRichText class="slds-input" aura:id="nam" value="{!v.orr.Message__c}" />
Here is the layout that I am looking for. The Font Family will have list of fonts and the Words should give the count of characters. Can someone help me on this 
User-added image
  • January 23, 2018
  • Like
  • 0
I am having fits with lightning aura iteration, it doesn't do anything just puts in a blank row, no errors .Having zero luck here is my lightning component
Component:
 
<table class="slds-table slds-table--bordered slds-table--cell-buffer">

                            <tr class="slds-text-title--caps">
                            <th scope ="col">
                                <div class="slds-truncate" title="Cart">Cart</div>
                            </th>
                            <th scope="col">
                                <div class="slds-truncate" title="QT">QT</div>
                            </th>
                            <th scope="col">
                                <div class="slds-truncate" title=""></div>
                            </th>
                        </tr>

                    <tbody>
                            <aura:iteration items="{!v.orderItemList}" var="ct">

                                    <tr>
                                <th scope="row" data-label="Cart">
                                    <div class="slds-truncate" title="{!ct.Description__c}">{!ct.Description__c }</div>
                                </th>
                                <td data-label="QTY">
                                    <div class="slds-truncate" title="{!ct.Quantity__c}">{!ct.Quantity__c}</div>
                                </td>
                                <td data-label="">
                                    <div class="slds-truncate" title="{!ct.Price__c}">{!ct.Price__c}</div>
                                </td>
                            </tr>  
                        </aura:iteration>
                    </tbody>
                        </table>
Here is the JS:
 
({
    doInit : function(component, event, helper) {
        var action = component.get("c.getOrder");
        action.setParams({
            "recordId":component.get("v.recordId")
            //"recordId":"8010K0000026d6Y"

        });

        action.setCallback(this,function(response){

            var state = response.getState();
            if(state === "SUCCESS"){
               component.set("v.order",response.getReturnValue()); 
               console.log(response.getReturnValue());

            }
        });

        $A.enqueueAction(action);

    },

    sendE : function(component, event, helper) {

        var email = component.get("v.order.Email__c");
        var subject = component.get("v.order.Subject__c");
        var action2 = component.get("c.sendEmail");
        var getallitems = component.get("c.orderItem")['ct'];
        var ItemList =[];

        for (var key in getallitems){
           ItemList.push(key+ '=' +getallitems[key]); 
        }
        component.set("v.ItemList", orderItemList);
        console.log(orderItemList);
        action2.setParams({

            "email":email,
            "rId":component.get("v.recordId"),
            "subject":subject

        });
        action2.setCallback(this,function(res){

            var state = res.getState();
            if(state === "SUCCESS"){
                alert("win");
               //component.set("v.order",response.getReturnValue()); 
               console.log(res.getReturnValue());

            }
            else{

                console.log("failed");
            }
        });
        $A.enqueueAction(action2);

    }


})
Controller:
 
public  static Line__c orderItem {get;set;}
     @AuraEnabled
    public static Line__c getOrderLines(string recordId) {
     orderItem = [select Id,Quantity__c,Price__c,Price__c,
                 Description__c,Order__r.Total__c
                 from Line__c where Order__c=:recordId];
        system.debug('Order rows'+orderItem);
        return orderItem;   
    }



 
  • January 22, 2018
  • Like
  • 0