• v varaprasad
  • PRO
  • 2772 Points
  • Member since 2015
  • Salesforce Developer

  • Chatter
    Feed
  • 89
    Best Answers
  • 2
    Likes Received
  • 0
    Likes Given
  • 14
    Questions
  • 612
    Replies
Hi Team,

Trigger not fetching the values all, i am inserting new records through data import wizard, i am not getting any error but after insert some records are updating and some records are not update, Example today inserted 500 records though data import wizard now its inserting 500 records but out of 500, 200 records its updating the EHR_TS__c value and remaining 300 not updating, and after i exported 300 records and update only ID, at that time 300 records its updating.

Please Help me where i am mistake in code its very urgent, below is my code Trigger & Class ,Thanks Advanced.

************************************ TRIGGER  ***********************************************************

Trigger UpdateEHRate on Time_Sheet__c (before insert,before update,after update, after insert)
{        
    if((Trigger.isInsert && Trigger.isAfter) || (Trigger.isUpdate && Trigger.isAfter)){   
        if(checkRecursive.isFirstRun()){

            List<Time_Sheet__c> timeList = EHRTriggerHandler.UpdateEHRate(trigger.New);
            if(timeList.size() > 0){
                update timeList;
            }
        }
    }
}

**************************************** APEX CLASS ****************************************************

public class EHRTriggerHandler{
    
    public static List<Time_Sheet__c> UpdateEHRate(List<Time_Sheet__c> lstTS){ 
       List<Time_Sheet__c> timeList = new List<Time_Sheet__c>();
        System.debug('@@@@@@@1'+timeList);
       set<Id> TSIds = new set<Id>();
       Map<Id ,boolean> mapTimeSheet = new Map<Id,boolean>();
        for(Time_Sheet__c EHR : lstTS) {    
            TSIds.add(EHR.Employee__c);
        }                       
        
        List<Estimated_Hourly_Rate__c> EHRlist = [SELECT Id, Name,Employee__c,Start_Date__c,End_Date__c,Estimated_Hourly_Rate_Variable__c 
                                              FROM Estimated_Hourly_Rate__c 
                                              WHERE Employee__c =:TSIds];  
        
        Map<id,List<Estimated_Hourly_Rate__c>> mapEs = new Map<id,List<Estimated_Hourly_Rate__c>>();
        
        for (Estimated_Hourly_Rate__c c : EHRlist) {
                List<Estimated_Hourly_Rate__c> l = mapEs.get(c.Employee__c);
                if (l == null) {
                    l = new List<Estimated_Hourly_Rate__c>();
                    mapEs.put(c.Employee__c, l);
                }
            l.add(c);
        }
        
        boolean isMatchFound = false;        
        //if(EHRlist!=null && !EHRlist.isEmpty()) {
         for(Time_Sheet__c timeSheetRec :lstTS){
             Time_Sheet__c timee = new Time_Sheet__c();  
             
             List<Estimated_Hourly_Rate__c> listes = mapEs.get(timeSheetRec.Employee__c);
            for(Estimated_Hourly_Rate__c EHR : listes) {   
                     if(timeSheetRec.Record_Date__c >= EHR.Start_Date__c && timeSheetRec.Record_Date__c <= EHR.End_Date__c ){                    
                        timee.id = timeSheetRec.id;
                        timee.EHR_TS__c = EHR.Estimated_Hourly_Rate_Variable__c; 
                        //timeSheetRec.EHR_TS__c = EHR.Estimated_Hourly_Rate_Variable__c;  
                        isMatchFound = true;
                        
                    } 
                }
                
                 timeList.add(timee);              
            }  
          //}             
           
        if(!isMatchFound){
            lstTS[0].addError('The given Record date does not fall under any of the Estimated Hourly Rates record(s)');
        }
        
        return timeList;
  }  
}

it keeps return not writeable error... how should i resolve this error?
 
private List<Contact> contactList;

   public void addMore() {
    

        string nameT = Apexpages.currentPage().getParameters().get('nameT');
        string phoneT = Apexpages.currentPage().getParameters().get('phoneT');
        string emailT = Apexpages.currentPage().getParameters().get('emailT');

    system.debug(nameT + '//' + phoneT + '//' + emailT);


    Contact att = new Contact();

    att.name = nameT;
    att.phone = phoneT;
    att.email = emailT;

    contactList.add(att);


 //i want this parameters to List value but it doesnt work properly..
  • May 24, 2018
  • Like
  • 0
Vf 

<apex:page Controller="Task39PhoneValidation">
  <apex:sectionHeader title="Student" subtitle="Home"/>
  <apex:pagemessages />
  <apex:form >
    <apex:pageblock tabstyle="Student__c">
      <apex:pageblockbuttons >
        <apex:commandButton value="Save" action="{!submit}"/>
        <apex:commandButton value="Save&New" action="{!saveandnew}"/>
        <apex:commandButton value="Cancel" action="{!cmeback}"/>
      </apex:pageblockbuttons>
      <apex:pageBlockSection >
        
      <apex:pageBlockSection title="Student Details" >
        <apex:inputField value="{!st.Name}"/>
        <apex:inputField value="{!st.Last_Name__c}"/>
        <apex:inputField value="{!st.Dob__c}"/>
      </apex:pageBlockSection>
      <apex:PageBlockSection title="Additional Details">
        <apex:inputField value="{!st.Tenure__c}"/>
        <apex:inputField value="{!st.Course__c}"/>
        <apex:inputField value="{!st.Doctor__c}"/>
      </apex:PageBlockSection>
      <apex:pageBlockSection title="Contact Details">
        <apex:inputField value="{!st.Address__c}"/>
        <apex:inputField value="{!st.Permanent_Address__c}"/>
        <apex:inputField value="{!st.Mobile__c}"/>
      </apex:pageBlockSection>
      </apex:pageBlockSection>
    </apex:pageblock>
  </apex:form>
</apex:page>




Controller:

public with sharing class Task39PhoneValidation {
    
    Public Integer phn;
    
    public Task39PhoneValidation(){
        st = new Student__c();
        
    }

    public PageReference cmeback() {
        return null;
    }


    public PageReference saveandnew() {
        return null;
    }


    public PageReference submit() {
        phn = st.mobile__c.length();
        if(phn == 10 ){
            insert st;
        }
        else{
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING,'Your Phone number should have Only 10 digits not more than that or lesser then that .'));
        }
        
        return null;
    }


    public Student__c st { get; set; }
}
I am trying to change the "status" field(custom) of the contact object by using a batch. If I update the fields in the execute method then it gets updated but if I try to update it in the finish method then my list is empty. I am not getting this!
 
global class BatchNSchedulable implements Database.Batchable<sObject>{
	global list<contact> con=new list<contact>();
	String query = 'SELECT id,name,status__c FROM contact WHERE CreatedDate= Yesterday';
	global Database.QueryLocator start(Database.BatchableContext bc){
		System.debug('In the start');
		 return (Database.getQueryLocator(query));
	}
	global void execute(Database.BatchableContext bc,list<sObject> li){
		System.debug('In the execute');
		con = (list<contact>)li;
		System.debug(con.size());	
		for(contact ct:con){
			ct.put('status__c','None');
		}
		System.debug('con in execute is '+con);
	}
	global void finish(Database.BatchableContext bc){
		System.debug('con is '+con);
		update con;
		System.debug('In the finish');
	}

}

 
Hi,

I need to check a checkbox field once the picklist value is selected,
Here are the details,
picklist field - pick__c('abc','pqr')
checkbox field - check1__c,check__c


If pick__c is 'abc' automatically check1__c should be checked and check2__c should be left unchecked and vice versa.

 
Hi, we're a non profit org with very limited recources. Therfore thanks for any help since we don't have IT personal.
I wrote this follwing Apex-Code which apparentely needs testing before deployment. I guess it's not to hard, but I have no idea how to do it. Thanks!

public class PV_Stundenerfassung {
 
  public Contact getContact() {
    return [select id, name, PV_Soz_Abgeleistete_Stunden__c,
            (select name, PV_SE_Mitarbeiter__c, PV_SE_Datum__c, PV_SE_Stundenanzahl__c, LastModifiedBy.firstname, LastModifiedBy.lastname, LastModifiedDate, PV_SE_Datum_Anzeige__c, PV_SE_Zuletzt_geaendert_Anzeige__c
             from Stundenerfassung__r )
            from Contact where id =
             :System.currentPageReference()
             .getParameters().get('id')];
  }
}
I've been trying to create a trigger for a while and it is not going well, but I was tackling it wrong.  I have now created a field called Trigger_Help__c on the Opportunity Object and I need it to be unique.  I have found the following code and I think it needs to be something similar.  Is it possible someone could help me change it to work how I need?
 
