• Niraj Kr Singh
  • SMARTIE
  • 853 Points
  • Member since 2015


  • Chatter
    Feed
  • 27
    Best Answers
  • 0
    Likes Received
  • 2
    Likes Given
  • 3
    Questions
  • 150
    Replies
Hello,

I am doing Upsert Operation....
Below is my code.
I have a problem while performing Upsert operation:
Scenirio:
Firstly i have to insert a records
then perform Upsert Operation.
I am using external Id while performing DML (Non Atomic)
The records in inserted insted of upsert .




public class upsertDatabase {
    
    public list<Customer_Project__c> cPlist;
    
    public upsertDatabase(){
        cPlist=new list<Customer_Project__c>();
        list<Opportunity> opList=[select id,name from Opportunity where name='Sapna'];
        // insert the new Records
        for(Opportunity ops:opList){
            Customer_Project__c c1=new Customer_Project__c();
            c1.Name='Timakshi';
            c1.ExternalID__c=111;
           c1.Opportunity__c=ops.id;
            c1.Payment__c=78787;
            cPlist.add(c1);
        }
        database.SaveResult[] sr=database.insert(cpList,false);
        for(database.SaveResult s:sr){
            if(s.isSUCCESS()){
                system.debug('success Message' +s.getID());
            }
            else{
                database.Error[] myError=s.getErrors();
                for(database.Error er:myError){
                    system.debug('Error Mesaage for Inserting the records' +er.getMessage());    
                }
            }
        }
// upsert the Records 
        for(Opportunity oops:opList){
            Customer_Project__c c2=new Customer_Project__c();
            c2.Name='Taniya';
            c2.Opportunity__c=oops.id;
            c2.Payment__c=8888855;
            c2.ExternalID__c=989;
            cPlist.add(c2);
        }
        for(Opportunity oops:opList){
            Customer_Project__c c3=new Customer_Project__c();
            c3.Name='Geta';
            c3.Opportunity__c=oops.id;
            c3.Payment__c=8744;
            c3.ExternalID__c=99;
            cPlist.add(c3);
        }
        database.UpsertResult[] UpResult=database.upsert(cPlist,false);
        
        for(database.UpsertResult uR:UpResult){
            if(uR.isSUCCESS()){
                system.debug('Success for Upserting the records' +uR.getId());
            }
            else{
                database.Error[] myUpsertError=uR.getErrors();
                for(database.Error ero:myUpsertError){
                    system.debug('My upsert Errors Message' +ero.getMessage());
                }
                }
            }
        }
        
    }
list<HCP_User_BMS_CN__c> hcplist =[SELECT ,Hospital_Name_BMS_CN__c, Id, User_BMS_CN__r.name, Status_BMS_CN__c FROM HCP_User_BMS_CN__c  ];
for(HCP_User_BMS_CN__c hcp : hcplist){
    String hco = hcp.Hospital_Name_BMS_CN__c;
    String temp='';
    for (integer i = 0; i < hco.length(); i++) {
        temp += hco.substring(i, i+1) + '%';
    }
    String hcolike ='%'+temp ;
    
    list<Account> hcos = [SELECT Name FROM Account where  Name like: hcolike];
    list<String> hcolist = new list<String>();
    for (integer i = 0; i < hcos.size(); i++) {
        hcolist.add(hcos[i].Name);
    }
    //System.debug('hcolist'+'   '+hco+' '+hcolist.size());
    
    if(hcolist.size()>0){
        list<Account> acclist = [select id ,Name,Primary_Parent_vod__r.Name FROM Account where Primary_Parent_vod__r.Name in :hcolist and Name=:hcp.User_BMS_CN__r.name];
        if(acclist.size()>0){
           System.debug('acclist'+acclist); 
        }
    }
}

Because soql inside a for loop ,I am Getting This Below Error:System.LimitException: Too many SOQL queries: 101 . How to deal with it?
  • September 05, 2018
  • Like
  • 0
I created a trigger to invoke an apex class. The trigger is activated every time a contract is entered, i needed to get the ID of this contract, put it on the trigger and send it to my apex class, where i will conduct a query to send information to a partner Webservice.
I'm not finding content for this subject in Trailhead and developer.salesforce.
Could someone help me with this problem?

Thank you
Hi,

I'm using lightning:inputField, but I want only the input field, nothing else.
I have hidde the label, but I automaticaly get the helptext near the field.
And I don't want it in my component.

My code is :
<lightning:inputField fieldName="myCustomField__c" variant="label-hidden" "/>

Any Idea ?
 
Hi Team,

which is the best scenario for calling handler class

Scenario : 1
-------------------
trigger OpportunityTrigger on Opportunity (before insert, before update, before delete, after insert, after update) {
    
    if(Trigger.isBefore && Trigger.isInsert){
        
        // before insert.
        
    }
    
    if(Trigger.isBefore && Trigger.isUpdate){
        
        //  before update.
        
    }
    
    if(Trigger.isBefore && Trigger.isDelete){
        
         //  before delete
    }
    
}
Scenario : 2
trigger OpportunityTrigger on Opportunity (before insert, before update, before delete, after insert, after update) {
    
    if(Trigger.isBefore){
        
        if(Trigger.isInsert){
            
            // before insert
        }
        else
            if(Trigger.isUpdate){
                
                // before update.
                
            }
        
        else
            if(Trigger.isDelete){
                
              //  before delete
                
            } 
    }
        
}

Please let me know which is the best practice.

Thanks,
Lakshmi.

 
I want to create a instance of account to update some field related to that accountRecord during lead conversion.
I am getting Illegal assignment from SObject to Account. How to resolve that?

Account ac = lc.getAccountRecord();
Hi Team,

I have 2 Objects, (Parent-abc__c & Child-CL__c) with loookup relationship.

There are 15 Picklist values in abc__c object.(eg: Country__c, State__c, Region__c, Gender__c.......)
There are 4 Fields in CL__c object(Old value, abc__c, NEW Value, action)

Now I want to create a child record(CL__c) if someone MODIFIES/UPDATES any of the 15 Picklist values.

The CL__c record must have the Old value as well as NEW value for user reference.

How to achieve this using trigger? any code samples? TIA

 
  • August 27, 2018
  • Like
  • 0
I am trying to send a record to an external system via Async service . Only one value within that payload needs to be an array while the remaining should be string. Does any one know how it can be done?
searlization looks like below..
Map<String, String> data = new Map<String, String>{
            'email' => acc.Email__c,
            'displayName' => acc.Display_Name__c,
            'bioUrl' => acc.Bio_URL__c,
            'imageUrl' => acc.Image_URL__c,
            'vertical' => acc.Channel__c,
            'status' => acc.Status__c,
            'gid' => acc.Legacy_GID__c,
            'numberOfExperts' => String.valueOf(acc.Number_of_Experts__c),
            'userId' => String.valueOf(acc.Selene_ID__c),
            'socialPreference' => acc.Social_Presence__c
        };
        String jsonInput = JSON.serializePretty(data, True);

While the output that I am seeking is like..
{
  "socialPreference" : [
                    "www.facebook.com/101", 
                    "www.twitter.com/101"
                        ],
  "userId" : "123456789123",
  "numberOfExperts" : "1",
  "gid" : "210967",
  "status" : "LIVE",
  "vertical" : "SALESFORCE",
  "imageUrl" : "",
  "bioUrl" : "",
  "displayName" : "test101",
  "email" : "test101@test.com"
}
I don't know how to convert just one value (socialPresence)into an array format.
That is a LONG TEXT field in UI and will hold multiple urls separated by comma or semi-colon.

 
Hi all,

