• Sunil02Kumar
  • NEWBIE
  • 140 Points
  • Member since 2010
  • Senior Salesforce Developer


  • Chatter
    Feed
  • 5
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 0
    Questions
  • 28
    Replies
I created a resource to insert an Account record with fields- Name and Description in SF1(say), and i want to send the values from another instance SF2(say) using REST API from URL parameters.

I created one VF page with fields Name and Description. when i entered Name and Description fields respectively they should go to contoller dynamically and create the record in resource instance.

My question is how to pass the values from VF page to Controller(into URL parameters.)?
Hi Experts!

I'm a newbie and I've created a Trigger below with the help of awesome people here. This works fine but my friend suggested to study about the Trigger Handler so we can limit triggers in object and my code will be easier to debug. I want to learn the Best Practices on this so please help and advise how to put this with Class. 
 
trigger UpdateHourlyRate on Job__c (Before insert, Before update) {

    Set<Id> AccID = new Set<Id>();
    Set<String> JobType = new Set<String>();
    
    Map<String,Rate_card__c> RateCardMap = new Map<String,Rate_card__c>();
    
    for (Job__c Job: Trigger.new){AccID.add(Job.Account__c); JobType.add(Job.Type__c);}
    
    For(Rate_Card__c RateCard : [SELECT Id, Hourly_Rate__c, Account__c, Type__c 
                                 FROM Rate_card__c 
                                 WHERE Account__c IN: AccID]){
								 	
                                     RateCardMap.put(RateCard.Account__c + RateCard.Type__c, RateCard);
  
                                 }
 
	For (Job__c Jobs: Trigger.new ){
            
            if(RateCardMap.containsKey(Jobs.Account__c+Jobs.Type__c)){ 
    
                Jobs.Hourly_Rate__c = RateCardMap.get(Jobs.Account__c + Jobs.Type__c).Hourly_Rate__c;

    }
}

I'm not sure how to start though. basically, I thought of building a class like below.
 
public class JobHourlyRateUpdate {

    Set<Id> AccID = new Set<Id>();
    
    public Static void computeHourlyRate(List<Job__c> Jobs){
        
            For(Job__c Job:Jobs){
                AccID.add(Job.Account__c);
            }
            
            Map<String,Rate_card__c> RateCardMap = new Map<String,Rate_card__c>();
            
            For(Rate_Card__c RateCard : [SELECT Id, Hourly_Rate__c, Account__c, Type__c 
                                     FROM Rate_card__c 
                                     WHERE Account__c IN: AccID]){
                                        
                                         RateCardMap.put(RateCard.Account__c + RateCard.Type__c, RateCard);
      
                                     }
        
    }
}


Here's what my code does:

When Job Record is Created or Updated, find Rate Card from Account (Related List) and update the Job's Hourly Rate if the Ratecard has the same Type as the Job.

Result Should be something like below.

User-added image


It would be fantastic if there are documents you can reffer me so I can start learning about this :)

Thanks in Advance!
I need to alter or set the system.date to another date for testing purposes (test the trigger), but I can't find a way to do it.

The trigger works great but it take the system.now().date as a value and the Test coverage always fails because I can not test all the cases:  

