• PawanKumar
  • PRO
  • 2095 Points
  • Member since 2013


  • Chatter
    Feed
  • 68
    Best Answers
  • 0
    Likes Received
  • 2
    Likes Given
  • 3
    Questions
  • 440
    Replies

I'm doing an upload attachment to AWS, but I'm getting this error -- 'You have uncommitted work pending. Please commit or rollback before calling out'
How do I fix this?

@AuraEnabled
    public static void savePDupcsSettings(ForUploadCustomSettings__c upcsSet, String recId){
        ForUploadCustomSettings__c upcs = new ForUploadCustomSettings__c();
        upcs = upcsSet;
        if (upcs.Objects__c != null) {
			if (recordId != null) {
                upcs.Name = upcs.Objects__c +'-'+ upcs.Fields__c +'-'+ upcs.Value__c;
			    update upcs;
            } else {
                ForUploadCustomSettings__c newVal = new ForUploadCustomSettings__c();
                newVal.Name = upcs.Objects__c +'-'+ upcs.Fields__c +'-'+ upcs.Value__c;
                newVal.Objects__c = upcs.Objects__c;
                newVal.Fields__c = upcs.Fields__c;
                newVal.Value__c = upcs.Value__c;
                insert newVal;
            }
        }
        
        String stage = 'Closed Won';
        ForUploadCustomSettings__c csList = [SELECT Id, Id, Objects__c, Fields__c, Value__c 
                                                              FROM ForUploadCustomSettings__c 
                                                              WHERE Value__c = :stage LIMIT 1];
        if (csList != null) {
            Set<Id> Ids = new Set<Id>();
			for (Opportunity opp : [SELECT Id, Name FROM Opportunity WHERE IsClosed = true AND IsWon = true]) {
				Ids.add(opp.Id);
			}

			String formattedDateString = Datetime.now().format('EEE, dd MMM yyyy HH:mm:ss z');   
			String host = 's3.amazonaws.com/';
			String method = 'PUT';
			
			HttpRequest req = new HttpRequest();
			Http http = new Http();

			List<Attachment> att = [SELECT Id, Name, Body, ContentType FROM Attachment WHERE ParentId IN :Ids];
			List<AWScredentialsSettings__c> creds = [SELECT Id, ClientKey__c, SecretKey__c, BucketName__c FROM AWScredentialsSettings__c LIMIT 1];
			if (!att.isEmpty() && !creds.isEmpty()) {
				String bucketname = creds[0].BucketName__c;
				String key = creds[0].ClientKey__c;
				String secret = creds[0].SecretKey__c;
				String attachmentBody = EncodingUtil.base64Encode(att[0].Body);
				String filename = att[0].Name;
				
				req.setMethod(method);
				req.setEndpoint('https://' + host + bucketname + '/' + filename); // The file should be uploaded to this path in AWS -- Opportunity/Salesforce Id/Secret Files/filename
				req.setHeader('Content-Length', String.valueOf(attachmentBody.length()));
				req.setHeader('Content-Encoding', 'UTF-8');
				req.setHeader('Content-type', att[0].ContentType);
				req.setHeader('Connection', 'keep-alive');
				req.setHeader('Date', formattedDateString);
				req.setHeader('ACL', 'public-read');
				req.setBody(attachmentBody);
				
				String stringToSign = method+'\n\n\n'+ att[0].ContentType + '\n' + formattedDateString +'\n/'+ bucketname +'/' + filename;
				Blob mac = Crypto.generateMac('HMACSHA1', blob.valueof(stringToSign),blob.valueof(secret));
				String signed  = EncodingUtil.base64Encode(mac);
				String authHeader = 'AWS' + ' ' + secret + ':' + signed;
				req.setHeader('Authorization',authHeader);
			}
			
			HTTPResponse res = http.send(req);
			System.debug('*Resp:' + String.ValueOF(res.getBody()));
			System.debug('RESPONSE STRING: ' + res.toString());
			System.debug('RESPONSE STATUS: ' + res.getStatus());
			System.debug('STATUS_CODE: ' + res.getStatusCode());
        }
    }