I am unable to create the test class for cancel button. I tried but got error 
 Argument 1 cannot be null.
Please provide the test class for following code

   public pagereference cancel()
    {
     
       PageReference reqPageRef = new PageReference(ApexPages.currentPage().getParameters().get('retURL')); 
       reqPageRef.setRedirect(true);  
       return reqPageRef;
    }

Thanks
Hi,

I wrote a trigger and test Class. am getting 100% coverage in the sandbox but 0% Code Coverage in Production. Kindly Please help me to solve this issue. 

My trigger:

trigger Cumulative_Calcuation on Opportunity (Before Update) {
List<Target__C> Tglist= New List<Target__C>();
List<Target__C> Tglist1= New List<Target__C>();
Map<String,ID> Mapfield = New map<String,ID>();
Map<String,ID> MapTele = New map<String,ID>();
List<Incentive__c >lstInc =New list<Incentive__c >();
List<Incentive__c >lstInc1 =New list<Incentive__c >();
List <Cumulative__c> Cumlist= New list <Cumulative__c>();
List <Cumulative__c> Cumlist1= New list <Cumulative__c>();
list<Cumulative__c > lstcum = new list<Cumulative__c >(); 
list<Opportunity > opplist = new list<Opportunity >(); 
Set<String> setAllNames = new Set<String>();      
       For(Opportunity opp:Trigger.New){               
       Mapfield .put(opp.Field_Executive__c,opp.ID);MapTele.put(opp.Hidden_Owner_Name__c,opp.ID);} 
       setAllNames.addAll(Mapfield.keyset()); setAllNames.addAll(MapTele.keyset());             
for(target__C objTG : [SELECT ID, name FROM target__C WHERE Name in: setAllNames AND Active__c = True]) {
                if(Mapfield.containskey(objTG.Name)){
                    TGlist1.add(objTG);}
                if(MapTele.containskey(objTG.Name)){
                    TGlist.add(objTG);}}
            for(Opportunity opp: trigger.new ) { 
                    if(TGlist1.size()>0){if(opp.Field_Executive__c==TGlist1[0].NAme){
                                   opp.Target__C= TGlist1[0].ID; } }
                    IF(TGlist.size()>0){if(opp.Hidden_Owner_Name__c==TGlist[0].NAme){   
                                   opp.Telecaller__c=TGlist[0].ID;
                                   }
        
        }         
            If(opp.Telecaller__c!=Null && opp.Cumulative_Updated__c==False && opp.Work_Order_Created_Date__c!=Null ){
              Cumlist=[select ID,Target__c,Type1_Customer_Order_value_MPD__c,Type1_Customer_Order_Value_PD__c,Type2_Customer_Order_value_MPD__c,Type2_Customer_Order_value_PD__c,Type3_Customer_Order_value_MPD__c,Type3_Customer_Order_value_PD__c,Type4_Customer_Order_value_MPD__c,Type4_Customer_Order_value_PD__c,From_Date__c,To_Date__c from Cumulative__c where Target__c=:opp.Telecaller__c and  From_Date__c<=:opp.Work_Order_Created_Date__c and To_Date__c>=:opp.Work_Order_Created_Date__c];    if(Cumlist.size()>0){For(Cumulative__c Cum:Cumlist){lstInc = [select ID from Incentive__c where ID =:Opp.IncentiveSlab__c and Opp_Discount_To__c>=:opp.Discount__c]; If(lstInc.size()>0 ){If(Opp.Customer_Slab_Type__c=='Type 4'){ Cum.Type4_Customer_Order_value_PD__c+= opp.Individual_Order_value__c;opp.Cumulative_Updated__c=True;}Else IF(Opp.Customer_Slab_Type__c=='Type 2'){Cum.Type2_Customer_Order_value_PD__c+= opp.Individual_Order_value__c; opp.Cumulative_Updated__c=True;}Else IF(Opp.Customer_Slab_Type__c=='Type 3'){Cum.Type3_Customer_Order_value_PD__c+= opp.Individual_Order_value__c;opp.Cumulative_Updated__c=True;}Else IF(Opp.Customer_Slab_Type__c=='Type 1'){Cum.Type1_Customer_Order_Value_PD__c+= opp.Individual_Order_value__c;opp.Cumulative_Updated__c=True; }} IF(lstInc.size()<=0 ){If(Opp.Customer_Slab_Type__c=='Type 4'){Cum.Type4_Customer_Order_value_MPD__c+= opp.Individual_Order_value__c;opp.Cumulative_Updated__c=True;
                            }Else IF(Opp.Customer_Slab_Type__c=='Type 2'){Cum.Type2_Customer_Order_value_MPD__c+= opp.Individual_Order_value__c;opp.Cumulative_Updated__c=True; }Else IF(Opp.Customer_Slab_Type__c=='Type 3'){Cum.Type3_Customer_Order_value_MPD__c += opp.Individual_Order_value__c;opp.Cumulative_Updated__c=True;} Else IF(Opp.Customer_Slab_Type__c=='Type 1'){Cum.Type1_Customer_Order_value_MPD__c+= opp.Individual_Order_value__c;opp.Cumulative_Updated__c=True;} }lstcum .add(Cum);opplist.add(opp);} } } If(opp.Target__C!=Null && opp.FE_Cumulative_Updated__c==False && opp.Work_Order_Created_Date__c!=Null ){               
              Cumlist1=[select ID,Target__c,Type1_Customer_Order_value_MPD__c,Type1_Customer_Order_Value_PD__c,Type2_Customer_Order_value_MPD__c,Type2_Customer_Order_value_PD__c,Type3_Customer_Order_value_MPD__c,Type3_Customer_Order_value_PD__c ,Type4_Customer_Order_value_MPD__c,Type4_Customer_Order_value_PD__c,From_Date__c,To_Date__c from Cumulative__c where Target__c=:opp.Target__C and From_Date__c<=:opp.Work_Order_Created_Date__c and To_Date__c>=:opp.Work_Order_Created_Date__c]; if(Cumlist1.size()>0){For(Cumulative__c Cum:Cumlist1){ lstInc1 = [select ID from Incentive__c where ID =:Opp.IncentiveSlab__c and Opp_Discount_To__c>=:opp.Discount__c]; If(lstInc1.size()>0 ){If(Opp.Customer_Slab_Type__c=='Type 4'){ Cum.Type4_Customer_Order_value_PD__c+= opp.Individual_Order_value__c;opp.FE_Cumulative_Updated__c=True;}Else IF(Opp.Customer_Slab_Type__c=='Type 2'){Cum.Type2_Customer_Order_value_PD__c+= opp.Individual_Order_value__c;opp.FE_Cumulative_Updated__c=True;}Else IF(Opp.Customer_Slab_Type__c=='Type 3'){Cum.Type3_Customer_Order_value_PD__c += opp.Individual_Order_value__c; opp.FE_Cumulative_Updated__c=True;
                             }Else IF(Opp.Customer_Slab_Type__c=='Type 1'){Cum.Type1_Customer_Order_Value_PD__c+= opp.Individual_Order_value__c;   opp.FE_Cumulative_Updated__c=True; }} IF(lstInc1.size()<=0 ){ If(Opp.Customer_Slab_Type__c=='Type 4'){Cum.Type4_Customer_Order_value_MPD__c+= opp.Individual_Order_value__c; opp.FE_Cumulative_Updated__c=True;}Else IF(Opp.Customer_Slab_Type__c=='Type 2'){ Cum.Type2_Customer_Order_value_MPD__c+= opp.Individual_Order_value__c; opp.FE_Cumulative_Updated__c=True;}Else IF(Opp.Customer_Slab_Type__c=='Type 3'){ Cum.Type3_Customer_Order_value_MPD__c+= opp.Individual_Order_value__c; opp.FE_Cumulative_Updated__c=True;} Else IF(Opp.Customer_Slab_Type__c=='Type 1'){Cum.Type1_Customer_Order_value_MPD__c+= opp.Individual_Order_value__c;opp.FE_Cumulative_Updated__c=True;} }lstcum .add(Cum); opplist.add(opp);
                      } } } 
                      update lstcum ; }}