Trigger

trigger leadDuplicatePreventer on Lead
                               (before insert, before update) {

    Map<String, Lead> leadMap = new Map<String, Lead>();
    for (Lead lead : System.Trigger.new) {
       
        // Make sure we don't treat an email address that 
        // isn't changing during an update as a duplicate. 
   
        if ((lead.Email != null) &&
                (System.Trigger.isInsert ||
                (lead.Email !=
                    System.Trigger.oldMap.get(lead.Id).Email))) {
       
            // Make sure another new lead isn't also a duplicate 
   
            if (leadMap.containsKey(lead.Email)) {
                lead.Email.addError('Another new lead has the '
                                    + 'same email address.');
            } else {
                leadMap.put(lead.Email, lead);
            }
       }
    }
   
    // Using a single database query, find all the leads in 
   
    // the database that have the same email address as any 
   
    // of the leads being inserted or updated. 
   
    for (Lead lead : [SELECT Email FROM Lead
                      WHERE Email IN :leadMap.KeySet()]) {
        Lead newLead = leadMap.get(lead.Email);
        newLead.Email.addError('A lead with this email '
                               + 'address already exists.');
    }
}

 
Hello everyone,

I am having some difficult deciding which tool should I use.

I read some user saying Ant migration tool is safer and easier to use. Could someone help to evaluate them?

Thanks!

Regards,

Pedro Motta
I  am trying to use the following  deduplication logic with Trigger on Candidate object to prevent inserting duplicates based on a unique key . However this logic  even prevents  me from inserting the first entry too which is not a duplicate . not sure  what I am doing wrong. Please advise.

Trigger:
trigger CandidateKeyTrigger on Candidate__c (before insert,before update) {
    CandidateKeyClass.candidatededuplicationmethod(Trigger.new);
}

Class:
public class CandidateKeyClass {
    public static void candidatededuplicationmethod(List<Candidate__c> newcandidates){
        Map<String,Candidate__c> newcandidatemap = new Map<String,Candidate__c>();
        //check the batch for duplicates
        for(Candidate__c cand:newcandidates){
                if(newcandidatemap.containsKey(cand.Unique_Key__c)){
                    cand.adderror('Duplicate name+email found in batch');
                }
                else{
                    newcandidatemap.put(cand.Unique_Key__c,cand);
                }
        }
        //check the db for duplicates
        if(!newcandidatemap.isempty()){
            for(List<Candidate__c> cands:[Select unique_key__c from Candidate__c where unique_key__c in :newcandidatemap.keyset()]){
                for(Candidate__c can:cands){
                    if(newcandidatemap.containsKey(can.Unique_Key__c){
                        newcandidatemap.get(can.Unique_Key__c).adderror('duplicate unique key found in salesforce with id ' + can.id);
                    }
                }
            }
        }
    }
}
 
trigger trigMapFields on Lead (before update) {

    Map<Home_Phone,String> leadHome = new Map<Home_Phone,String>(); // Map of the converted Contact phone and the Lead phone

    for(Lead lead : Trigger.new) {
        if (lead.IsConverted) {
            leadStatus.put(lead.ConvertedContactHome_Phone,lead.Home_Phone);
        }
    }
    List<Contact> conContacts = [select Phone from Contact WHERE Contact.Home_Phone IN :leadHome.keySet()];
    for ( Contact c : conContacts) {
        c.Phone = leadHome.set(Home_Phone);
    }
    update conContacts;
}

is this the correct trigger? can anyone correct me if i am wrong?
<b>Apex Class</b>

public class RenewOppEndate
{
     public static final string CRenewOppEndate = 'RenewOppEndate';
     public static final string UPDATEENDATE = 'updateEndate';
    
    public static void updateEndate(List<Opportunity> oppNewList)
    {
        try
        {
            set<Id> accIdSet = new set<Id>();
            Date TempEffDate = NULL;
            
            for(Opportunity opp: oppNewList)
            {
                if(opp.AccountId != NULL && opp.Type == Label.Renewal)
                {
                    accIdSet.add(opp.AccountId);
                }
            }
            Map<ID,Account> accMap = new Map<ID,Account>([select Id,(select Id,Effective_Date__c from Opportunities Order By Effective_Date__c DESC LIMIT 1) 
                                     from Account where ID IN:accIdSet LIMIT 50000]);
            
            for(Opportunity opp : oppNewList)
            {
                if(String.isNotBlank(opp.AccountId) && opp.Type == Label.Renewal){
                    Account accObj = accMap.get(opp.AccountId);
                    List<Opportunity> oldOppList = accObj.opportunities;
                    if(oldOppList != NULL && !oldOppList.isEmpty()){
                        Date tempEffectiveDate = oldOppList[0].Effective_Date__c; 
                        opp.Effective_Date__c = tempEffectiveDate != NULL ? tempEffectiveDate.addYears(1) : tempEffectiveDate ;
                    }
                }               
            }
        }
        catch(exception ex)
        {UTIL_LoggingService.logHandledException(ex);}
    }
    
}


<b>Test Class

</b>
<b>@isTest
public class RenewOppEndate_Test
{
    