trigger UpdateType on Account (before insert,before update,after insert) {
if(trigger.isInsert && trigger.isBefore)
{
for(Account a:trigger.new)
{
if(a.industry=='education')
{
a.addError('we dont deal with education industry');
}
}
}
if(trigger.isUpdate)
{
for(Account a:trigger.new)
{
if(a.Type=='Prospect')
{
a.Type='Other';
}
}
}
}
@isTest
public class UpdateTypeTest {
static testmethod void accUpdate()
{
   Account acc= new Account( Name='Example', Industry='Education');
    insert acc;
    acc=[select name, industry, type from account where type=:acc.Type];
    System.assertEquals('Other', acc.Type);
    update acc;
   
    
}
}

Test class for the Trigger

Here the trigger fires whenever we give the type on account as prospect it would update it to 'Other'

My test class is covering only 60% of the code , somehow it is not covering the updated part. Can someone help me out?

My requirement is once all the records are updated using Batch, all the updated records should get synced with the external System using REST services.
I process insert to some tables:
public PageReference  checkoutPaypal()
    {
      try
      {
          List<AccountUser__c>  listacc =  [SELECT id,AccountId__c FROM AccountUser__c  WHERE  email__c=:email  LIMIT 1];
          AccountUser__c a=new AccountUser__c();
          Account acc=new Account();
          if(listacc.size()>0)
          {
              a=listacc.get(0);             
          }
          else
          {
              acc.Name=name;             
              insert acc;
              //save value ok    
             
              //           
              a.Name=name;
              a.AccountId__c=acc.Id;
              a.Email__c=email;
              a.Status__c=0;
              a.Password__c='0';
              insert a;            
           }
          
            
          Contact con=new Contact();
          con.LastName=name;
          con.Email=email;
          //con.Phone__c=phonenumber;
          con.AccountId=a.AccountId__c;
          insert con;
         
          //
          Contract hd=new Contract();
          hd.AccountId=a.AccountId__c;
          hd.StartDate=system.today();
          hd.ContractTerm=1;
          insert hd;
          
          Order od=new Order();
          od.AccountId=a.AccountId__c;
          od.ContractId=hd.Id; 
          od.EffectiveDate=system.today();
          insert od;
          Double itotalMoney=0;
          if(ids !='')
          {
            
              string searchquery='select ProductCode,Name,ImageName__c,(Select UnitPrice,Pricebook2.Name From PricebookEntries where IsActive=True  Order By UnitPrice ASC )  from Product2 where ProductCode in ('+SOQL_IDs+')'; 
              List<Product2>  MyProducts= Database.query(searchquery); 
              List<OrderItem> lsDetail=new List<OrderItem>();
              for(Integer i=0;i<MyProducts.size();i++)   
              {   
                  String code=MyProducts.get(i).ProductCode;
                  String sl=listCarts.get(code);
                  OrderItem ode=new OrderItem();
                  ode.OrderId=od.Id;
                  ode.Quantity=Double.valueOf(sl);
                  ode.UnitPrice=MyProducts.get(i).PricebookEntries.get(0).UnitPrice;
                  ode.Product2Id=MyProducts.get(i).Id;
                  lsDetail.Add(ode);
                  itotalMoney=itotalMoney+ ode.Quantity * ode.UnitPrice;
              }
              
               insert lsDetail;
          }
         
        
         Pagereference redirectedPage = New PageReference('/apex/payment?amount='+itotalMoney);  
         return redirectedPage;
      }
      catch(DmlException e)
      {
          err=e.getMessage();
      }
      
       return null;
      
    }
Current if function occur error, some process still insert data ok.
I want rollback all, if occur error/
How can rollback database in apex?
Hello!

I am developing automation to create SBQQ quotes and opportunities in order to eventually create contracts, etc... One step of the automation tries to contract the opportunity. When calling, I notice that I am getting the following error. The contract is produced but I am not getting a renewal opportunity created. Any help would be greatly appreciated.

Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, SBQQ.QuoteAfter: execution of AfterUpdate

caused by: System.CalloutException: Callout from triggers are currently not supported.

(SBQQ)

We see this error in the Apex Jobs status detail for the apex class SBQQ ContractService. Does anyone know what is failing and why?

Update, if we reduce the batch size to 1, this error doesn't occur.
Hello All,

I have a trigger which is after trigger and it is sending an email to the contact, my requiremnt is once I sent email I want to update one of field of my custom object. Can someone help with sample code.