My Test class:

@isTest(seeAlldata=True)
Public class Cum_incentive_Test{
    static testMethod void Cum_incentive_Test(){
    
    String opportunityName = 'My Opportunity';
String standardPriceBookId = '';
list<Cumulative__c > lstcum = new list<Cumulative__c >(); 
list<Opportunity > opplist = new list<Opportunity >(); 


 Incentive__c INC= new Incentive__c(Name='Indoor test', Active__c = true, Product_Type__c = 'Indoor', 
         Start_Date__c = date.newinstance(2014,12,25), Area__c = 'All India');
        insert INC;
        
        IncentiveLineItem__c inclitem = new IncentiveLineItem__c(Incentive__c = INC.id,Other_Mode__c=0.80 ,Customer_Mode__c='Type 3',Neft_Cash__c=0.75 , Discount_From__c=0,Discount_To__c=10,Field_Staff__c=1,Telesales__c=1,Combined__c=2);
        insert inclitem;
PriceBook2 pb2Standard = [select Id ,Incentive_Slab__c from Pricebook2 where isStandard=true];
standardPriceBookId = pb2Standard.Id;

pb2Standard .Incentive_Slab__c=inc.ID;
Update pb2Standard ;

 Account a = new Account(Name = 'ApprovalTest' ,Lock_record__C=FALSE , Customer_Type__c='Builders');
 insert a; 
 
 Contact con = new COntact();
 con.email='test@fmail.co';
 con.ACCOUNTID=a.ID;
 con.lastname='test' ;            
 insert con;   
    
Opportunity o = new Opportunity(AccountId=null, Name='test', 
StageName='Prospecting', CloseDate=Date.today());
insert o;

Opportunity opp = [SELECT Name,IncentiveSlab__c,Discount__c FROM Opportunity WHERE Id = :o.Id];


Product2 p2 = new Product2(Name='Test Product',isActive=true);
insert p2;
Product2 p2ex = [SELECT Name FROM Product2 WHERE Id = :p2.Id];
System.assertEquals('Test Product', p2ex.Name);


PricebookEntry pbe = new PricebookEntry(Pricebook2Id=standardPriceBookId, Product2Id=p2.Id, UnitPrice=99, isActive=true);
insert pbe;
PricebookEntry pbeex = [SELECT Pricebook2Id FROM PricebookEntry WHERE Id = :pbe.Id];
System.assertEquals(standardPriceBookId, pbeex.Pricebook2Id);

OpportunityLineItem oli = new OpportunityLineItem(PriceBookEntryId=pbe.Id, OpportunityId=o.Id, Quantity=1, TotalPrice=99);
insert oli;

OpportunityLineItem oliex = [SELECT PriceBookEntryId FROM OpportunityLineItem WHERE Id = :oli.Id];
System.assertEquals(pbe.Id, oliex.PriceBookEntryId); 

Quote Q = new Quote();
            Q.Name = 'Quote';
            Q.OpportunityId = Opp.id; 
            Q.Quote_Count__c = 00000000;
            Q.Approved__c = true;
            Q.Quote_Number__c ='000000';
            Q.Quotation_Date__c = date.newinstance(2013,3,5);
            Q.Pricebook2Id = pb2Standard .id;        
            insert Q;
   
Project__c Proj = new Project__c(name='Proj't, Opportunity__c = Opp.id, Quote__c = Q.id, Project_Type__c = 'New PE', Date_of_Installation__c = date.newinstance(2013,4,5),
Nature_of_Case__c ='No Adv, Dspch & Erection Pending',Contact__C=con.ID,Customer_Name__c=a.id,Special_Instructions__c ='Test for Work order Pdf to be generated');    
            
insert Proj;  

 

Opp.Pricebook2Id = pb2Standard .id;
opp.IncentiveSlab__c= pb2Standard .Incentive_Slab__c;
opp.Field_Executive__c='Raman.A';
update Opp; 

list<Incentive__c > lstInc1=new list<Incentive__c >{INC};


/*lstInc1=[select ID from Incentive__c where ID=:Opp.IncentiveSlab__c AND Opp_Discount_To__c>=:opp.Discount__c];
      
update lstInc1;*/
 
    
Target__c  TC= NEw Target__c (Name='Raman.A',Out_Standing_Amount__c=10000,Active__c=True,Target_Amount__c=700000);
 Insert TC; 
 
 

Cumulative__c CTC= New Cumulative__c (From_Date__c=Date.today(),
To_Date__c=date.newinstance(2018,7,30),Target__c=TC.ID);
        
insert CTC;  

  
Target__c  TC1= NEw Target__c (Name='Ashok',Out_Standing_Amount__c=10000,Active__c=True,Target_Amount__c=700000);
 Insert TC1; 
 
 
Cumulative__c CTC1= New Cumulative__c (From_Date__c=Date.today(),
To_Date__c=date.newinstance(2018,7,30),Target__c=TC1.ID);
  
insert CTC1; 

    
Opportunity o1 = new Opportunity(AccountId=null, Name='test', 
StageName='Open', CloseDate=Date.today());
insert o1;

Opportunity o2 = new Opportunity(AccountId=null, Name='test', 
StageName='Open', CloseDate=Date.today());
insert o2;

o2.StageName='Closed/Lost';

Update o2;


Opportunity o3 = new Opportunity(AccountId=null, Name='test', 
StageName='Open', CloseDate=Date.today());
insert o3;
 try{ 
          o3.StageName='Closed Won';
          Update o3;
                   
        }Catch (DMLException e){
            System.assert(e.getMessage().contains('No Test Record'), 'No Test Record.');
        }




        
}
}


Thanks,
Shakila
 
HI, i am practicing for Salesforce developer 1.  I came across this question and the answer offered didnt make any sense to me.

The operation manager at a construction company uses a custom object called Machinery to manage the usage and maintenance of its cranes and other machinery. The manager wants to be able to assign machinery to different construction jobs, and track the dates and cost associated with each job. More than one piece of machinery can be assigned to one construction job. What should a developer do to meet these requirements?
  1. Create a lookup field on the machinery object to the construction job object
  2. Create a junction object with Master-Detail Relationship to both the machinery object and the construction job object.
  3. Create a lookup field on the construction job object to the machinery object
  4. Create a Master-Detail lookup field on the machinery object to the construction job object

The answer provided was n.3.  I would have gone with n.2.

Would you be able to help me with this and explain the answer to this by any chance

Many thanks
 
Hello,

i have problem with my lightning code. 

i am using this action in a save function:
var getDateDifference = cmp.get('c.getDateDiff');
getDateDifference.setParams({deliveryDate: soldByDate.get('v.value')});
getDateDifference.setCallback(this, function(respDate){
    console.debug("DATE DIFF " + respDate.getState());
    console.debug("DATE DIFF " + respDate.getReturnValue());
    });