    private static testMethod void renewOpptyTest()
    {   
        User testUser = Util02_TestData.createUser();
        
        Account testAccount = Util02_TestData.createAccountData();   
        
        System.runAs(testUser)
        {
           
            Database.insert(testAccount);
            
            Opportunity opp = Util02_TestData.createOpportunity();
            opp.AccountId = testAccount.id;
            opp.stageName = Label.Renewal;
            database.insert(opp);   
        }       
    }
        
}     </b>

 
static void testUpdate() {
    User userStandard = TestUtil.getUserStandardDE(0);
    System.runAs(userStandard) {
        Account accountBusiness= [Select Id from Account where Name = :TestUtil.ACCOUNT_BUSINESS_NAME LIMIT 1];
        Account accountBusinessDuplicate= [Select Id from Account where Name = 'DuplicateCompany' LIMIT 1];

        AccountDuplicate__c ad = new AccountDuplicate__c();
        ad.Account1__c = accountBusiness.Id;
        ad.Account2__c = accountBusinessDuplicate.Id;
        ad.Status__c = 'Open';
        ad.Criteria__c ='Other matches';

        Test.startTest();
        insert ad;


        ad.Remarks__c = 'changed';
        update ad;


        ad.Status__c = 'Rejected';
        update ad;


        ad.Status__c = 'Open';
        update ad;


        Test.stopTest();
    }
}
I want to send emails from apex, I'm using Visualforce email templates. This is my code:
 
EmailTemplate templateId = [Select id from EmailTemplate where DeveloperName = 'User_Template'];
OrgWideEmailAddress[] owea = [select Id from OrgWideEmailAddress LIMIT 1];

               	
for(User usr: users) {
    Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();

    if ( owea.size() > 0 ) {
        email.setOrgWideEmailAddressId(owea.get(0).Id);
    }
			
    email.setSaveAsActivity(false);
    email.setSubject('Test Subject');			
    email.setTargetObjectId(usr.Id);
    email.setTemplateID(templateId.Id); 

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

Email template:
<messaging:emailTemplate subject="Test" recipientType="User">
	<messaging:htmlEmailBody >
		this is a test
	</messaging:htmlEmailBody>
</messaging:emailTemplate>



It's sending the email but the body is empty. 

When sending from setup and using "Send Test and Verify Merge Fields" - it works - body is sent.

I've tried this: Sending Emails in Salesforce to Non-Contacts Using Apex . It throws an error a null reference error, I've checked in the log and the emailBody is null.

I've tried setting email.setWhatId(usr.Id);  - no change

The only solution that worked was building the message as string in apex and using email.setHtmlBody(someString);

However I'm curious of why using the template doesn't work, any help would be highly appreciated.
Hi,

I'm writing test code for a new class that allows you to add multiple Competitors to an Opportunity. I've got the code and visualforce page working, although I'm having a bit of a tough time on the test code as I'm not really sure how to go about getting coverage for adding or removing a row. Maybe I'm overthinking the whole thing, but here's what I've got so far. Any help would be greatly appreciated. I'm more admin-based than developer so it's a little out of my wheelhouse.

Class
 
public with sharing class OpportunityCompetitor{

    public List<Opportunity_Competitor__c> oppComp {get; set;}
    private final Opportunity opp;
    public OpportunityCompetitor(ApexPages.StandardController cstmController) {
        Opp=(Opportunity)cstmController.getrecord();
        oppComp = new List<Opportunity_Competitor__c>();
        Opportunity_Competitor__c OpptyComp = new Opportunity_Competitor__c();
        OpptyComp.Opportunity__c = opp.id;
        oppComp.add(OpptyComp);
        } 
    
    public void addrow(){
        Opportunity_Competitor__c OpptyComp = new Opportunity_Competitor__c();
        OpptyComp.Opportunity__c = opp.id;
        oppComp.add(OpptyComp);}
    
     public void removerow(){
        Integer i = oppComp.size();
        OppComp.remove(i-1);}
    
    public PageReference save(){
        
   //error handling //   
   try{
      insert OppComp;
    }
      catch(Exception e){
           ApexPages.addMessages(e);
       return null;
    }
      
     
    // redirect the user back to the Opportunity record //        
        PageReference opprec = new PageReference('/'+opp.id);
        opprec.setRedirect(true);
        return opprec;
    }
}

Visualforce Page
<apex:page extensions="OpportunityCompetitor" tabStyle="Opportunity" standardController="Opportunity">
    <apex:form >
      <apex:sectionheader title="Opportunity Competitors" subtitle="{!Opportunity.Name}" />
            <apex:pageBlock >
        <p>
          Add one or more Competitors for this Opportunity. You can find competitors by using the Competitor lookup
           or by typing a name in the Competitor field. Click Add Row to enter multiple records or Remove Row to delete rows.  
       </p>
       <p>
        Click Save to add all entered Competitors to the Opportunity. Click Cancel to return to the Opportunity 
        record without saving. All data entered will be lost if you click Cancel.
       </p>
        <br />
        <apex:pageMessages />
        
            <apex:pageBlockButtons location="bottom">
                <apex:commandButton value="Save" action="{!save}" />
                <apex:commandButton value="Cancel" action="{!cancel}" />
            </apex:pageBlockButtons>
        
             <apex:pageblocktable value="{!OppComp}" var="OC" Title="Opportunity Competitors" id="table">
                      
         <!-- prevent users changing the Opportunity -->
         <apex:column headervalue="Oppportunity" rendered="false">
            <apex:inputfield value="{!OC.Opportunity__c}" style="width:250px;" />
        </apex:column>
         
         <apex:column headervalue="Competitor" >
           <apex:inputfield value="{!OC.Competitor__c}" style="width:290px;" />
        </apex:column>
                 
        <apex:column headervalue="Won" >
           <apex:inputfield value="{!OC.Won__c}" style="width:290px;" />
        </apex:column>
    
            </apex:pageBlockTable>
                      
              <div style="text-align:right;margin-right:10px;font-weight:bold;">       
                     <apex:commandLink value="Add Row" action="{!addRow}" rerender="table,error" immediate="true" /> &nbsp;|&nbsp;
                    <apex:commandLink value="Remove Row" action="{!removeRow}" rerender="table,error" immediate="true" />   
        </div>
            
        </apex:pageBlock>
    </apex:form>
</apex:page>
Test Code
@isTest
private class testOpportunityCompetitor{
      
       static testMethod void testOpportunityCloseExtOpp() {
        
       Id AcctRecordTypeId = Schema.SObjectType.Account.getRecordTypeInfosByName().get('Sales Accounts').getRecordTypeId();
       Id CompRecordTypeId = Schema.SObjectType.Account.getRecordTypeInfosByName().get('Competitor Accounts').getRecordTypeId();
       Id OppRecordTypeId = Schema.SObjectType.Opportunity.getRecordTypeInfosByName().get('Standard').getRecordTypeId();
          
       //Create an account //
        Account acc = new Account();
        acc.Name='Account';
        acc.Type='Prospect';
        acc.recordTypeId = AcctRecordTypeId;
        insert acc;
     
        //Create an Opp //
        Opportunity Opp = new Opportunity();
        
        opp.recordTypeId = OppRecordTypeId;
        opp.name='test opp';
        opp.AccountId=acc.Id;
        opp.Type='NewBusiness';
        opp.Opportunity_Segment__c='Test';
        opp.closeDate=date.today();
        opp.StageName='New';
        opp.LeadSource='Cold Call';
        insert opp;          
       
        //Create a competitor account //
        Account acd = new Account();
        acd.Name='Competitor';
        acd.Type='Competitor';
        acd.recordTypeId = CompRecordTypeId;
        insert acd;
           
        List<Account> Comptr = [SELECT id from Account WHERE Id = :acd.id];
        List<Opportunity> oppList = [SELECT id from Opportunity WHERE Id = :opp.id];
    
        Opportunity_Competitor__c oppComp = new Opportunity_Competitor__c();
        oppComp.Opportunity__c=opp.Id;
        oppComp.Competitor__c=acd.ID;
        insert oppComp;
              
        Test.startTest();
        PageReference pageRef = Page.OpportunityCompetitor;
        Test.setCurrentPageReference(pageRef);
        
        /* Standard controller for the Opportunity */
        ApexPages.StandardController stdCon = new ApexPages.StandardController(opp);
        
        /*Construct the controller extension with the standard controller arg*/
        OpportunityCompetitor Ext = new OpportunityCompetitor(stdCon);
        PageReference oppPage = Ext.save();
        System.assert(oppPage != null);             
        Test.stopTest();
        }
          
          
      
}


 
Hi ,
I'm very new to triggers and managed to write a trigger and it works in Sandbox  and it's test cass is success but not covering code coverage show only 0. Unable to achieve code coverage, any suggestions to direct me to achieve my 100% code coverage.

I appreciate you help in advance!!

My trigger:

trigger parentCaseClose on case(before update)
{
    set<id> openCaseIDs = new set<id>();
    
    for(case caseList : [select id, ParentId, status from case where ParentId In:trigger.newMap.keyset() AND status != 'Closed'])
    {
        openCaseIDs.add(caseList.ParentId);
    }
    
    for(case newCase : trigger.new)
    {
        if(newCase.status != trigger.oldMap.get(newCase.id).status && newCase.status == 'Closed' && openCaseIDs.contains(newCase.id))
        {
            newCase.addError('The associated child cases are open');
        }
    }
}



My Test class:

@isTest

private class TestParentCaseCloseValidation {
   
  public static List<Case> createCase(string caseStatus) {
     // test account insert
    Account a = new Account();
       a.Name = 'sample account';
       insert a;
    // test contact insert
     Contact c = new Contact();
        c.FirstName = 'Test';
        c.LastName = 'contact';
        c.AccountId= a.Id;
        insert c;
        
     List<Case> cases = new List<Case>();
    // string caseStatus = 'In Progress';
     Case parent = new Case( Subject='TEST', contactID = c.id,Status=caseStatus );
        insert parent;
       
     cases.add(parent);
       // system.debug('insert parent',cases.isEmpty());
    
     Case child1 = new Case(Subject='child1',  contactID = c.id, Status=caseStatus,ParentId=parent.Id);
        insert child1;
        cases.add(child1);
    
    
     Case child2 = new Case(Subject='child2', contactID = c.id, Status=caseStatus,ParentId=parent.Id);
        insert child2;
        cases.add(child2);
        return cases;
    
    
    
 }
   
     static testMethod void testCloseParent() {
      
        List<Case> cases = createCase('In Progress');
            String parentId = null;
     //Update one of the children and see that the parent stays open
          for (Case c:cases) {
              if (c.ParentId!=null) {
                  parentId = c.ParentId;
                  c.Status = 'Closed';
                 
                }
          }
        update cases;
        //Shouldn't be closed yet
            Case parent = [select IsClosed from Case where Id=:parentId];
                System.assert(parent.IsClosed==false);
               
             for (Case c:cases) {
                    if (c.ParentId!=null && c.Status!='Closed') {
                        parentId = c.ParentId;
                        c.Status = 'Closed';
                       
                      
                    }
                }update cases;
        
       
    
       
        test.startTest();
                          
    try
   
        {
            update parent;
 
        }

        catch(System.DMLException e)

        {

            System.assert(e.getMessage().contains('There are still Child Cases Open '));

        }
     test.stopTest();
    }
}
I am new to apex so just trying my best. I know this is not right but this is what I am working with so far. Any insight would be greatly appreciated.

trigger channelpartner on Task (after insert) {
for (task t : Trigger.new) {
if(acct.channel_object != null){

Task tsk = new Task(),
accList.add(c.accountID)

t.channel_partner = acct.channel_object

tasks.add(tsk);}
}
insert tasks;
}
I am trying to write a trigger to compare the area code from the lead phone and the Area Code name, pull the Parent Market from the Area Code and populate it on a field in the Lead upon creation. The relationship between the 3 objects are: 
Area_Code__c (child Object of Market__c)
Market__c(Custom Object with master-detail to Area_Code)
Lead(Lookup relationship to Market__c called Lead_Market__c)
I created a formula field on the lead object to pull the area code out of the phone number on lead and it is called Area_Code__c.
I have created this Trigger and it saves but and I am not getting any errors but it is not populating the Lead_Market__c field either. According to the debug logs the problem seems to be in the last for loop called  LeadNameLoop. Does anyone see anything wrong with this?
Trigger AreaCode on Lead (before insert) {

Set <String> InitialLeadName = new Set <String> ();

for(Lead LeadNameLoop : trigger.New)
{
    InitialLeadName.add(LeadNameLoop.Area_Code__c);
}
Map <String, Area_Code__c> matchingAreaCodeMap = new Map <String, Area_Code__c> ();

for (Area_Code__c Record : [Select Id, Name, Market__c From Area_Code__c Where Name IN :InitialLeadName])
{
    matchingAreaCodeMap.put(Record.Market__c, record);
}

List <Lead> FinalLeadList = new List <Lead> ();

    for(Lead LeadNameLoop : trigger.New)
{
    if (matchingAreaCodeMap.get(LeadNameLoop.Name) != null)
    {
          LeadNameLoop.Lead_Market__c = matchingAreaCodeMap.get(LeadNameLoop.Area_Code__c).Market__c;
         FinalLeadList.add(LeadNameLoop);
    }
} 
upsert FinalLeadList;
}
I am facing coverage issue in my test class,please suggest
CLASS
public class SurveyDetailViewPage {
    String Id;
    public Survey_Mcd__c smc;
    public SurveyDetailViewPage(ApexPages.StandardController controller) {
    Id = ApexPages.Currentpage().getParameters().get('id');
    this.smc = (Survey_Mcd__c)controller.getRecord();
    }

}


TEST CLASS

@isTest
private class TestsurveydetailViewPage {
  static testMethod void myUnitTest1() {
  
        Test.startTest();
        Survey_Mcd__c smc = new Survey_Mcd__c();
        smc.Survey_Name__c = 'McDonald';
        smc.Question__c = 'Test';
        smc.X5_Scale_Rating__c = false;
        insert smc;
        
List<Survey_Mcd__c> smcRecord = new List<Survey_Mcd__c>();
smcRecord = [Select Id From Survey_Mcd__c where Id=:smc.Id LIMIT 1];
if(smcRecord.size()>0)
ApexPages.Currentpage().getParameters().put('id',smcRecord.get(0).Id); 
        Test.stopTest();
    }
}
I am trying to get increase code coverage for this code which is part of unmanaged package.
I could get onlyy 12 lines out of 51 .Which is casuing for my other code to fail in deployment.

Please help me.

this is the apex class
public class CreateStatementPDFConroller{
public String todayDate {get;set;}
public  String ids {get;set;}
public Map<String,accountInDirectPrice> accountInDirectPriceMap{get;set;}

public Map< Account , List< AcctSeed__Billing__c > > accountBillingMap {get;set;}
    public CreateStatementPDFConroller(){
        
        accountInDirectPriceMap = new Map<String,accountInDirectPrice>();
        
        List<Account> accList = [Select Id,Name,Account_Code__c,AcctSeed__Billing_Contact__r.Email FROM Account WHERE Balance_Remaining__c > 0 AND RecordType.Name =: Label.SubAgentAccount];
        ids = '';                                             
        for(Account acc:accList) {
            ids += acc.Id + ',';
        }
        
        todayDate = Datetime.now().format('MM/dd/yyyy');
        accountBillingMap = New Map< Account , List< AcctSeed__Billing__c > >();
        // parameter ids 
             //ids = ApexPages.currentPage().getParameters().get('id');
        if( String.IsNotBlank( ids ) ){
            List< String > idLst = ids.split(','); 
            
            Map< Id , Account > accountMap = New Map< Id , Account >([SELECT Id, Account_Code__c, Name, BillingStreet, BillingCity, BillingState, BillingPostalCode, BillingCountry 
                                  FROM Account 
                                  WHERE Id IN : idLst]);
            // fill account to map                       
            for( Account ac : accountMap.values() ){
                accountBillingMap.put(ac , New List< AcctSeed__Billing__c >());
                accountInDirectPrice accval = new accountInDirectPrice();
                accountInDirectPriceMap.put(ac.id,accval);
            }   
                               
            List< AcctSeed__Billing__c > billing = [SELECT Id ,AcctSeed__Age__c ,Name, AcctSeed__Customer__r.Name,Insured__c,AcctSeed__Status__c,AcctSeed__Proprietary_Billing_Number__c,AcctSeed__Date__c,Policy__r.Billing_Company__r.Name,Policy__r.Effective_Date__c,Policy__r.Name,AcctSeed__Due_Date2__c,Policy__r.Name_Insured__c,Policy__r.Policy_Type__c,Policy__r.Status_Type__c,
                                          Sub_Agent_Percent__c,Sub_Agent_Commission_Total__c,Transaction__r.Transaction_Amount__c,Transaction__r.Account__r.Name,AcctSeed__Total__c,Transaction__r.Name,Amount_Due__c,Billing_Type__c,AcctSeed__Balance__c,AcctSeed__Received_Amount__c  FROM AcctSeed__Billing__c 
                                          WHERE AcctSeed__Customer__c IN : idLst  ];
            if( !billing.IsEmpty() ){
                for( AcctSeed__Billing__c ab : billing ){
                    if( accountMap.containsKey(ab.AcctSeed__Customer__c) && accountBillingMap.containsKey(accountMap.get(ab.AcctSeed__Customer__c) ) ){
                       
                        //ab.AcctSeed__Date__c = date.ValueOf(DateTime.newInstance(ab.AcctSeed__Date__c.month(),ab.AcctSeed__Date__c.day(),ab.AcctSeed__Date__c.year()).format('d-MM-YYYY'));
                        accountBillingMap.get(accountMap.get(ab.AcctSeed__Customer__c)).add(ab);
                    }
                    
                    if(accountMap.containsKey(ab.AcctSeed__Customer__c)){
                            
                            if(accountInDirectPriceMap.containsKey(ab.AcctSeed__Customer__c) && ab.AcctSeed__Age__c != null && ab.AcctSeed__Age__c != '' && ab.AcctSeed__Age__c != 'Closed'){
                                
                                accountInDirectPrice accval = accountInDirectPriceMap.get(ab.AcctSeed__Customer__c);
                                if(ab.AcctSeed__Age__c == '0-Current'){
                                    
                                    accval.currentPrice += ab.AcctSeed__Balance__c;
                                
                                } else if(ab.AcctSeed__Age__c == '1-30 Days'){
                                    
                                    accval.to30Days += ab.AcctSeed__Balance__c;
                                    
                                } else if(ab.AcctSeed__Age__c == '31-60 Days'){
                                    
                                    accval.to60Days += ab.AcctSeed__Balance__c;
                                    
                                } else if(ab.AcctSeed__Age__c == '61-90 Days'){
                                    
                                    accval.to90Days += ab.AcctSeed__Balance__c;
                                    
                                } else if(ab.AcctSeed__Age__c == 'Over 90 Days'){
                                                                    
                                    accval.over90days += ab.AcctSeed__Balance__c;
                                }
                                
                                accountInDirectPriceMap.put(ab.AcctSeed__Customer__c,accval);
                                
                                
                            }  
                     }
                }
            }
        }        
    }
    
    public class accountInDirectPrice{
      
      public Decimal currentPrice {get;set;}
      public Decimal to30Days{get;set;}
      public Decimal to60days{get;set;}
      public Decimal to90days{get;set;}
      public Decimal over90days{get;set;}
      
      public accountInDirectPrice(){
          
          currentPrice = 0;
          to30Days = 0;
          to60Days = 0;
          to90Days = 0;
          over90days = 0;
      }
    }
}

test class
 
@isTest
public class CreateStatementPDFConrollerTest {
    @isTest
    public static void unitTest(){
        List<Account> accountLst = new List<Account>();
        Account accObj1 = new Account(Name='test',Balance_Remaining__c=20);
        accountLst.add(accObj1);
        Account accObj2 = new Account(Name = 'test',Balance_Remaining__c=23);
        accountLst.add(accObj2);
        insert accountLst;

        RecordType RecordType1 = [SELECT Id from RecordType where name='General Liability' and sobjecttype = 'Policy__c'];
        
        Policy__c policyObj = new Policy__c();
        policyObj.recordTypeId = RecordType1.Id;
        policyObj.Account__c = accountLst[0].Id;
        policyObj.Name = 'test';
        policyObj.Agency_Commission__c = 10.1;
        policyObj.Billing_Type__c = 'Agency Bill';
        policyObj.Billing_Company__c = accountLst[1].Id;
        insert policyObj;
        
        Transaction__c transObj = new Transaction__c();
        transObj.Account__c = accountLst[0].Id;
        transObj.Policy_Name__c = policyObj.Id;
        transObj.Transaction_Amount__c = 10;
        transObj.Tran_Code__c = 'Audit Premium- Add';
        transObj.Client_Type__c='Direct Insured';
        insert transObj;
        
        AcctSeed__Accounting_Period__c accountingPeriod = new AcctSeed__Accounting_Period__c();
        accountingPeriod.Name = '2016-12';
        accountingPeriod.AcctSeed__Start_Date__c = System.today().addDays(792);
        accountingPeriod.AcctSeed__End_Date__c = System.today().addDays(7888);
        accountingPeriod.AcctSeed__Status__c = 'Open';
        insert accountingPeriod;
        
        AcctSeed__Billing_Format__c billingformatObj = new AcctSeed__Billing_Format__c();
        billingformatObj.name = 'test';
        billingformatObj.AcctSeed__Type__c = 'Billing';
        billingformatObj.AcctSeed__Visualforce_PDF_Page__c = 'BillingActivityStatementPDF';
        billingformatObj.AcctSeed__Default_Email_Template__c = 'Activity_Statement_Email_Template';
        insert billingformatObj;
        
        AcctSeed__Billing__c billingObj = new AcctSeed__Billing__c();
        billingObj.AcctSeed__Status__c = 'In Process';
        billingObj.AcctSeed__Customer__c = accountLst[1].Id;
        billingObj.Transaction__c = transObj.Id;
        billingObj.Policy__c = policyObj.Id;
        billingObj.AcctSeed__Date__c = System.today().adddays(76);
        billingObj.AcctSeed__Accounting_Period__c = accountingPeriod.Id;
        billingObj.AcctSeed__Billing_Format__c = billingformatObj.Id;
        insert billingObj;
        
        ApexPages.currentPage().getParameters().put('id',accountLst[0].id);
        CreateStatementPDFConroller controllerObj = new 
        CreateStatementPDFConroller();
        
       

    }
}

 
Hi All,

Please help me on below issue.


1. Trigger will work on user mode or system mode
2. In below class account is having one contact but one user able to see contact another user not why another user not able to see contact please help me.

3. As per my knowledge below class will work on system mode.
4. Please help me why another user not ble to see the contact.
 
trigger sampleTrigger on account(after update){
  AccountHelper.Createcontact(Trigger.new);
}

If account type == hot then i need create one conatct for account only one contact.
If contact is existing then no need to crete contact.

public class AccountHelper{

 public static void Createcontact(list<account> accs){
  set<id> acciDs = new set<id>(); 
  for(account acc : accs){
   if(acc.type == 'hot'){    
      acciDs.add(acc.id);   
   } 
 }
 list<account> accslist = [select id,name,(select id from contacts) from acount];
 
 for(account acc : accslist){
     if(acc.contacts.size()== 0){
	 
	    //crating contact here 
	 }
 
 }
}

 
If anybody aware on deleting territories  can help me  because we could not able to delete territories  even though we had "Managed Territories"  permission in profile level. The  territory  trying to delete don't have child  territory but have parent territory.So while deleting I am getting the following error  below.

Error:  
Cannot Delete the Territory
You cannot delete the territory because at least one territory rolls up to it. 

could you please help on this.
I'm looking for a side gig, about 30 hours a week.

My certficiations: http://certification.salesforce.com/certification-detail-print?conId=003G000002FKbh3IAD

I have about 5 years experience with Salesforce. Please send an email: varaprasad4sfdc@gmail.com email for a resume.

Thanks
Varaprasad
@For Support : varaprasad4sfdc@gmail.com
Some users having issue with list views .
Ex : 

DETAILED DESCRIPTION:
1) select a personalized view (here e.g. 003 - My cases in process).
2) open a case out of this list (here e.g. CAS001).
3) go back to the case list by pressing the "Back-Arrow" of the browser .
 