Thanks.
What i'm trying to achive:

Simply call a class from a trigger when checkbox is checked and lead record is saved.

Error message:

Error: Compile Error: Method does not exist or incorrect signature: void runEligibilityCheck() from the type Eligibility at line 4 column 15
 
// My Class

global with sharing class Eligibility {
// Code here
    
      private static String runEligibilityCheck(String patientID) {
      // More code in my method

     }

}
// My Trigger.
Trigger CheckEligiblityUponSelfSchedule on Lead (before update, before insert) {
  for (Lead l: Trigger.new) {
  if(l.self_scheduled__c = TRUE){
  Eligibility.runEligibilityCheck();
    }
  }
}
I'm sure that this is something very simple that I'm missing in my SOQL structure. My current code is:
public class NewActionListController {
    
public List<ACT_Action__c> getnewActions() { 
        List<ACT_Action__c> results = Database.query(
        'SELECT ID, Name FROM ACT_Action__c'
            'WHERE username=:UserInfo.getUserName()');
    return results;
}
}

I am getting an error that says the following:
Extra ')', at 'WHERE username=:UserInfo.getUserName()'

Can someone help? Thanks!
I have no errors in the code, but the button is not working.  The idea is that it is supposed to send an email to the contact email of X3_Party_Installer and then create an activity as well.  Yet, when I press the button nothing happens.  Is there something wrong with the code?

Controller:
public class SendSiteSurveyEmailController {

    public String Site_Survey {get;set;}
    
    Public SendSiteSurveyEmailController(ApexPages.StandardController controller) {
        Site_Survey = ApexPages.currentPage().getParameters().get('Id');
    }
    
    Public Pagereference SendSiteSurveyFunction() {
        list<Site_Survey__c> sitelist = [SELECT X3rd_Party_Installer__c, X3rd_Party_Installer__r.email FROM Site_Survey__c LIMIT 1];
		String toaddress= sitelist[0].X3rd_Party_Installer__r.email;
        try{
            Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
            String[] addr = new String[] {toaddress};
                mail.setToAddresses(addr);
            	mail.setReplyTo(toaddress);
            	mail.setSenderDisplayName('Name');
            	mail.setSubject('DarPro Site Survey');
            	mail.setBccSender(false);
            	mail.setUseSignature(true);
            	mail.setHtmlBody('<b> BODY </b>');
            
            List<Messaging.EmailFileAttachment> fileAttachments = new List<Messaging.Emailfileattachment>();
            for (Attachment a : [SELECT Name, Body, BodyLength FROM Attachment WHERE ParentId = :Site_Survey Order By LastModifiedDate DESC Limit 1]){
                Messaging.Emailfileattachment efa = new Messaging.Emailfileattachment();
                efa.setFileName(a.Name);
                efa.setBody(a.Body);
                fileAttachments.add(efa);
                //mail.setFileAttachments(new Messaging.SingleEmailMessage[] {efa});
            }
            mail.setFileAttachments(fileAttachments);
            
            Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
            
            Contact ct = [SELECT id FROM Contact WHERE Email = :toaddress LIMIT 1];
            
            Task newTask = new Task(Description = 'Site Survey Email',
                                   Priority = 'Normal',
                                   Status = 'Completed',
                                   Subject = 'Site Survey',
                                   Type = 'Email',
                                   WhoId = ct.Id);
        } catch(Exception e) {}
        
        PageReference reference = new PageReference('https://darlingingredients--griffsdbx.cs11.my.salesforce.com/'+Site_Survey);
        reference.setRedirect(true);
        return reference;
    }
}

VF Page: 
<apex:page standardController="Site_Survey__c" extensions="SendSiteSurveyEmailController">
<apex:form >
<script type="text/javascript">
function init() {
sendEmail();
}
if(window.addEventListener)
window.addEventListener('load',init,true)
else
window.attachEvent('onload',init)
</script>

<apex:actionFunction name="sendEmail" action="{!sendSiteSurveyFunction}">
</apex:actionFunction>
</apex:form>
</apex:page>

 
i want to create a button add contact when i clicked one more empty contact show in my page.
like this screen shot.
User-added image
Hi All,
I created post method in my controller class but i can see that post method is send request twice to the middlewre while updating record,but while creating a record it is sending request only onece ,hereis my sample post class ,can someone please suggest me how i can improve  my method.
 