$A.enqueueAction(getDateDifference);
it calls this Apex-Method:
 
@AuraEnabled
public static Integer getDateDiff(String deliveryDate){
    system.debug('divdate' + deliveryDate);
    system.debug('date ' + system.today());    
    return 120;
}

It is actually called successfully (i can see the apex debug messages), but the javascript debugs are not showing in the developer console of my browser.

Note: 120 is just a return for testing. 

Any advise about this?

thanks
Peter
Handler--------------------------

public class UpdateAccAddressTriggerHandler{
    public static void changeAccAddress(list<contact> contList){
        set<Id> AcctIds=new set<Id>();
        list<Account> accList=new list<Account>();
        map<Id,Contact> contMap = new map<Id,Contact>();
        
        for(Contact con:contList){
            AcctIds.add(con.AccountId);       
        }
        
        for(Contact con:[Select Id,AccountId, MailingStreet,MailingCity, MailingState, MailingCountry,  MailingPostalCode,LastModifiedDate  from Contact 
        WHERE AccountId IN:AcctIds order by LastModifiedDate Desc limit 1]){
             if(!contMap.containskey(con.accountId)){
             contMap.put(con.AccountId,con); 
             }           
        }
        
        for(Account acc:[select id,BillingCity,BillingStreet,BillingCountry,BillingPostalCode from Account where id IN:AcctIds]){          
            Contact con =contMap.get(acc.id);
            acc.BillingStreet=con.MailingStreet; 
            acc.BillingCity=con.MailingCity;
            acc.BillingState=con.MailingState;
            acc.BillingPostalCode=con.MailingPostalCode;
            acc.BillingCountry=con.MailingCountry;                   
            accList.add(acc);
       }                
       update accList;        
   }
}

Trigger--------------------------
trigger updateAccAddressTrigger on Contact (after insert,after update) {
    if(Trigger.isAfter){
        UpdateAccAddressTriggerHandler.changeAccAddress(Trigger.New);
    
    }
}
  • August 07, 2018
  • Like
  • 0
Hi, we are a publishing company that sell adverts into different magazine 'Issues'(custom SF Object)

I have an apex trigger called EndOfSeriesIssue that takes the latest Issue from opportunityLineItem and puts it to a look up field on opportunity called last_issue__c, based on Issue_publication_date__c

This works fine. However there is a problem when two issues have the same Issue_publication_date__c. Could anyone tell me how to modify my trigger to deal with this problem? Trigger below:


trigger EndOfSeriesIssue on Opportunity (before update) {
    
    for (Opportunity o : Trigger.new) {
        
        OpportunityLineItem[] LineItemArray =
       [select Issue__c, Issue_publication_date__c from OpportunityLineItem where OpportunityId = :o.id ORDER BY Issue_publication_date__c DESC];
       if (LineItemArray.size() > 0) {
           
           o.last_issue__c = LineItemArray[0].Issue__c;
           
       }else{
           
            o.last_issue__c = null;   
           
      }
   }
}
I have Visualforce page  with below code
<apex:page controller="assign_1_Controller">
<apex:pageBlock >
    <apex:form >
   <apex:pageBlockSection columns="1">
        <apex:inputField value="{!newCase.ContactId}" label="Search Contact">      
        </apex:inputField>
        
        <apex:commandButton value="Go" title="Go" action="{!go}"/>
        
        <!-- <apex:commandButton value="Add New Contact" title="Add New Contact" action="{!addNewContact}"/> -->
        </apex:pageBlockSection>
    </apex:form>
    </apex:pageBlock>
</apex:page>
and 

Controller
public Contact contactbyLookup{get;set;}
public PageReference go(){
        PageReference p = new PageReference('/apex/Casetabsearchassignment');
        if(newCase.ContactId != null){
        contactByLookup = [select id,
                                  Name,
                                  Business_Vertical__c  
                                  from Contact 
                                  where id =: newCase.ContactId];
    
        }
        return p;
    }
 
Hi All,

Any help in writting test class for the below trigger is appreciated.

trigger test on Mail__c (after update) {
            list<Duration__c> durations = new list<Duration__c>();
            set<string> trackedFields = new set<string> {'OwnerId', 'Status__c', 'Sub_Status__c'}; 
            STOWD.API.CalculateDurations(durations, trackedFields, 'Request__History', 'ParentId'); 
            database.insert(durations, false);
    }
  • July 26, 2018
  • Like
  • 0
I am trying to build a test class for accounts that populate the city and state based on the zip code when they are created. I am getting the error however on line 25 "Method does not exist or incorrect signature: void makeZipCallout(Id) from the type AccountClass" I have tried multiple ways of correcting it but cannot for the life of me to figure out whats wrong.

Here is the test class:
@IsTest
public class TestAccountClass {
Static testMethod void AccountClassTest(){
Account a = new Account(Name = 'Test Class');

a.BillingCity = 'SAINT PAUL';
a.BillingState = 'MN';
a.BillingPostalCode = '55113';
a.BillingCountry = 'US';
insert a;   
Test.startTest();
HttpRequest request = new HttpRequest();
StaticResourceCalloutMock mock = new StaticResourceCalloutMock();
mock.setStaticResource('GoogleMapsAPI');
mock.setStatusCode(200);
mock.setHeader('Content-Type', 'application/json');
mock.respond(request);
HttpResponse response = new HttpResponse();
JSONParser responseParser = JSON.createParser(response.getBody());

// Set the mock callout mode
Test.setMock(HttpCalloutMock.class, mock);

// Call the method that performs the callout
AccountClass.makeZipCallout(a.Id);

}
}

Here is the code used to call the city and state based on the zip if that helps :
// Use a name besides "Account" otherwise you'll get compilation problems due to symbol collision
public with sharing class AccountClass {
	
	private static boolean isTrigger = false;		// Pitfall #4: Used to prevent infinite loops
    public class accountException extends Exception {}

	/* format from ziptasticapi.com:  
	    {"country":"US","state":"CA","city":"SAN JOSE"}
	*/
	// Format returned by ziptastic API
	public class ziptasticReturn {
    	string country;
	    string state;
	    string city;
	}	
	 
	// Trigger Handler to do zipCodeLookup when new records are created
	//  Do this after the record is created so we have an ID we can reference
	public static void onAfterInsert( List<Account> triggerNew)
	{
		// Pitfall #4 - Prevent infinite loops
		if (isTrigger == true) {
			return;				// Just return if this is called as a result of our DML operation
		} else
		   isTrigger = true;	// Set this so we know we caused ourselves to be called again
		
		// Must pass IDs & not SObjects to @future because the SObject may change by the time @future executes
		List<Id> accountsId = new List<Id>();
		for (Account a : triggerNew) {
			accountsId.add(a.Id);
		}	
		system.debug(LoggingLevel.Info, 'onAfterInsert called with '+triggerNew+'; sending IDs='+accountsId);
		makeZipCallout(accountsId);
	}
	
	// Pitfall #1 & #2 - Triggers must do callouts from an '@future' and (callout = true) anotated function
	@future (callout = true) 
	private static void makeZipCallout(List<Id>acct)
	{
		system.debug(LoggingLevel.Info, 'makeZipCallout with '+acct);
		string resp;
		
		// Pitfall #3 - Fetch records of the IDs for updating
		List<Account> accountSet = [SELECT Id, BillingPostalCode, BillingCity, BillingState, BillingCountry
									FROM account 
									WHERE Id = :acct];
		
		for (Account a : accountSet) {
			
			// Note this version of the API is only for the US
		    string endpoint ='http://ziptasticapi.com/';
		    endpoint = endpoint + a.BillingPostalCode;
		    system.debug(LoggingLevel.Info,'zipCode.clslling endpoint='+endpoint);
	 
		    HttpRequest req = new HttpRequest();
		    HttpResponse res = new HttpResponse();
		    Http http = new Http();
		    req.setMethod('GET');
		    req.setEndpoint(endpoint);
	 
		    try {
		      res = http.send(req);
		      if (res.getStatusCode() != 200) {
		        throw new accountException(res.getStatus());
		      }
		    } catch (accountException e) {
		      system.debug(LoggingLevel.Error, 'Error HTTP response code = '+res.getStatusCode()+'; calling '+endpoint );
		      return;
		    }
	  
	    	resp = res.getBody();
	    	JSONParser parser = JSON.createParser(resp);
	    	parser.nextToken(); // Start object "{"
        
        	ziptasticReturn zipInfo = new ziptasticReturn();
		    // This convenient method reads the JSON stream into a class in one go
		    zipInfo = (ziptasticReturn) parser.readValueAs(ziptasticReturn.class);
		    a.BillingState = zipInfo.state;
		    a.BillingCity = zipInfo.city;
		    a.BillingCountry = zipInfo.country;
	    	
		}    
		update accountSet;		// Call DML operation to update
		isTrigger = false;		// Pitfall #4 - Trigger is done so reset this
	}		 //makeZipCallout()
}