The wrong list of cases is displayed Here.

Any help really appreciated.

Thanks
Varaprasad
Hi ,

Some times in chatter Chatter bold ,italic buttons are not displaying.
User-added image

Please let me know the reason .

Thanks
Varaprasad
 
Hi I have come across the below error, using JavaScript in Button.

An error has occurred while processing your request. The salesforce.com support team has been notified of the problem. 
If you believe you have additional information that may be of help in reproducing or correcting the error, please contact Salesforce Support.
 Please indicate the URL of the page you were requesting, any error id shown on this page as well as any other related information.
 We apologize for the inconvenience. 

Thank you again for your patience and assistance. And thanks for using salesforce.com! 

Error ID: 1652772134-27944 (-1092651723)
 
{!REQUIRESCRIPT("/soap/ajax/15.0/connection.js")}
{!REQUIRESCRIPT("/soap/ajax/15.0/apex.js")}
var r = "{!Opportunity.Opportunity_Product_Count__c}";
var oppid = "{!Opportunity.Id}";
 

if(r == 1 )
{        
                    window.location.href='/apex/VFPageName?id='+oppid;
}
else
{
    alert ("No Products exists !");

Please help me out with alternative solution ASAP
Hi All,

i need to create one validation rule..

User-added image

in each prefernce picklist field i have 3 values
primary
ok to contact
do not contact

Among all 6 fields i need to select only one field value is primary....


Any Help really Appreciate...

Thanks
varaprasad


 
I have a Parent Object called "Treatement" and a child object "Infusion". For a particular treatement we have to create infusion records. the 1st Infusion record should have infusion number (a field in Infusion) as 1 and 2nd record should have infusion number as 2 , and the count should continue. 

How to achive this..

Thanks 
Hi Everyone.

  i need small help regarding on schedule apex.
  how we will schedule one class with different timings.
EX:i want to schedule one class :  Runs at 4:20; 7:50: 16:20; 20:50 CET these timings.

Thanks in Advance


 
Hi All ,

   i am writing test class for following schedule class 
      global class scheduleAccountWriteXML implements Schedulable{
    
    // Execute method
    
    global void execute(SchedulableContext SC) {
        
        try{
      
// Code to be executed when the schedule class wakes up

            
            CalloutAccountRequest.basicAuthCalloutRequest();
           
            String CRON_EXP = '0 0 * * * ?';
            string jobName = 'Account_Interface_Schedule_job_that_runs_every_1_hour_for_Accounts'; 
            scheduleAccountWriteXML p = new scheduleAccountWriteXML();
            system.schedule(jobName, CRON_EXP, p);              
            
        }     
        
        Catch (Exception e){            
            
            Messaging.SingleEmailMessage emailMessage = new Messaging.SingleEmailMessage();
           
            emailMessage.setToAddresses(new String[] { 'varaprasad.vemula@accenture.com'});
            emailMessage.setSubject('Subject');
            
          
            emailMessage.setPlainTextBody(e.getmessage());
         
            Messaging.SendEmailResult[] emailResult = Messaging.sendEmail(new Messaging.SingleEmailMessage[] { emailMessage}, true);
        }
    }
}

I received code 90%,but test execution will be fail .

@isTest
public class Test_scheduleAccountWriteXML {
    public static testmethod void testaccountxml(){
    Test.StartTest();
              
            String CRON_EXP = '0 0 * * * ?';           
            scheduleAccountWriteXML scc6= new scheduleAccountWriteXML();       
            String jobid = system.schedule('varam', CRON_EXP, scc6);  
        
     Test.StopTest();  
        
         
    }
}


Any help please.


 
Hi Everyone ,

i created one class for generating xml file and by using callouts i am sending file to external system.
Here my requirement is 
  EX : file is more than one mb 1.5 mb
          i need to split xml file one is 1MB
                                          2nd one is 0.5mb
                                           is it possible to split file,,,,  Give me some ideas

Thanks all.
 
Hi

    I need to create multiple tasks in single page and i need to assign to user.Through vf page how we will implement this one .

 We need to have a VF section  so that from same page I can create multiple tasks without navigating to different page. Essentially in new task we need to have all the fields and can only refer what is in Action plan. 

Thanks to all ....
 

 
Hi All

   A and B are objects having lookup relationship
   A is parent and having status field
   B is child having status field
here my requiremeent is parent is having n on of childs in child what is the staus field value i need to update same thing in parent....

Thanks to alll
 
Hi I have come across the below error, using JavaScript in Button.

An error has occurred while processing your request. The salesforce.com support team has been notified of the problem. 
If you believe you have additional information that may be of help in reproducing or correcting the error, please contact Salesforce Support.
 Please indicate the URL of the page you were requesting, any error id shown on this page as well as any other related information.
 We apologize for the inconvenience. 

Thank you again for your patience and assistance. And thanks for using salesforce.com! 

Error ID: 1652772134-27944 (-1092651723)
 
{!REQUIRESCRIPT("/soap/ajax/15.0/connection.js")}
{!REQUIRESCRIPT("/soap/ajax/15.0/apex.js")}
var r = "{!Opportunity.Opportunity_Product_Count__c}";
var oppid = "{!Opportunity.Id}";
 

if(r == 1 )
{        
                    window.location.href='/apex/VFPageName?id='+oppid;
}
else
{
    alert ("No Products exists !");

Please help me out with alternative solution ASAP
Hi All,

i need to create one validation rule..

User-added image

in each prefernce picklist field i have 3 values
primary
ok to contact
do not contact

Among all 6 fields i need to select only one field value is primary....


Any Help really Appreciate...

Thanks
varaprasad


 
trigger SVMXUPG_convertNumberToWord on SVMXC__Quote__c (before insert, before update) {
    EnglishNumberToWords enw = new EnglishNumberToWords();
    for(SVMXC__Quote__c Quote: Trigger.new){
        Quote.Net_Amount_in_Text__c = enw.convert(Quote.Total_After_VAT__c);
    }
}
 
Hi all - We need to query a list of parent IDs for which all related record have a status = closed. In our case, the parent object is Contact and children are a Custom Object. Once we have the list we'll update a field on the Contact.

Can someone help with the SOQL query / list part?

Thanks!
I am getting this error for the below code--->The markup in the document following the root element must be well-formed.

<apex:page controller="AddMultipleAprrovers"  sidebar="False"  showheader="False"/>

    <apex:form>
        
        <apex:commandButton value="Add" action={!addRow}/>
        
        <apex:Repeat value="{!formList} var="form"/>
        
          <c:Case_Task_From ca="{!form}"/>    
        
        </apex:Repeat>

    </apex:form>

</apex:page>
Hello,

The business requirement is to have a lookup relation ship between a Contract and Opportunity. A field on the opportunity must get the SUM of a custom field on the Contracts which belong to the opportunity.

On mass update, I get an error "first error: UNABLE_TO_LOCK_ROW, unable to obtain exclusive access to this record"

After I lock the Account record, I get "First error: Record Currently Unavailable: The record you are attempting to edit, or one of its related records, is currently being modified by another user. Please try again."
 
public class contractRollUpCLASS {
    @future
    public static void calculate(Set<Id> recordIds) {
  
    List<Contract> contrList = [SELECT Id, AccountId, Renewal_Opportunity__c FROM Contract WHERE Id IN : recordIds];
    Set<Id> oppIds = new Set<Id>();
    Set<Id> accIds = new Set<Id>();
    
    for(Contract con : contrList) {
        oppIds.add(con.Renewal_Opportunity__c);
        accIds.add(con.AccountId);
        
    }
        
//lock the account
    List<Account> accList = [SELECT Id FROM Account WHERE Id IN : accIds FOR UPDATE];
    
    
    //Map will contain one Opportunity Id to one sum value.
    map<Id, Double> OpportunityMap = new Map<Id,Double>();
    
    List<Opportunity> oppsToUpdate = new List<Opportunity>();
    
    //aggregate result.
    for(AggregateResult q : [SELECT Renewal_Opportunity__c, SUM(Latest_PD_Renewal_Amount__c) sumLatest FROM Contract WHERE Renewal_Opportunity__c IN : oppIds AND Latest_PD_Renewal_Amount__c != null GROUP BY Renewal_Opportunity__c]) {
  
        OpportunityMap.put((Id)q.get('Renewal_Opportunity__c'),(Double)q.get('sumLatest'));
    }
    
    for(Opportunity opp : [SELECT Id, Annual_Maintenance_Value__c, AccountId FROM Opportunity WHERE Id IN : oppIds]) {
 
        Double sumLatestPD = OpportunityMap.get(opp.Id);
        opp.Annual_Maintenance_Value__c = sumLatestPD;
        oppsToUpdate.add(opp);     
    }    

        update oppsToUpdate;   

    }
}


Any ideas how I can bypass this issue?
Thanks,

Angel

Hi All,

I am trying to bring shipping information from XPO Logistics into Salesforce.  I was given a bearer token and I have to go through Postman to refresh the token every 12 hours.  Will I need to do an OAuth?  If so, will the callback URL be the Postman, the XPO Logistics or Salesforce?  I am very confused about what the callback URL does, and how I would get the callback URL if I need to get one on Postman.  Please help!
Hello,

I am trying to create Parent & Child records in single DML statement, I am able to do the same for most of the object, but I have a requirement to create Account and Task in single DML.

I am getting "Field is not writeable: Task.What" error message. Here is the code I am trying to do so:


Account accReference = new Account(
     Autodesk_CSN__c ='1322'//external id
);

Account acc = new Account(Name='test', Autodesk_CSN__c='1322');

Task task = new Task();
task.What = accReference, // here is the problem, not sure what would be the relationship field name to refer parent?
task.ActivityDate=Date.Today(),
task.Subject = 'Testing',
task.Priority = 'High',
task.OwnerId = UserInfo.getUserId();

Database.SaveResult[] results = Database.insert(new SObject[] { acc, task });

Any help would be appreciated.

Thanks,
Tarun
Hi, I'm trying to write a test class for the below:
global class EmptyDeletedRecords implements Database.Batchable<sObject>, Schedulable{   
    global EmptyDeletedRecords(){}

    global Database.QueryLocator start(Database.BatchableContext bc){
        return Database.getQueryLocator([Select id from Deleted_record__c where CreatedDate <LAST_N_DAYS:5]);
    } 

    //Execute method for the Schedulable interface
    global void execute(SchedulableContext sc){   
        //execute the batch
        EmptyDeletedRecords deleteCS = new EmptyDeletedRecords();
        ID batchprocessid = Database.executeBatch(deleteCS);
    }

    //Execute method for the batchable interface
    global void execute(Database.BatchableContext BC, list<sObject> scope){     
        delete scope;   
        DataBase.emptyRecycleBin(scope); 
    }

    global void finish(Database.BatchableContext BC){}
}
But am not sure how to test the scope deletion:
@isTest
private class EmptyDeletedRecords_Test{
  @testSetup
  static void setupTestData(){
    test.startTest();
    Deleted_record__c deleted_record_Obj = new Deleted_record__c(Deleted_ID__c = '5001p00002O54P2AAJ', External_ID__c = 'null', Object_Type_From_Apex__c = 'Case_with_custom_object');
    Insert deleted_record_Obj; 
    test.stopTest();
  }
    
    static testMethod void testBatch(){
    SchedulableContext sc = null;
    EmptyDeletedRecords tsc = new EmptyDeletedRecords();
    tsc.execute(sc);
  }
}
Any advice how to test that? Thanks!

 
I have been trying to use static resources to test a piece of code I wrote and am trying to validate and deploy on my production org. I created a static resource called GDPR that houses the JSON. Then I wrote a private test class that mocks up a response then calls my method. The problem is no matter what I do I cant seem to make salesforce use the static resource when its validating my code. I will include all my code below, what do I need to modify to make this work properly?

WRAPPER:
public class GDPRWrapper{

    public GDPRWrapper(List<GDPRData> templst){
            GDPRList = templst;
        }
    public List<GDPRData> GDPRList {get; set;}

    public class GDPRData {

        public Integer gdprId {get; set;}  //26636
        public String firstName {get; set;}
        public String lastName {get; set;}
        public String email {get; set;}
        public String phone {get; set;}
        public String accountName {get; set;}
        public String contactId {get; set;}    //AA111222333AAAe
        public String emailHash {get; set;}    //78fcb5ad502033c46d35abcecb3615bd92757fb0451485a19b27b7515f6d82d0
        public String createDate {get; set;}   //2018-05-17T15:19:37.000+0000
        public String responseDate {get; set;} //2018-05-21T10:38:53.000+0000
        public String notifyDate {get; set;}
        public boolean marketing {get; set;}
        public boolean security {get; set;}
        public boolean support {get; set;}
        public boolean contactPhone {get; set;}
        public boolean contactEmail {get; set;}
        public boolean contactOther {get; set;}
        public boolean invalid {get; set;}
        
        
    }
   public static List<GDPRData> parse(httpResponse json){
        return (List<GDPRData>) System.JSON.deserialize(json.getBody(), List<GDPRData>.class);
    }
 
    
}

Web Callout Class:
 
public class JSONDeserialize {

    public GDPRWrapper wrapper {get;set;}
   
    
    @Future(callout=true)
    public static void deserialize() {
        GDPRWrapper wrapper;
    
        
        Http h = new Http();
        HttpRequest request = new HttpRequest();
        
        request.setEndPoint('**********************');
        Blob headerValue = Blob.valueOf('d18849ea4155:d83ce6ef3dbe');
        String authorizationHeader = ('Basic ' + EncodingUtil.base64Encode(headerValue));
        
        
        request.setHeader('Authorization', authorizationHeader);
        request.setMethod('GET');
        try{
        HttpResponse response = h.send(request);
        
        System.debug('JSON RESPONSE: ' + response);
        List<GDPRWrapper.GDPRData> obj = GDPRWrapper.parse(response);
        wrapper = new GDPRWrapper(obj);
        
        System.assert(wrapper.GDPRList!=null);
        updateData(wrapper);
        }catch(JSONException j){
                    System.debug('An unexpected error has occured: ' + j.getMessage());
                }

      }
      
      
      public static void UpdateData(GDPRWrapper wrapper){
        List<Contact> contactPref = new List<Contact>();
        List<Contact> newContacts = new List<Contact>();
          
        for(Integer i = 0; i < wrapper.GDPRList.size(); i ++){
        if(wrapper.GDPRList[i].contactId.length() > 3){
                if(wrapper.GDPRList[i].contactId.subString(0,3) == '003'){
                    Contact toInsert = new Contact();
                    toInsert.firstName = wrapper.GDPRList[i].firstName;
                    toInsert.lastName = wrapper.GDPRList[i].lastName;
                    toInsert.email = wrapper.GDPRList[i].email;
                    toInsert.Email_Hash__c = wrapper.GDPRList[i].emailHash;
                    toInsert.Id = wrapper.GDPRList[i].contactId;
                    toInsert.Sales_and_Marketing__c = wrapper.GDPRList[i].marketing;
                    toInsert.Critical_Security_Notes__c = wrapper.GDPRList[i].security;
                    toInsert.Product_Information__c = wrapper.GDPRList[i].support;
                    toInsert.Contact_Via_Text__c = wrapper.GDPRList[i].contactPhone;
                    toInsert.Contact_Via_Email__c = wrapper.GDPRList[i].contactEmail;
                    contactPref.add(toInsert);
           
                }
            }
        else{
             Contact toInsert = new Contact();
             toInsert.firstName = wrapper.GDPRList[i].firstName;
             toInsert.lastName = wrapper.GDPRList[i].lastName;
             toInsert.email = wrapper.GDPRList[i].email;
             toInsert.Email_Hash__c = wrapper.GDPRList[i].emailHash;
             
             toInsert.Sales_and_Marketing__c = wrapper.GDPRList[i].marketing;
             toInsert.Critical_Security_Notes__c = wrapper.GDPRList[i].security;
             toInsert.Product_Information__c = wrapper.GDPRList[i].support;
             toInsert.Contact_Via_Text__c = wrapper.GDPRList[i].contactPhone;
             toInsert.Contact_Via_Email__c = wrapper.GDPRList[i].contactEmail;
             newContacts.add(toInsert);
        
        
        }
           
            
          
        
        }
          try{
              if(contactPref.size()>0){
                  upsert contactPref;
              }
              if(NewContacts.size()>0){
                  insert NewContacts;
              }          
            } 
            catch(DmlException e){
                    System.debug('An unexpected error has occured: ' + e.getMessage());
                }
      
      }
     }

Test Class:
 
@isTest
private class desearializeTest{

    @isTest static void testWebCalloutWithStaticResource(){
    
        StaticResourceCalloutMock mock = new StaticResourceCalloutMock();
        mock.setStaticResource('GDPR');
        mock.setStatusCode(200);
        mock.setHeader('Content-Type', 'application/json');
    
        Test.setMock(HttpCalloutMock.class, mock);
        JSONDeserialize.deserialize();
    
    }


}

When I run the basic validation now I get four errors, all of them the same 
 
Methods defined as TestMethod do not support Web service callouts 
Stack Trace: null


 
  • I have 2 objects: Contact and Rlayer__c
  • Each contact can have 1 or more records on Rlayer__c
  • I would like to create a counter field on Rlayer (now, and then when a record is created on Rlayer.
  • So the first record related to the contact on Rlayer WHERE sportsclub__c = 'Windsor' = should have a field count__c = 1
  • The 2nd record on Rlayer  related to the contact on Rlayer WHERE sportsclub__c = 'Windsor' = should have a field count__c = 2
  • The 3rd record on Rlayer  related to the contact on Rlayer WHERE sportsclub__c = 'Windsor' = should have a field count__c = 3
How can I achieve this?

Ideally with DML code and 'update' command. I have an idea of DML but do not know who to select records from 2 objects related to each other.

Thanks, Dave


 
I have a trigger on Opp, after each insert/update I need to recalculate a user's sales for the month. I have the user set and I can do an aggregate query, but how do I connect these in the map?
Here is what I have so far, any help would be appreciated!
//get total current count of opps
    oppList = [SELECT Id,Amount FROM Opportunity 
                WHERE CloseDate = THIS_MONTH 
                AND StageName = 'Closed–Won'];
    //add opps to set to get comm splits
    for(Opportunity o:oppList){
        oppSet.add(o.Id);
    }
    //get aggregate of all commission splits
    csAgg = [SELECT SUM(Split_Amount__c),User__c 
            FROM Commission_Split__c 
            WHERE Opportunity__c IN :oppSet];
    //get comm splits attached to this opp
    csList = [SELECT Id,Split_Amount__c,User__c,Opportunity__c 
                FROM Commission_Split__c 
                WHERE Opportunity__c IN :oppSet];
    //get users
    for(Commission_Split__c c:csList){
        userSet.add(c.User__r.Id);
    }
    //now I have my users in a Set, and aggregate results above, how do I connect?
    public Map<Id, AggregateResult> userSales = 
        new Map<Id,AggregateResult>([SELECT SUM(Split_Amount__c) 
                                    FROM Commission_Split__c 
                                    WHERE User__c IN :userSet)]);

 
Hello everyone,
I have created a trigger which will update Contact Object field(Most_recent_Opportunity_Stage__c) whenever opportunity status gets changed.
My trigger is working fine but associated Test class is not making 75% code coverage of Trigger. I am new to salesforce and not having much experince to build test class so please help me.

Here is my Trigger and associated test class :

Trigger :

trigger UpdateMostRecentOpportunityStageOfContact on Opportunity (after update) {
  Set<String> ContactIds = new Set<String>();
     Set<String> oppIds = new Set<String>();
     if(UpdateStageOnContactHandler.isFirstTime){
             UpdateStageOnContactHandler.isFirstTime=false;
    List<OpportunityContactRole> conList = new List<OpportunityContactRole>([select ContactId from OpportunityContactRole where IsPrimary = true and OpportunityId IN :Trigger.newMap.keySet() limit 1]);
     for(OpportunityContactRole c :conList)
       {
           ContactIds.add(c.ContactId);
       }    
    List<OpportunityContactRole> oppList =  new List<OpportunityContactRole>([select ContactId,opportunityId,CreatedDate from OpportunityContactRole where IsPrimary = true and ContactId =: ContactIds order by CreatedDate desc  limit 1]);
    for(OpportunityContactRole cr :oppList)
       {
           oppIds.add(cr.opportunityId);
       } 
    if(!oppIds.isEmpty()){
    Opportunity op = [select StageName from opportunity where Id =:oppIds limit 1]; 
    List<Contact> contactToUpdate = new List<Contact>();
    for(Opportunity opp : trigger.new){
           for(OpportunityContactRole c :oppList){ 
                if(opp.AccountId != null){
                 contactToUpdate.add(new Contact(Id = c.ContactId, Most_recent_Opportunity_Stage__c=op.StageName)); 
               }
           }    
       }
       if (contactToUpdate != null && !contactToUpdate.isEmpty())
        {
            Update contactToUpdate;
        } 
     }
   }      
 }


TEST Class :

@isTest
public class TestUpdateMostRecentopportunityStage {
   static testMethod void TestUpdateStageOnContactTest()
    {   
        Account a = new Account(Name = 'TestUpdateStageOnContactTest');
        a.Type = 'Prospect';
        insert a;

        Contact newContact1 = new Contact(Lastname='TestUpdateStageOnContactTest1', AccountId = a.Id ,Email='mayanks+test1@webgility.com' );
        insert newContact1;
        
        Contact newContact2 = new Contact(Lastname='TestUpdateStageOnContactTest2', AccountId = a.Id ,Email='mayanks+test2@webgility.com' );
        insert newContact2;
    
      
        Opportunity o1 = new Opportunity(AccountId=a.Id, name='OPP test1', StageName='Demo', CloseDate = Date.today() );
       insert o1;
        OpportunityContactRole ocr1 = new OpportunityContactRole(OpportunityId = o1.Id, ContactId = newContact1.Id, Role='Decision Maker',Isprimary=true );
        insert ocr1;
        
          Opportunity o2 = new Opportunity(AccountId=a.Id, name='OPP test2', StageName='Open', CloseDate = Date.today() );
       insert o2;
        OpportunityContactRole ocr2 = new OpportunityContactRole(OpportunityId = o2.Id, ContactId = newContact2.Id, Role='Decision Maker',Isprimary=true );
        insert ocr2;
        
          Test.StartTest();
        o1.stageName='Demo';
        update o1;
        newContact1.Most_recent_Opportunity_Stage__c='Demo';
        update newContact1;
        
         o2.stageName='Open';
        update o2;
        newContact2.Most_recent_Opportunity_Stage__c='Open';
        update newContact2;
        
        Test.StopTest();
         
      }   
}


Thanks,
Mayank
Hi Team,

Trigger not fetching the values all, i am inserting new records through data import wizard, i am not getting any error but after insert some records are updating and some records are not update, Example today inserted 500 records though data import wizard now its inserting 500 records but out of 500, 200 records its updating the EHR_TS__c value and remaining 300 not updating, and after i exported 300 records and update only ID, at that time 300 records its updating.

Please Help me where i am mistake in code its very urgent, below is my code Trigger & Class ,Thanks Advanced.

************************************ TRIGGER  ***********************************************************

Trigger UpdateEHRate on Time_Sheet__c (before insert,before update,after update, after insert)
{        
    if((Trigger.isInsert && Trigger.isAfter) || (Trigger.isUpdate && Trigger.isAfter)){   
        if(checkRecursive.isFirstRun()){

            List<Time_Sheet__c> timeList = EHRTriggerHandler.UpdateEHRate(trigger.New);
            if(timeList.size() > 0){
                update timeList;
            }
        }
    }
}

**************************************** APEX CLASS ****************************************************

public class EHRTriggerHandler{
    
    public static List<Time_Sheet__c> UpdateEHRate(List<Time_Sheet__c> lstTS){ 
       List<Time_Sheet__c> timeList = new List<Time_Sheet__c>();
        System.debug('@@@@@@@1'+timeList);
       set<Id> TSIds = new set<Id>();
       Map<Id ,boolean> mapTimeSheet = new Map<Id,boolean>();
        for(Time_Sheet__c EHR : lstTS) {    
            TSIds.add(EHR.Employee__c);
        }                       
        
        List<Estimated_Hourly_Rate__c> EHRlist = [SELECT Id, Name,Employee__c,Start_Date__c,End_Date__c,Estimated_Hourly_Rate_Variable__c 
                                              FROM Estimated_Hourly_Rate__c 
                                              WHERE Employee__c =:TSIds];  
        
        Map<id,List<Estimated_Hourly_Rate__c>> mapEs = new Map<id,List<Estimated_Hourly_Rate__c>>();
        
        for (Estimated_Hourly_Rate__c c : EHRlist) {
                List<Estimated_Hourly_Rate__c> l = mapEs.get(c.Employee__c);
                if (l == null) {
                    l = new List<Estimated_Hourly_Rate__c>();
                    mapEs.put(c.Employee__c, l);
                }
            l.add(c);
        }
        
        boolean isMatchFound = false;        
        //if(EHRlist!=null && !EHRlist.isEmpty()) {
         for(Time_Sheet__c timeSheetRec :lstTS){
             Time_Sheet__c timee = new Time_Sheet__c();  
             
             List<Estimated_Hourly_Rate__c> listes = mapEs.get(timeSheetRec.Employee__c);
            for(Estimated_Hourly_Rate__c EHR : listes) {   
                     if(timeSheetRec.Record_Date__c >= EHR.Start_Date__c && timeSheetRec.Record_Date__c <= EHR.End_Date__c ){                    
                        timee.id = timeSheetRec.id;
                        timee.EHR_TS__c = EHR.Estimated_Hourly_Rate_Variable__c; 
                        //timeSheetRec.EHR_TS__c = EHR.Estimated_Hourly_Rate_Variable__c;  
                        isMatchFound = true;
                        
                    } 
                }
                
                 timeList.add(timee);              
            }  
          //}             
           
        if(!isMatchFound){
            lstTS[0].addError('The given Record date does not fall under any of the Estimated Hourly Rates record(s)');
        }
        
        return timeList;
  }  
}

it keeps return not writeable error... how should i resolve this error?
 
private List<Contact> contactList;

   public void addMore() {
    

        string nameT = Apexpages.currentPage().getParameters().get('nameT');
        string phoneT = Apexpages.currentPage().getParameters().get('phoneT');
        string emailT = Apexpages.currentPage().getParameters().get('emailT');

    system.debug(nameT + '//' + phoneT + '//' + emailT);


    Contact att = new Contact();

    att.name = nameT;
    att.phone = phoneT;
    att.email = emailT;

    contactList.add(att);


 //i want this parameters to List value but it doesnt work properly..
  • May 24, 2018
  • Like
  • 0
Hi All,

Before executing Batch apex how am i getting the Jobid of batch apex in finish method as shown below.

Please explain as i am a new to salesforce.

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()]; ( how do i get job id in finish method before executing batch apex )
// Send an email to the Apex job's submitter notifying of job completion.

Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage(); String[] toAddresses = new String[] {a.CreatedBy.Email}; mail.setToAddresses(toAddresses); mail.setSubject('Apex Sharing Recalculation ' + a.Status); mail.setPlainTextBody ('The batch Apex job processed ' + a.TotalJobItems + ' batches with '+ a.NumberOfErrors + ' failures.'); Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail }); }

 
Vf 