public static HttpResponse  postData(String url, String json)
     {
            HttpResponse response;
            HttpRequest req = new HttpRequest();
             req.setClientCertificateName('HttpClientCert');           
               
            req.setMethod('POST');
            req.setEndpoint(url);
            req.setHeader('Content-Type', 'text/plain; charset=utf-8');
            req.setTimeout(30000);
            //req.setHeader('Content-Type', 'application/json; charset=utf-8');
            req.setHeader('SOAPAction', url);
            req.setBody(json);
           
            Http httpSender = new Http();
            String responseString = '';
            
            try
            {
              if (!Test.isRunningTest()){
                  response = httpSender.send(req);
              }else{
                  response = new HttpResponse();
              }
            }
            catch(System.CalloutException e)
            {
              system.debug('***********'+e);     
            }
            return response;
       
    }

 
i want to create contact records using checkbox in vf page 
Apex Controller:

public class AddmultipleContactsVF {
      Contact Cont = new Contact();
      public list<Contact> listContact{get;set;}
      public Boolean IsSelected{set;get;}

       public AddmultipleContactsVF()
      {     
      listContact=new list<Contact>();
      listContact.add(Cont);
      }
      
      Public void addContact()
      {
      Contact con = new Contact();
      listContact.add(con);
      }
      public PageReference saveContact() {    
      for(Integer i=1; i<listContact.size(); i++)
      {
      if(Isselected==true){
      upsert listContact;
      }
      } 
      return null;
      }
public class wrapperContact{
      public Boolean IsSelected{set;get;}
      public wrapperContact(){
      IsSelected=false;
      }
}
}
VF Page:
<apex:page Controller="AddmultipleContactsVF">
<apex:form >
<apex:pageBlock >
<apex:pageBlockTable value="{!listContact}" var="con">
<apex:column headerValue="Contact LastName">
<apex:inputCheckbox value="{!IsSelected}" id="InputId"/>
<apex:inputField value="{!con.LastName}"/>
<apex:CommandButton value="+" action="{!addContact}"/>
</apex:column>
</apex:pageBlockTable>
<apex:pageBlockButtons >
<apex:CommandButton value="Save Contact" action="{!saveContact}"/>
</apex:pageBlockButtons>
</apex:pageBlock>
</apex:form>
</apex:page>User-added image
 
I plan to register a salesforce developer account with a group email, is it possible? Thanks for your help
My understanding of application event is if two components not related to each then we can use applicaiton event to pass data.

Please correct me if wrong.

I have done a code but I am unable to pass data.
ApplicationEvent.vt

<aura:event type="APPLICATION" description="Event template">

<aura:attribute name="message"
                type="string"
                access="public"/>
    
</aura:event>


ParentComponent.cmp

<aura:component implements="flexipage:availableForAllPageTypes" access="global" >
	
    <aura:attribute name="someattr"
                    type="string"
                    default="I am GOD"
                    access="private"/>
    
    <aura:registerEvent name="handleApplicationEvent"
                        type="c.ApplicationEvent"/>
    
    <lightning:button name="clickMe"
                      label="ClickMe"
                      onclick="{!c.HandleApplicationEvent}"/>
    
    
</aura:component>


PrentComponentController.js

({
	HandleApplicationEvent : function(component, event, helper) {
		
        debugger;
        var applnEvent=$A.get("e.c:ApplicationEvent");
        
        
        var val=component.get("v.someattr");
        console.log(val);
        
        applnEvent.setParams({"message" : val});
        
        applnEvent.fire();
     }
})


ChildComponent.cmp

<aura:component >
	
    <aura:attribute name="receivedvaluefromparent"
                    type="string"
                    access="private"/>
    
    <aura:handler event="c:ApplicationEvent"
                  action="{!c.HandleApplicationEvent}"/>
    
    <c:ParentComponent/>
    Inside the child component : {!v.receivedvaluefromparent}
    
</aura:component>


ChildComponent.js

({
	HandelApplicationEvent : function(component, event, helper) {
		
        debugger;
        var evtMessage=event.getParam("message");
        
        console.log(evtMessage);
        component.set("v.receivedvaluefromparent",evtMessage.ToString());
        
	}
})


MainApp.app