Any help is appreciate!
 
  public void setLandDRecordCount() {

        for(AggregateResult ar : [select Product__r.city_ins__SubType__c, count(ID) 
                                    from        Quote_Temp__C 
                                    where       Product__r.city_ins__Type__c = 'LAndD'
                                    and         Quote__c = :quoteId
                                    group by    Product__r.city_ins__SubType__c 
                                 ] ) 
        {
            LandDMap.put((String) ar.get('city_ins__SubType__c'), (Integer) ar.get('expr0'));
        }
    }
    
    /*********************************************************/
    /* Setect the appropriate L&D templates                  */
    /*********************************************************/
    public String  getTemplateNameForLAndD(string groupSize) {
        
        /* 
        One Product Template either ( LAndD , LAndDD or STD )   <Sub_ProductType>_Template 
        Two Product Templates ( LAndD + LAndDD Template )   
        Two Product Templates ( LandD + STD Template )
        Two Product Template ( LandDD + STD Template )

        LAndD Count
        LAndDD count
        STD Count
        Template 1 : LAndDLAndDD
        Template 2 : LAndDLAndDDSTD
        Template 3 : LAndDSTD 
        Template 3 : LAndD 
        */
        setLandDRecordCount();
        
        String LAndD_Str    = ''; 
        String LAndDD_Str   = '';
        String STD_Str      = '';
        
        String LandDTemplate = '';
        
        if (LAndDMap.get('LAndD') > 0 ) {
            LAndD_Str   = 'LAndD'; 
            LAndDD_Str = '';
        }
        if (LAndDMap.get('LAndDD') > 0) {
            LAndDD_Str  = 'LAndDD';
            LAndD_Str = '';
        }
        if ( LAndDMap.get('STD') > 0) {
            STD_Str     = 'STD';
        }
        return LAndD_Str + LAndDD_Str + STD_Str + 'Template'+groupSize;

    }
    
How to resolve 
Select Id ,name,(Select Product_dashcode__c from IX_V1__PP_Relationships__r)from IX_V1__ICIX_Product__c
                                                             Where Name 
                                                             LIKE:newSearchText 
                                                             OR Product_dashcode__c=:productName 

It showing 


                           OR Product_dashcode__c=:productName
                              ^
ERROR at Row:5:Column:65
No such column 'Product_dashcode__c' on entity 'IX_V1__ICIX_Product__c'. If you are attempting to use a custom field, be sure to append the '__c' after the custom field name. Please reference your WSDL or the describe call for the appropriate names.
Hi All,

I have written a trigger to update both opportunity and cumulative object.
My logic is working fine for the same I have written a test class. My code coverage is 81 % in Sandbox when I go for deployment in production ...during the validation am getting following error. Kindly let me know How to overcome from the below error.

User-added image
My trigger:

trigger UpdateAmountInWords on Opportunity (Before Update) {
List<Target__C> Tglist= New List<Target__C>();
List<Target__C> Tglist1= New List<Target__C>();
Map<String,ID> Mapfield = New map<String,ID>();
Map<String,ID> MapTele = New map<String,ID>();
List<Incentive__c >lstInc =New list<Incentive__c >();
List<Incentive__c >lstInc1 =New list<Incentive__c >();
List <Cumulative__c> Cumlist= New list <Cumulative__c>();
List <Cumulative__c> Cumlist1= New list <Cumulative__c>();
list<Cumulative__c > lstcum = new list<Cumulative__c >(); 
list<Opportunity > opplist = new list<Opportunity >(); 
 Utils u = new Utils();
       For(Opportunity opp:Trigger.New){ 
       // Update opporunity Amount In Words
        opp.Amount_To_Words_Total_Amount_With_Tax__c = u.convert(opp.Total_Amount_With_IGST__c.longValue())+' Only'; 
        opp.Amount_To_Words_Total_Tax_Amount__c = u.convert(opp.Total_Tax_Amount__c.longValue())+' Only'; 
        //            
       Mapfield .put(opp.Field_Executive__c,opp.ID);MapTele.put(opp.Hidden_Owner_Name__c,opp.ID);}
       
TGlist1=[select ID, name from target__C where Name in:Mapfield.keyset() and Active__c=True];           
TGlist=[select ID, name from target__C where Name in:MapTele.keyset() and  Active__c=True];
            for(Opportunity opp: trigger.new ) { 
                    if(TGlist1.size()>0){if(opp.Field_Executive__c==TGlist1[0].NAme){
                                   opp.Target__C= TGlist1[0].ID; } }
                    IF(TGlist.size()>0){if(opp.Hidden_Owner_Name__c==TGlist[0].NAme){   
                                   opp.Telecaller__c=TGlist[0].ID;}}         
            If(opp.Telecaller__c!=Null && opp.Cumulative_Updated__c==False && opp.Work_Order_Created_Date__c!=Null ){
              Cumlist=[select ID,Target__c,Type1_Customer_Order_value_MPD__c,Type1_Customer_Order_Value_PD__c,Type2_Customer_Order_value_MPD__c,Type2_Customer_Order_value_PD__c,Type3_Customer_Order_value_MPD__c,Type3_Customer_Order_value_PD__c,Type4_Customer_Order_value_MPD__c,Type4_Customer_Order_value_PD__c,From_Date__c,To_Date__c from Cumulative__c where Target__c=:opp.Telecaller__c and  From_Date__c<=:opp.Work_Order_Created_Date__c and To_Date__c>=:opp.Work_Order_Created_Date__c];
                   if(Cumlist.size()>0){For(Cumulative__c Cum:Cumlist){lstInc = [select ID from Incentive__c where ID =:Opp.IncentiveSlab__c and Opp_Discount_To__c>=:opp.Discount__c]; 
                        If(lstInc.size()>0 ){If(Opp.Customer_Slab_Type__c=='Type 4'){           
                                Cum.Type4_Customer_Order_value_PD__c+= opp.Individual_Order_value__c;opp.Cumulative_Updated__c=True;
                             }Else IF(Opp.Customer_Slab_Type__c=='Type 2'){Cum.Type2_Customer_Order_value_PD__c+= opp.Individual_Order_value__c; opp.Cumulative_Updated__c=True;
                             }Else IF(Opp.Customer_Slab_Type__c=='Type 3'){Cum.Type3_Customer_Order_value_PD__c+= opp.Individual_Order_value__c;opp.Cumulative_Updated__c=True;
                             }Else IF(Opp.Customer_Slab_Type__c=='Type 1'){Cum.Type1_Customer_Order_Value_PD__c+= opp.Individual_Order_value__c;opp.Cumulative_Updated__c=True;
                             }} IF(lstInc.size()<=0 ){If(Opp.Customer_Slab_Type__c=='Type 4'){Cum.Type4_Customer_Order_value_MPD__c+= opp.Individual_Order_value__c;opp.Cumulative_Updated__c=True;
                            }Else IF(Opp.Customer_Slab_Type__c=='Type 2'){Cum.Type2_Customer_Order_value_MPD__c+= opp.Individual_Order_value__c;opp.Cumulative_Updated__c=True;
                            }Else IF(Opp.Customer_Slab_Type__c=='Type 3'){Cum.Type3_Customer_Order_value_MPD__c += opp.Individual_Order_value__c;opp.Cumulative_Updated__c=True;
                            } Else IF(Opp.Customer_Slab_Type__c=='Type 1'){Cum.Type1_Customer_Order_value_MPD__c+= opp.Individual_Order_value__c;opp.Cumulative_Updated__c=True;
                            } }lstcum .add(Cum);opplist.add(opp);} } } 
         If(opp.Target__C!=Null && opp.FE_Cumulative_Updated__c==False && opp.Work_Order_Created_Date__c!=Null ){               
              Cumlist1=[select ID,Target__c,Type1_Customer_Order_value_MPD__c,Type1_Customer_Order_Value_PD__c,Type2_Customer_Order_value_MPD__c,Type2_Customer_Order_value_PD__c,Type3_Customer_Order_value_MPD__c,Type3_Customer_Order_value_PD__c ,Type4_Customer_Order_value_MPD__c,Type4_Customer_Order_value_PD__c,From_Date__c,To_Date__c from Cumulative__c where Target__c=:opp.Target__C and From_Date__c<=:opp.Work_Order_Created_Date__c and To_Date__c>=:opp.Work_Order_Created_Date__c];
               if(Cumlist1.size()>0){For(Cumulative__c Cum:Cumlist1){ 
                       lstInc1 = [select ID from Incentive__c where ID =:Opp.IncentiveSlab__c and Opp_Discount_To__c>=:opp.Discount__c]; 
                        If(lstInc1.size()>0 ){If(Opp.Customer_Slab_Type__c=='Type 4'){ Cum.Type4_Customer_Order_value_PD__c+= opp.Individual_Order_value__c;opp.FE_Cumulative_Updated__c=True;
                             }Else IF(Opp.Customer_Slab_Type__c=='Type 2'){Cum.Type2_Customer_Order_value_PD__c+= opp.Individual_Order_value__c;opp.FE_Cumulative_Updated__c=True;
                             }Else IF(Opp.Customer_Slab_Type__c=='Type 3'){Cum.Type3_Customer_Order_value_PD__c += opp.Individual_Order_value__c; opp.FE_Cumulative_Updated__c=True;
                             }Else IF(Opp.Customer_Slab_Type__c=='Type 1'){Cum.Type1_Customer_Order_Value_PD__c+= opp.Individual_Order_value__c;   opp.FE_Cumulative_Updated__c=True;
                             }} IF(lstInc1.size()<=0 ){ If(Opp.Customer_Slab_Type__c=='Type 4'){Cum.Type4_Customer_Order_value_MPD__c+= opp.Individual_Order_value__c; opp.FE_Cumulative_Updated__c=True;
                        }Else IF(Opp.Customer_Slab_Type__c=='Type 2'){ Cum.Type2_Customer_Order_value_MPD__c+= opp.Individual_Order_value__c; opp.FE_Cumulative_Updated__c=True;
                        }Else IF(Opp.Customer_Slab_Type__c=='Type 3'){ Cum.Type3_Customer_Order_value_MPD__c+= opp.Individual_Order_value__c; opp.FE_Cumulative_Updated__c=True;
                        } Else IF(Opp.Customer_Slab_Type__c=='Type 1'){Cum.Type1_Customer_Order_value_MPD__c+= opp.Individual_Order_value__c;opp.FE_Cumulative_Updated__c=True;}        
                        }lstcum .add(Cum); opplist.add(opp);
                      } } } 
                      update lstcum ; }}

 
Hi, 
My requirement is like that:
1. We can add/remove any no.of column in table.
2. Position of column should be changable and in sorting order on tha basis of value in column/cell.

Please suggest some idea/workaround on it.
Hi Everyone,
I am facing problem to hide the input field using javascript:
<apex:inputField Id="IFWhatId" value="{!objTask.WhatId}"/>

how can hide this <apex:inputField> using javascript.

Thanks
Niraj
 
My requirement is to create a field like "Related to" in this image.
Step1: Picklist with the Objects
Step2: On select of any one object, need to display all related records
Requirement to create a field like "Related to" field in this picture
Give me quick suggestion.

Thakns Niraj  
What I have so far covers 26% of the batch class. I'm not able to cover the execute portion of the batch class.

batch.cls
public class Batch implements Database.Batchable<sObject> {