<apex:page Controller="Task39PhoneValidation">
  <apex:sectionHeader title="Student" subtitle="Home"/>
  <apex:pagemessages />
  <apex:form >
    <apex:pageblock tabstyle="Student__c">
      <apex:pageblockbuttons >
        <apex:commandButton value="Save" action="{!submit}"/>
        <apex:commandButton value="Save&New" action="{!saveandnew}"/>
        <apex:commandButton value="Cancel" action="{!cmeback}"/>
      </apex:pageblockbuttons>
      <apex:pageBlockSection >
        
      <apex:pageBlockSection title="Student Details" >
        <apex:inputField value="{!st.Name}"/>
        <apex:inputField value="{!st.Last_Name__c}"/>
        <apex:inputField value="{!st.Dob__c}"/>
      </apex:pageBlockSection>
      <apex:PageBlockSection title="Additional Details">
        <apex:inputField value="{!st.Tenure__c}"/>
        <apex:inputField value="{!st.Course__c}"/>
        <apex:inputField value="{!st.Doctor__c}"/>
      </apex:PageBlockSection>
      <apex:pageBlockSection title="Contact Details">
        <apex:inputField value="{!st.Address__c}"/>
        <apex:inputField value="{!st.Permanent_Address__c}"/>
        <apex:inputField value="{!st.Mobile__c}"/>
      </apex:pageBlockSection>
      </apex:pageBlockSection>
    </apex:pageblock>
  </apex:form>