Example

   
    Datetime required = system.now().date();    
    Datetime validDate = system.now().date();     
    String todayDay= validDate.formatGMT('EEEE');  

   for ( Order__c Order : Trigger.new )
    {
        Order__c queryOrder= [SELECT Id,Name,Otter_FFA_Is_Updatable__c,Required_Date__c From Order__c where Id=:Order.Id];
        //if was no update through QAD
        if ((queryOrder.Otter_FFA_Is_Updatable__c=='')||(queryOrder.Otter_FFA_Is_Updatable__c==null))
        {//if Required_Date__c != null
        if ( Order.Required_Date__c != null )
        {
        required = Order.Required_Date__c;
            if(validDate.date().daysBetween(required.date())<=1){//If there is a difference of one day 
            if (todayDay.toUpperCase() =='THURSDAY'){
                if (hour<11){days=1;}
                else {days=4;}
            }
            else if (todayDay.toUpperCase() =='FRIDAY'){
                if (hour<11){days=3;}
                else {days=4;}
            }
            else if (todayDay.toUpperCase() =='SATURDAY'){
              {days=3;}
            }
            else if (todayDay.toUpperCase() =='SUNDAY'){
              {days=2;}
            }                
            else {
                if (hour<11){days=1;}
                else {days=2;}
            }

                
Those Thursday, friday, saturday and sunday I can test it.

Any advice will be appreciate it.
I want to out put the Created By Name instead of the ID but don't know how to query the Users Name since __r doesnt work on the CreatedById Field. And then output the Name of the user on the repeated output of code.
VisualForce Page Code:

<apex:repeat value="{!customerHealth.Histories}" var="hh">
    <tr>
       <td><apex:outputText value="{0, date, EE MMMM dd, YYYY}"><apex:param value="{!hh.CreatedDate}"/></apex:outputText></td>
       <td><apex:outputText value="{!hh.CreatedById}"></apex:outputText></td>
       <apex:outputPanel rendered = "{!hh.Field = 'created'}">
           <td><apex:outputText value="{!hh.Field}"></apex:outputText></td>
       </apex:outputPanel>
       <apex:outputPanel rendered = "{!hh.Field != 'created'}">
           <td>Changed <strong><apex:outputText value="{!hh.Field}"></apex:outputText></strong> to  <strong><apex:outputText value="{!hh.NewValue}"></apex:outputText></strong></td>
       </apex:outputPanel>
   </tr>
</apex:repeat>

Apex Class Code:

List<Customer_Health__c> customerHealths = new List<Customer_Health__c>([SELECT Name, (SELECT NewValue, Field, CreatedById, CreatedDate FROM Histories) FROM Customer_Health__c WHERE Id= :CHidNum]);
customerHealth = customerHealths.get(0);

Hi can any one suggest me the chanfes to mu code where it is necessary.

This was the complete error

First error: Update failed. First exception on row 0; first error: MISSING_ARGUMENT, Id not specified in an update call: []

 

Here is my code

 

global class MRUpdate2 implements Database.Batchable<sobject>,Schedulable {

global final string query= 'select id,Amount__c,name,End_Date__c,know_date__c,Today__c,contract__c,Email__c,Status__c,Start_Date__c from Maintanence_Renewal__c';
global final string email;
global MRUpdate2()
{

System.debug('--- Followers list: ' + query);
email='attelli.anilkumar@gmail.com';
}
global void execute(SchedulableContext SC) {
// invoke business logic - this method is strictly to invoke
// the method from the scheduler...
MRUpdate2 MR2 = new MRUpdate2();
ID batchprocessid = Database.executeBatch(MR2,10);

}
global Database.QueryLocator start(Database.BatchableContext BC)
{

return Database.getQueryLocator(this.query);
}

global void execute(Database.BatchableContext BC, List<Maintanence_Renewal__c> scope)
{
List<Maintanence_Renewal__c> MRSToUpdate = new List<Maintanence_Renewal__c>();

for(Maintanence_Renewal__c m :scope)
{
if(m.Today__c==m.know_date__c)
{
Maintanence_Renewal__c c2= new Maintanence_Renewal__c(Start_Date__c=m.End_Date__c,
Status__c='Pending',
contract__c=m.contract__c,Email__c=m.Email__C,
Amount__c=m.Amount__c+(m.Amount__c *5/100));
MRSToUpdate.add(c2);
}
}
update MRSToUpdate;
}
global void finish(Database.BatchableContext BC){
// Get the ID of the AsyncApexJob representing this batch job
// from Database.BatchableContext.
// Query the AsyncApexJob object to retrieve the current job's information.

AsyncApexJob a = [Select Id, Status, NumberOfErrors, JobItemsProcessed,
TotalJobItems, CreatedBy.Email
from AsyncApexJob where Id =:BC.getJobId()];

// Send an email to the contractor notifying about contract.
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
String[] toAddresses = new String[] {email};
mail.setToAddresses(toAddresses);
mail.setSubject('Renew your contract');
mail.setPlainTextBody('Dear Sir/Madam please Renew Your Contract it will expire in 60 days' );

Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
}

}

 

Tnanks & Regards

Attelli

I have made a lightning component (that uses the lightning:tree) that works fine when I place it in the lightning page layout, however when I place it in a legacy VF page (the VF page is a tab on the record detail page) using Lightning Out the down/right chevrons do not render.  Then if I place my component on a VF page inside an apex : tabPanel the component does not render at all.

Is there still ongoing work in the Lightning dev team to integrate Lightning and Visualforce together?  Perhaps the lightning:tree component itself has a few bugs?
Hi All,
I have contacts(updates and new) from an external system which i need to send over to Salesforce(SF) via SOAP. I have created a field (IFCS_c) as an external id with the intention to use this as part of the upsert so that SF will either create a new contact or update an existing contact. At the same time if it is a new contact i need to associate it to an existing Account record object using AccountId field in Contact. The external id field name is set to IFCS_c. The upsert for contact WSDL is as below:
  <urn:externalIDFieldName>IFCS__c</urn:externalIDFieldName>
  <urn:sObjects xsi:type="Contact" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <urn:AccountId>001S000000nbmnsIAA</urn:AccountId>
    <urn:IFCS__c>1741</urn:IFCS__c>
    <urn:Contact_Type__c>Card Delivery</urn:Contact_Type__c>
    <urn:MailingStreet/>
    <urn:OtherStreet/>
    <urn:FirstName>Bob Tester</urn:FirstName>
    <urn:LastName>Bob Tester</urn:LastName>
    <urn:Primary__c>false</urn:Primary__c>
  </urn:sObjects>
</urn:upsert>

I am getting the following message:
<con1:ReceivedFaultDetail xmlns:con1="http://www.bea.com/wli/sb/stages/transform/config">
      <con1:faultcode xmlns:urn="urn:fault.enterprise.soap.sforce.com">urn:INVALID_FIELD</con1:faultcode>
      <con1:faultstring>INVALID_FIELD: Field name provided, IFCS__c does not match an External ID for Contact</con1:faultstring>
      <con1:detail>
        <sf:InvalidFieldFault xsi:type="sf:InvalidFieldFault" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:sf="urn:fault.enterprise.soap.sforce.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
          <sf:exceptionCode>INVALID_FIELD</sf:exceptionCode>
          <sf:exceptionMessage>Field name provided, IFCS__c does not match an External ID for Contact</sf:exceptionMessage>
          <sf:row>-1</sf:row>                                                                                      
          <sf:column>-1</sf:column>
        </sf:InvalidFieldFault>
      </con1:detail>
      <con1:http-response-code>500</con1:http-response-code>

 Any help will be great and thanks in advance.
I created a resource to insert an Account record with fields- Name and Description in SF1(say), and i want to send the values from another instance SF2(say) using REST API from URL parameters.

I created one VF page with fields Name and Description. when i entered Name and Description fields respectively they should go to contoller dynamically and create the record in resource instance.

My question is how to pass the values from VF page to Controller(into URL parameters.)?
Hi Experts!

I'm a newbie and I've created a Trigger below with the help of awesome people here. This works fine but my friend suggested to study about the Trigger Handler so we can limit triggers in object and my code will be easier to debug. I want to learn the Best Practices on this so please help and advise how to put this with Class. 
 
trigger UpdateHourlyRate on Job__c (Before insert, Before update) {

    Set<Id> AccID = new Set<Id>();
    Set<String> JobType = new Set<String>();
    
    Map<String,Rate_card__c> RateCardMap = new Map<String,Rate_card__c>();
    
    for (Job__c Job: Trigger.new){AccID.add(Job.Account__c); JobType.add(Job.Type__c);}
    
    For(Rate_Card__c RateCard : [SELECT Id, Hourly_Rate__c, Account__c, Type__c 
                                 FROM Rate_card__c 
                                 WHERE Account__c IN: AccID]){
								 	
                                     RateCardMap.put(RateCard.Account__c + RateCard.Type__c, RateCard);
  
                                 }
 
	For (Job__c Jobs: Trigger.new ){
            
            if(RateCardMap.containsKey(Jobs.Account__c+Jobs.Type__c)){ 
    
                Jobs.Hourly_Rate__c = RateCardMap.get(Jobs.Account__c + Jobs.Type__c).Hourly_Rate__c;

    }
}

I'm not sure how to start though. basically, I thought of building a class like below.
 
public class JobHourlyRateUpdate {

    Set<Id> AccID = new Set<Id>();
    
    public Static void computeHourlyRate(List<Job__c> Jobs){
        
            For(Job__c Job:Jobs){
                AccID.add(Job.Account__c);
            }
            
            Map<String,Rate_card__c> RateCardMap = new Map<String,Rate_card__c>();
            
            For(Rate_Card__c RateCard : [SELECT Id, Hourly_Rate__c, Account__c, Type__c 
                                     FROM Rate_card__c 
                                     WHERE Account__c IN: AccID]){
                                        
                                         RateCardMap.put(RateCard.Account__c + RateCard.Type__c, RateCard);
      
                                     }
        
    }
}


Here's what my code does:

When Job Record is Created or Updated, find Rate Card from Account (Related List) and update the Job's Hourly Rate if the Ratecard has the same Type as the Job.

Result Should be something like below.

User-added image


It would be fantastic if there are documents you can reffer me so I can start learning about this :)

Thanks in Advance!
I have a following trigger to update the record type lookup. I'm taking value from the text field and trying to update lookup but its not working. can someone please help?
 
trigger UpdateLookup on Manager__c (after insert, after update) {
try {
set<string> rtset = new set<string>();
for (Manager__c inq : trigger.new) {
   rtset.add(inq.Record_Type__c);
}

Map<String, RecordType> rtmap = new Map<String, RecordType>([Select id from RecordType Where Name in :rtset]); 



for (Manager__c inq : trigger.new) {
     inq.RecordTypeId = rtmap.get(inq.Record_Type__c).id;
   
     
  
}
} catch(Exception e) {  
}
}

 
  • March 31, 2015
  • Like
  • 0
I need to alter or set the system.date to another date for testing purposes (test the trigger), but I can't find a way to do it.

The trigger works great but it take the system.now().date as a value and the Test coverage always fails because I can not test all the cases:  

Example

   
    Datetime required = system.now().date();    
    Datetime validDate = system.now().date();     
    String todayDay= validDate.formatGMT('EEEE');  

   for ( Order__c Order : Trigger.new )
    {
        Order__c queryOrder= [SELECT Id,Name,Otter_FFA_Is_Updatable__c,Required_Date__c From Order__c where Id=:Order.Id];
        //if was no update through QAD
        if ((queryOrder.Otter_FFA_Is_Updatable__c=='')||(queryOrder.Otter_FFA_Is_Updatable__c==null))
        {//if Required_Date__c != null
        if ( Order.Required_Date__c != null )
        {
        required = Order.Required_Date__c;
            if(validDate.date().daysBetween(required.date())<=1){//If there is a difference of one day 
            if (todayDay.toUpperCase() =='THURSDAY'){
                if (hour<11){days=1;}
                else {days=4;}
            }
            else if (todayDay.toUpperCase() =='FRIDAY'){
                if (hour<11){days=3;}
                else {days=4;}
            }
            else if (todayDay.toUpperCase() =='SATURDAY'){
              {days=3;}
            }
            else if (todayDay.toUpperCase() =='SUNDAY'){
              {days=2;}
            }                
            else {
                if (hour<11){days=1;}
                else {days=2;}
            }

                
Those Thursday, friday, saturday and sunday I can test it.

Any advice will be appreciate it.
trigger ParentChildcase on Case (before update) {

List<Case> listCase = [select Id,parentId,status from case where parentId != null  ];
////List<Queues> listqueue = [select Id from Queues where name = 'Welcome_Call_Queue'];
system.debug('listCase'+listCase);
map<Id,list<Case>> mapCase = new map<Id,list<Case>>();
    for(Case objCase : listCase){
         if(objCase.status != 'Closed'){
            List<Case> listCasemap = new List<Case>();
            if(mapCase.containskey(objCase.parentId))
                listCasemap = mapCase.get(objCase.parentId);
            listCasemap.add(objCase);
            mapCase.put(objCase.parentId,listCasemap);
         }
    }
    system.debug('mapCase'+mapCase);
    for(case caseObj:Trigger.New){
          if(caseObj.parentId == null && caseObj.Status == 'Closed'){
            if(mapCase.containskey(caseObj.Id)){
                List<Case> listCasemap = mapCase.get(caseObj.Id);
                if(listCasemap.size() != 0){
                    caseObj.addError('Unclosed Child Records are Present.');
                }               
            }
          }
        system.debug('caseObj.Owner.Name'+caseObj.Owner.Name);
        if(caseObj.OwnerID == '00GO0000001iIbf' && caseObj.Status == 'Closed'){
            caseObj.addError('please own the case and close');
        }          
      }   
}

 
Can you guys help me to write a test class?

My trigger:

trigger Atualizar_Fotosfaltantes_AR_case on Account (after update) {

   public List<Case> casesToUpdate = new List<Case>();
   public List<Task> tasksToUpdate = new List<Task>();
    
   public Set <id> ids = new Set <id> ();
    
    for (Account acc: trigger.new) {
        if (acc.antecipado__c == 'AR' || acc.antecipado__c == 'TES' || acc.Nome_do_produto_adquirido__c.contains('AR ')){
            ids.add(acc.id);
        }
    
    if(ids.size()>0){
    For(Case c : [SELECT Id, motivo__c, Formando_com_fotos__c, accountid FROM Case WHERE (motivo__c = 'Formandos AR' OR motivo__c = 'Fotos faltantes') AND accountId IN: ids]){
    For(Task t : [SELECT Id, subject, status FROM Task WHERE (subject = 'AR - Aguardando fotos faltantes' OR subject = 'AR - LuxColor - Aguardando fotos faltantes') AND status != 'Concluído' AND whatid =: c.id]){
    
            if((acc.Formando_com_novas_fotos__c == 'SIM' || acc.Formando_com_novas_fotos__c == 'NÃO') && c.motivo__c == 'Formandos AR'){        
                c.Formando_com_fotos__c = acc.Formando_com_novas_fotos__c;
                }
            if((acc.Formando_com_novas_fotos__c == 'SIM' || acc.Formando_com_novas_fotos__c == 'NÃO') && c.motivo__c == 'Formandos AR'){        
                t.status = 'Concluído';
                
            }
            if((acc.Formando_com_novas_fotos__c == 'FOTOS RECEBIDAS' || acc.Formando_com_novas_fotos__c == 'ENVIAR NOVAMENTE') && c.motivo__c == 'Fotos faltantes'){        
                c.Formando_com_fotos__c = acc.Formando_com_novas_fotos__c; 
            }
                casesToUpdate.add(c);
                tasksToUpdate.add(t); 
            }
    }
    }
    }
    	update casesToUpdate;
    update taskstoupdate;
}

I tried create the test class, but it stops to coverage in line 14 of my trigger so I stoped to continue in my test class. I got 52%:

@isTest(SeeAllData=true)
public class FotosFaltantes_AR_test{
  static testmethod void MyUnitTest001(){

      Account acc = new Account();
            acc.LastName = 'Account Avulso';
            acc.recordtypeid = '012U00000000vYx';
      		acc.Antecipado__c = 'AR';
   			acc.Formando_com_novas_fotos__c = null;
        insert acc;
      
       Test.startTest();
          
           acc.Formando_com_novas_fotos__c = 'SIM';
    update acc;
      
      Test.stopTest();

    Case c = new Case();
      	c.motivo__c = 'Formandos AR';
        c.Formando_com_fotos__c = null;
      	c.status = 'Novo';
      c.AccountId = acc.id;
      insert c;
      
    Task t = new Task();
      	t.Subject = 'AR - Aguardando fotos faltantes';
      	t.Status = 'Nenhum';
      t.WhatId = c.id;
      insert t;
     

      	List<Case> cases = [SELECT Formando_com_fotos__c FROM Case WHERE Id =:c.Id];
       System.assertEquals(acc.Formando_com_novas_fotos__c, cases[0].Formando_com_fotos__c);
  }
}

Thanks !
We have written a de-duplication logic for contact records where we call a batch job from trigger (Yes, it sounds weird but the only thing that seems to work as we have variable criteria for each account). To overcome batch schedule limit of 5, we are using data loader with bulk API enabled and the natch size set to 1000 so that we can upload 5000 records successfully without hitting the 5 batch job limit. When I am testing with 3000 thousand contact records, let say they are named from Test0001 to Test3000 I am observing a strange behavior.

For 3000 records, 3 batch jobs start to run (as batch size is 1000). I am passing the newly inserted records in parameters to the stateful batch class. What I expect is that 1000 records will be passed for each of the 3 batch jobs and they will be compared to existing records for duplicates (which I query in start method of batch) but I only get Test0001 to Test0200 i.e. from batch of 1000 records inserted via data loader API only FIRST 200 records are passed in parameter to the batch class and rest 800 are not. This is something strance as it means only first 200 records are processes if I insert using a batch size of 1000 through data loader with Bulk API enabled.

Has anyone of you encountered this issue or have any ideas to share on how to deal with it? I can share code as well but I think the question is more conceptual. Any help is much appreciated.

Thanks