	public Database.QueryLocator start(Database.BatchableContext bc) {
        String query = 'SELECT Id, jstcl__Consultant__r.Previous_Timesheet_Status__c FROM jstcl__TG_Timesheet__c WHERE jstcl__Placement__r.ts2__Status__c =\'Active\' AND jstcl__Placement__r.VMS__c = \'\' AND jstcl__Week_Ending__c = LAST_N_DAYS:4 AND jstcl__Status__c = \'Pending\'';
          return Database.getQueryLocator(query);
    }
   public void execute(Database.BatchableContext BC, List<jstcl__TG_Timesheet__c> timesheets){
       List<Contact> consultants = new List<Contact>();
       List<Contact> consultants2 = new List<Contact>();

       for(jstcl__TG_Timesheet__c timesheet : timesheets){
           Contact consultant = timesheet.jstcl__Consultant__r; 
           if (consultant == null) continue;
           consultant.Previous_Timesheet_Status__c = 'Pending';
           if(consultants.contains(consultant)){
               consultants2.add(consultant);
           }else{consultants.add(consultant);}
           }
           update consultants;
        }
   public void finish(Database.BatchableContext BC){}
}
test.cls
@istest 
private class Test {

static TestMethod void hfTest() {
     Profile prof = [select id from profile where name='system Administrator'];
     User usr = new User(alias = 'usr', email='us.name@vmail.com',
                emailencodingkey='UTF-8', lastname='lstname',
                timezonesidkey='America/Los_Angeles',
                languagelocalekey='en_US',
                localesidkey='en_US', profileid = prof.Id,
                username='testuser128@testorg.com');
                insert usr;
    Id idRecordId = Schema.SObjectType.Contact.getRecordTypeInfosByDeveloperName().get('Candidate').getRecordTypeId();

    	ts2__Source__c source = new ts2__Source__c(Name = 'LinkedIn.com - Resume Search');
    	Account acc = new Account(Name = 'Express Scripts Holding Company');
        insert acc;
  		Account acc2 = new Account(Name = 'Candidates- 10-2018');
        insert acc2;
    	Contact con = new Contact(FirstName='fnadmes', LastName = 'lnamdes', Email = 'emadils@gmail.com', Phone = '9744800300', AccountId = acc2.Id, ts2__Source__c = source.Id, ts2__People_Status__c = 'Placed');
        Contact con2=new Contact(FirstName='fnames', LastName = 'lnames', Email = 'emails@gmail.com', Phone = '9743800300', AccountId=acc.Id, Relationship_Status__c = 'Lunch'); 
    	insert con; insert con2;
        ADP_Department__c adp = new ADP_Department__c(Name = 'Georgia');
        insert adp;
        ts2__Job__c job = new ts2__Job__c(Name = 'Software Engineer',Hiring_Manager_Contact__c = con2.Id);
        insert job;
        ts2__HolidayCalendar__c hcal = new ts2__HolidayCalendar__c(Name= 'Holiday Calendar');
        insert hcal;
        Labor_Category__c lcat = new Labor_Category__c(Name='Software Engineer 1');  
        insert lcat;
        ts2__Placement__c plc = new ts2__Placement__c(ts2__Job__c = job.Id, Contractor_Type__c = 'Technical Youth', Onboarding_Method__c= 'Staff Augmentation', ts2__Start_Date__c= Date.newInstance(2019, 1, 7), ts2__End_Date__c= Date.newInstance(2019, 2, 15),
        jstcl__HireType__c= 'W2', ADP_Department__c= adp.Id, ts2__Bill_Rate__c= 60.00, ts2__Pay_Rate__c= 30.00, jstcl__Invoice_Batch__c= 'Placement', ts2__Client__c= acc.Id, ts2__Hiring_Manager__c= con2.Id, jstcl__TimecardApprover__c= con2.Id, jstcl__HolidayCalendar__c= hcal.Id,
		State_Worked_In_Non_TFI_Placements__c= 'GA - Georgia', jstcl__Overtime_Bill_Rate__c= 60, jstcl__Burden__c= 0.20, jstcl__Accounts_Receivable_U__c= '00537000005d7F2AAI', jstcl__Terms__c= 'Net 60', ts2__Employee__c= con.Id, Labor_Category__c= lcat.Id);
		insert plc;
     	List<jstcl__TG_Timesheet__c> tsList = new List<jstcl__TG_Timesheet__c>();
    	 jstcl__TG_Timesheet__c ts = new jstcl__TG_Timesheet__c(jstcl__Consultant__c = con2.Id, jstcl__Placement__c = plc.Id, jstcl__Week_Ending__c = Date.newInstance(2019, 2, 15));
    tsList.add(ts);

	Test.startTest(); 
     Batch abcd = new Batch();
     ID batchprocessid = Database.executeBatch(abcd);
	Test.stopTest();
 }    
}

 
I've created a formula for a Workflow Rule to Update a field value. But I get and error message: Error: Incorrect number of parameters for function 'ISPICKVAL()' Expected 2, received 3

I don't seem able to correct this. Anyone have any ideas?

User-added image

 
Hi All, 

I am getting following error message: 

Challenge not yet complete... here's what's wrong:
A field with an API Name 'Match_Billing_Address__c' does not exist on the Account object

my code is as follows:


trigger AccountAddressTrigger on Account (before insert, before update) {
     for(Account a : Trigger.New) {
        if(a.Match_Billing_Address__c==true){a.ShippingPostalCode=a.BillingPostalCode;}
    }
}

 Thanks in Advance
Dear Developers,

I would like to send notification of public group users by using batch class(weekly based). can anyone please advise me how can i change my code for accurate requirement.

Batch Class 
global class PSO_etmfErrorLogBatch implements database.batchable<SObject>{

global database.querylocator start(database.batchableContext bc){
    system.debug('Start Method Running');
    return Database.getQueryLocator('Select Id,name from eTMF_Files_Error_Log__c');
}

global void execute(database.batchableContext bc, List<eTMF_Files_Error_Log__c> errlogList){
    system.debug('Execute Method Running');
    List<String> toAddresses = new List<String>();
    List<User> userList = [select id, name, email, isactive, profile.name, userrole.name, usertype 
                           from user 
                           where id in (select userorgroupid from groupmember where group.name = 'Document Tracking Admin')];
    for(User u : userList){           
        toAddresses.add(u.email);
    }  
    List < Messaging.SingleEmailMessage > emails = new List < Messaging.SingleEmailMessage > ();
    for (eTMF_Files_Error_Log__c irow_erLog : errlogList) {
        Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
        email.setToAddresses(toAddresses});
        email.setSubject('Last Week ETMF Error Log'); 
        email.setPlainTextBody('Dear user, Please Check Last Week ETMF Error Log');
        emails.add(email);
    }
    Messaging.sendEmail(emails);
}

global void finish(database.batchableContext bc){}

}

Hearty Thanks In Advance !!

Regards,
Soundar P
Hello Guys,

I am working on custom metadata, I have custom meta data "Org_Email_Signature__mdt" and is having field type Long text Area "Email_Signature__c".

Now, when I create a new user, I need to fetch that custom meta data to a field "Signature" in user object. I need to write a trigger for this.

Please help me to achieve this functionality.
Hello Group Members,

I just have a qauestion about apex trigger which is used to create a record. This trirgger currently sets the created by user to current user who has doen the transaction. Is there any way to make sure that I set the user to run the apex trigger in a saingle user context so that the record created by field is always same user irrespective of who did the transaction?
Hi All

How can i create child based on multi picklist value selectio on parent.I will select 1 value in multi picklist then it will create 1 child .i will select 2 value then it will create 2 child and so on.


 
I have a date field in Account . I need to find the date 365 days before the mentioned date in SOQL query
Hi,