<aura:application >
    <c:ParentComponent/>
</aura:application>

I checked using debugger but value is not comoing into the child attribute from the parent.

Please let me know where I go wrong.

thanks
sheila S
 
I have the following trigger which is poorly written and causing during data load and record update for certain records. I am trying to fix the query issue at list for now. But I am not expert like you guys so need help. 

Following Code trying to update but getting- Unexpected token issue. 
List <Investor_Position__c> listIvPost = [Select Id,Investor_Position_Account__c,Is_Active__c, Current_Commitments_Functional__c, Source_of_Capital__c,
                                                Investment_Vehicle__r.Id, Investment_Vehicle__r.Number_of_Current_Investors__c, Investment_Vehicle__r.Number_of_Historical_Investors__c
                                                from Investor_Position__c where Investment_Vehicle__r.Id IN  InvestmentVehicleIds];
            for(Id id : InvestmentVehicleIds)
            {
                for( Investor_Position__c obj :listIvPost )
                {
                    
                    if(obj.Is_Active__c == TRUE && obj.Source_of_Capital__c != null)
                    {



Original Code: 
trigger InvestorPositionTrigger on Investor_Position__c (after insert, after update, after delete) {

Set<Id> numofhistinvestors = new Set<Id>(); 
Set<Id> numofcurrentinvestors = new Set<Id>(); 
Set<Id> InvestmentVehicleIds = new Set<Id>(); 

List<Investment_Vehicle__c> lstUpdateInvVehicle = new List<Investment_Vehicle__c>();

if(trigger.isafter)
{
    if(trigger.isinsert || trigger.isupdate)
    {
        
            for(Investor_Position__c inv : Trigger.New)
            {
                InvestmentVehicleIds.add(inv.Investment_Vehicle__c);
            }    
    }   
     if(trigger.isdelete)
    {
        
            for(Investor_Position__c inv : Trigger.old)
            {
                InvestmentVehicleIds.add(inv.Investment_Vehicle__c);
            }    
    }       
    
            for(Id id : InvestmentVehicleIds)
            {
                for( Investor_Position__c obj : [Select Id,Investor_Position_Account__c,Is_Active__c, Current_Commitments_Functional__c, Source_of_Capital__c,
                                                Investment_Vehicle__r.Id, Investment_Vehicle__r.Number_of_Current_Investors__c, Investment_Vehicle__r.Number_of_Historical_Investors__c
                                                from Investor_Position__c where Investment_Vehicle__r.Id =:id])
                {
                    
                    if(obj.Is_Active__c == TRUE && obj.Source_of_Capital__c != null)
                    {                       
                    
                        if(obj.Current_Commitments_Functional__c > 0 && (obj.Source_of_Capital__c.contains('Limited Partners') || obj.Source_of_Capital__c.contains('Operating Partner')))
                        {
                            numofcurrentinvestors.add(obj.Investor_Position_Account__c);  
                        }
                        if(obj.Source_of_Capital__c.contains('Limited Partners') || obj.Source_of_Capital__c.contains('Operating Partner'))
                        {
                            numofhistinvestors.add(obj.Investor_Position_Account__c); 
                        }
                    }                   
                }
                
                Investment_Vehicle__c invveh = new Investment_Vehicle__c();
                invveh.Id = id;
                invveh.Number_of_Historical_Investors__c = numofhistinvestors.size();
                invveh.Number_of_Current_Investors__c = numofcurrentinvestors.size();
                
                lstUpdateInvVehicle.add(invveh);
                numofcurrentinvestors.clear();
                numofhistinvestors.clear();
            }  
            
            try
            {
                    if(lstUpdateInvVehicle.size() > 0)
                    {
                        update lstUpdateInvVehicle; 
                    }
                    
            }
            catch(exception ex)
            {
                 for (Investor_Position__c obj : trigger.new) 
            {         
                obj.addError(ex.getmessage());        
            } 
            }      
        
    
}

	if(Trigger.isInsert){
		ConfigurableRollup.rollup(trigger.new);
	}
	if(Trigger.isUpdate){
		system.debug('when is update------');
		ConfigurableRollup.rollup(trigger.new, Trigger.OldMap);
	}
	if(Trigger.isDelete){
		ConfigurableRollup.rollup(trigger.old);
	}
}