</apex:page>




Controller:

public with sharing class Task39PhoneValidation {
    
    Public Integer phn;
    
    public Task39PhoneValidation(){
        st = new Student__c();
        
    }

    public PageReference cmeback() {
        return null;
    }


    public PageReference saveandnew() {
        return null;
    }


    public PageReference submit() {
        phn = st.mobile__c.length();
        if(phn == 10 ){
            insert st;
        }
        else{
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING,'Your Phone number should have Only 10 digits not more than that or lesser then that .'));
        }
        
        return null;
    }


    public Student__c st { get; set; }
}
trigger CloneOpp on Opportunity( after insert, after update ) {
  Set<String> fields = Opportunity.getSobjectType().getDescribe().fields.getMap().keySet();

  Map<Id,opportunity_clone__c> co2 = new Map<Id,Opportunity_clone__c>();
  for(Opportunity record: Trigger.new) {
    co2.put(record.opportunity_clone__c,new opportunity_clone__c(id=record.opportunity_clone__c));
    for(String field:fields) {
      if(field.indexOf('__c')>-1) { // This is a custom field.
        try {
          Opportunity_clone__c.get(record.opportunity_clone__c).put(field,record.getSObject(field));
        } catch(exception e) { /* NOTE: This just means copy failed. */ }
      }
    }
  }
  update co2.values();
}

 
We are looking for a part time Salesforce developer to participate in several adhoc projects. The ideal candidate will have the following attributes and qualifications:
  • Superior written and verbal communciation skills
  • Through knowledge of the salesforce platform
  • Experience writing Visualforce pages and developing Apex code
  • Familiar with process builder and visual flows
  • Well versed in the transition from classic experience to lightning
  • U.S. citizen