Can you please help me with test  class
Class:
global class CDPWeeklyDigestBatchScheduler implements Schedulable {

    global void execute(SchedulableContext sc) {
        String query = 'SELECT Id, Deal_Id__c, Deal_Name__c, Deal_Stage__c, Type__c, Region_Type__c, Market__c, Deal_Owner__c, Latest_Change__c, Deal_Lost_Reason__c, Number_Of_Updates__c FROM CDP_Notification__c WHERE LastModifiedDate = LAST_N_DAYS:7 ';
        List<SObject> records = Database.query(query);    
        NotificationHelper.getNotificationHelperInstance().notifyUsersAboutWeeklyDigest(records);
    }








 
  • September 11, 2018
  • Like
  • 0
Hi,
Can you please help me with test class


Class:

global with sharing class BatchToEndCarouselAnnouncementsScheduler extends BatchScheduler implements Schedulable
{
    global BatchToEndCarouselAnnouncementsScheduler()
    {
        super(10 /*minutes between attempts */, 'End Carousel Announcements');
    }
    
    global void execute(SchedulableContext sc)
    {
        schedule(new BatchToEndCarouselAnnouncements());
    }
}


Extended Class:

public with sharing abstract class BatchScheduler implements Schedulable
{
    @TestVisible static final Integer MAX_CONCURRENT_BATCH = 5;
    @TestVisible Integer minutesBeforeReschedule;
    @TestVisible String title;
    public BatchScheduler( Integer minutes, String title )
    {
        this.minutesBeforeReschedule = minutes;
        this.title = title;
    } 
    public void schedule( IBatchHelper helper, Integer batchSize )
    {
        Integer currentlyRunningBatches = [SELECT count() FROM AsyncApexJob WHERE JobType='BatchApex'
                                           AND (Status = 'Processing' OR Status = 'Preparing')];
        if( currentlyRunningBatches < MAX_CONCURRENT_BATCH )
        {
            BatchHandler batch = new BatchHandler( helper );
            Database.executeBatch( batch, batchSize );
        }
        else
        {
            scheduleRetry();
        }
    }

    public void schedule( IBatchHelper helper )
    {
        schedule( helper, 200 );
    }

    @TestVisible void scheduleRetry() 
    { 
        Datetime rescheduleDateTime = Datetime.now().addMinutes(minutesBeforeReschedule); 
        String timeForScheduler = rescheduleDateTime.format('s m H d M \'?\' yyyy'); 
        System.schedule(title + ' ' + timeForScheduler, timeForScheduler, this); 
    } 
}
  • September 11, 2018
  • Like
  • 0
Hi, I have created a detail custom button of url type and passing Opportunity Date as shown below.

/apex/vfpage?oliId={!OpportunityLineItem.Id} && oppDate={!Opportunity.customDate__c}

And in apex constructor i am receiving the custom date value as below.

customDate = Date.valueOf(ApexPages.currentPage().getParameters().get('oppDate'));
But I am receiving error as
"Argument cannot be null. An unexpected error has occurred. Your development organization has been notified. "

How to pass the oppDate from url to constructor.
 
Hello,

I am doing Upsert Operation....
Below is my code.
I have a problem while performing Upsert operation:
Scenirio:
Firstly i have to insert a records
then perform Upsert Operation.
I am using external Id while performing DML (Non Atomic)
The records in inserted insted of upsert .




public class upsertDatabase {
    
    public list<Customer_Project__c> cPlist;
    
    public upsertDatabase(){
        cPlist=new list<Customer_Project__c>();
        list<Opportunity> opList=[select id,name from Opportunity where name='Sapna'];
        // insert the new Records
        for(Opportunity ops:opList){
            Customer_Project__c c1=new Customer_Project__c();
            c1.Name='Timakshi';
            c1.ExternalID__c=111;
           c1.Opportunity__c=ops.id;
            c1.Payment__c=78787;
            cPlist.add(c1);
        }
        database.SaveResult[] sr=database.insert(cpList,false);
        for(database.SaveResult s:sr){
            if(s.isSUCCESS()){
                system.debug('success Message' +s.getID());
            }
            else{
                database.Error[] myError=s.getErrors();
                for(database.Error er:myError){
                    system.debug('Error Mesaage for Inserting the records' +er.getMessage());    
                }
            }
        }
// upsert the Records 
        for(Opportunity oops:opList){
            Customer_Project__c c2=new Customer_Project__c();
            c2.Name='Taniya';
            c2.Opportunity__c=oops.id;
            c2.Payment__c=8888855;
            c2.ExternalID__c=989;
            cPlist.add(c2);
        }
        for(Opportunity oops:opList){
            Customer_Project__c c3=new Customer_Project__c();
            c3.Name='Geta';
            c3.Opportunity__c=oops.id;
            c3.Payment__c=8744;
            c3.ExternalID__c=99;
            cPlist.add(c3);
        }
        database.UpsertResult[] UpResult=database.upsert(cPlist,false);
        
        for(database.UpsertResult uR:UpResult){
            if(uR.isSUCCESS()){
                system.debug('Success for Upserting the records' +uR.getId());
            }
            else{
                database.Error[] myUpsertError=uR.getErrors();
                for(database.Error ero:myUpsertError){
                    system.debug('My upsert Errors Message' +ero.getMessage());
                }
                }
            }
        }
        
    }
If((LeadList[0].OwnerId != '005User1') || (LeadList[0].OwnerId != '005User2) || (LeadList[0].OwnerId != '005User3'))

Need help writing this line better
Hi Team,

We have updated the field in same object using before insert & Update triggers, Is it necessary to use Recursive class for this trigger.

Please let me know.

Thanks,
Lakshmi.
list<HCP_User_BMS_CN__c> hcplist =[SELECT ,Hospital_Name_BMS_CN__c, Id, User_BMS_CN__r.name, Status_BMS_CN__c FROM HCP_User_BMS_CN__c  ];
for(HCP_User_BMS_CN__c hcp : hcplist){
    String hco = hcp.Hospital_Name_BMS_CN__c;
    String temp='';
    for (integer i = 0; i < hco.length(); i++) {
        temp += hco.substring(i, i+1) + '%';
    }
    String hcolike ='%'+temp ;
    
    list<Account> hcos = [SELECT Name FROM Account where  Name like: hcolike];
    list<String> hcolist = new list<String>();
    for (integer i = 0; i < hcos.size(); i++) {
        hcolist.add(hcos[i].Name);
    }
    //System.debug('hcolist'+'   '+hco+' '+hcolist.size());
    
    if(hcolist.size()>0){
        list<Account> acclist = [select id ,Name,Primary_Parent_vod__r.Name FROM Account where Primary_Parent_vod__r.Name in :hcolist and Name=:hcp.User_BMS_CN__r.name];
        if(acclist.size()>0){
           System.debug('acclist'+acclist); 
        }
    }
}

Because soql inside a for loop ,I am Getting This Below Error:System.LimitException: Too many SOQL queries: 101 . How to deal with it?
  • September 05, 2018
  • Like
  • 0
 Map<String,String> resultMap = new Map<String,String>();
Can any onecan help me with test class

public with sharing class OpportunityQuickCreateExt
{
    public OpportunityQuickCreateExt( QuickCreateController quickCreateCont )
    {
        User currentUser = [ SELECT Default_Continent__c, Default_Market__c, Default_Region__c
                             FROM User WHERE Id = :UserInfo.getUserId() ];
        quickCreateCont.quickCreateObject.put( 'Name', 'Dummy Name' );
        quickCreateCont.quickCreateObject.put( 'StageName', 'E Qualify / Suspect-No RFP' );
        quickCreateCont.quickCreateObject.put( 'Continent__c', currentUser.Default_Continent__c );
        
        if( !String.isEmpty( currentUser.Default_Region__c ) )
        {
            List<Region__c> defaultRegion = [SELECT Id FROM Region__c WHERE Name = :currentUser.Default_Region__c LIMIT 1 ];
            quickCreateCont.quickCreateObject.put( 'Region__c', defaultRegion.isEmpty() ? NULL : defaultRegion[0].Id );
        }
        if( !String.isEmpty( currentUser.Default_Market__c ) )
        {
            List<Market__c> defaultMarket = [SELECT Id FROM Market__c WHERE Name = :currentUser.Default_Market__c LIMIT 1 ];
            quickCreateCont.quickCreateObject.put( 'Market__c', defaultMarket.isEmpty() ? NULL : defaultMarket[0].Id );
        }
    }
}
While inserting new account records before update account trigger is firing. I don't want to execute update trigger how to stop these update trigger execution. Please assist me.

Thanks!
I am working on writing a service which is expected to monitor Scheduled batch jobs. I am querying CronTrigger to get list of all scheduled classes but could not find a direct way to find out which ApexClass is scheduled. 

Is there a way in recent releases to find out which apex class is scheduled in particular CronTrigger record in Apex ?
One Trigger(T1) updates a field. This field update induces another Trigger (T2). Now both Trigger events will come under same transaction or a different transaction ?
Getting this error " There was an unexpected error while verifying this challenge. Usually this is due to some pre-existing configuration or code in the challenge Org. We recommend using a new Developer Edition (DE) to check this challenge. If you're using a new DE and seeing this error, please post to the developer forums and reference error id: CZIZGUYC " , when trying to do second challege of lightning connect.