• Maharajan C
  • ALL STAR
  • 7020 Points
  • Member since 2015
  • Sr.Associate Consultant
  • Infosys


  • Chatter
    Feed
  • 236
    Best Answers
  • 1
    Likes Received
  • 1
    Likes Given
  • 13
    Questions
  • 883
    Replies
Hello,

I'm trying to test the trigger below, however my test is not passing in the IF condition.

Trigger
trigger ValidateLead on Lead (before insert, before update){

	if (Trigger.isBefore) {
    	for(Lead led : trigger.new){

    		Lead leds = [SELECT Id, Name FROM Lead WHERE id=: led.Id];
    		
    			if(ValidaDocumento.isCNPJ(led.CNPJ__c))
    				led.CNPJ__c = ValidaDocumento.imprimeCNPJ(led.CNPJ__c);
    			else
    				led.addError('O CNPJ informado é Inválido');
	    }
    }
}

test class:
public static testMethod void createLead() {
	    
	    Lead prospect = new Lead(
	        
			LastName = 'TestProspect',
			CNPJ__c = 'teste',
			Company = 'TestCompany',
			Estado__c = 'SP'
		);
		ValidaDocumento.isCNPJ(prospect.CNPJ__c);
		ValidaDocumento.imprimeCNPJ(prospect.CNPJ__c);
		insert prospect;
		
		Lead prospect2 = new Lead(
	        
			LastName = 'TestProspect',
			CNPJ__c = '68119173000167',
			Company = 'TestCompany',
			Estado__c = 'SP'
		);
		ValidaDocumento.isCNPJ(prospect2.CNPJ__c);
		insert prospect2;
		
		Lead prospect3 = new Lead(
	        
			LastName = 'TestProspect',
			CNPJ__c = '00000000000000',
			Company = 'TestCompany',
			Estado__c = 'SP'
		);
		insert prospect3;
		ValidaDocumento.isCNPJ(prospect3.CNPJ__c);
		
		Lead prospect4 = new Lead(
	        
			LastName = 'TestProspect',
			CNPJ__c = '11111111111111',
			Company = 'TestCompany',
			Estado__c = 'SP'
		);
		insert prospect4;
		ValidaDocumento.isCNPJ(prospect4.CNPJ__c);
		
		Lead prospect5 = new Lead(
	        
			LastName = 'TestProspect',
			CNPJ__c = '681191730001',
			Company = 'TestCompany',
			Estado__c = 'SP'
		);
		insert prospect5;
	    ValidaDocumento.isCNPJ(prospect5.CNPJ__c);
	}
}
I'm in doubt how to make the test pass through my if conditional.
 
Can anyone let me know if im doing this correctly?

Need a validation rule that prevents a Sales user from updating a picklist to a Certain Value on a Certain Record Type.

For this excample, i want to prevent Sales User from updating picklist to Value1 (and allow all other values for them) for that record type

(AND( $User.ProfileId <> "Sales User",,$RecordType.Name = "Record Type Name",
ISCHANGED(Status__c),
NOT(ISPICKVAL(Status__c, 'Value2')),
NOT(ISPICKVAL(Status__c, 'Value3')),
NOT(ISPICKVAL(Status__c, 'Value4')),
)
)
Hello, 

I have a validation rule where the Picklist value = Yes, the text area field Assets Items should not be blank. The below VR is prompting that "Data Missing" Asset items are missing! when I complete the Assets Items field. 
Any idea how to modify the VR? 
Thank you!
 
AND(
    ISPICKVAL( Assets__c , 'Yes'),
    ISBLANK( Asset_Items__c )
)


 
  • September 16, 2019
  • Like
  • 0
Hey there,

I'm new to APEX and curious about converting Apex Triggers to Apex Classes in order to be in line with the One-Trigger-per-Object pattern. 

Let's say I have the following, very simple Trigger: Whenever an Account gets updated, the number of related contacts gets populated in the custom field Number_of_Contacts__c. The Trigger code looks like this:
 
trigger relatedContacts on Account (before update) {  
   
   List<Contact> relatedContacts = [SELECT Id
                                    FROM   Contact
                                    WHERE  AccountId IN :Trigger.new];
        
   for (Account a : Trigger.new) {
        a.Number_of_Contacts__c = relatedContacts.size();
    }            
    
}
First question: How would the Apex Class for this Trigger look like?

Second question: How shall I reference the Apex Class in the Master Trigger for the Account object? At least I already know where to put it:
trigger MasterOpportunityTrigger on Opportunity (
  before insert, after insert, 
  before update, after update, 
  before delete, after delete) {

  if (Trigger.isBefore) {
    if (Trigger.isInsert) {

    } 
    if (Trigger.isUpdate) {
      // MY TRIGGER WILL GO HERE ;)
    }
    if (Trigger.isDelete) {

    }
  }

  if (Trigger.isAfter) {
    if (Trigger.isInsert) {

    } 
    if (Trigger.isUpdate) {

    }
    if (Trigger.isDelete) {

    }
  }
}

I would highly appreciate if someone could teach me this best practice!

Best, 
David
  • September 11, 2019
  • Like
  • 0
I am trying to create a formula that compares a date field Like Acme_Date__c = TODAY() then display "TODAY" for atext value. 

I'm not sure how to accomplish this result without getting errors 
how to write 100% test class for Calculator CLass. Unit Testing on the Lightning Platform  Write Negative Tests
Hello All,
I have a Batch Class where I am updating all of the Contact Owners to Match the Account owners.
I am unable to cober the condition in Class.
Here are the Classes.
@isTest

private class TestBatchContactownerUpdate 
{
    static List<Account> aList;
    static testMethod void myUnitTest() 
   
    {
        UpdateContactOwnerToAccountOwnerBatch bat = new UpdateContactOwnerToAccountOwnerBatch();
     
        bat.finish(null);
    }
    static testMethod void testSchedulable()
    {
        Test.startTest();        
        String cron = '0 0 0 17 11 ? 2033';
        System.schedule('BATR99zz', cron, new UpdateContactOwnerToAccountOwnerBatch());
        Test.stopTest();
    }
  
    {
     Account acc = new Account(
            Name = 'testaccount'
            ,BillingPostalCode='22821'      
            ,RecordTypeId = '222222' 
        );
        insert acc; 

      
        Account sacc= [SELECT Id, Name,OwnerID from Account Where name = 'testAccount' limit 1];
       
        Contact con = new Contact(
            AccountId = sacc.id
            ,Lastname = 'testcontact'
            ,Firstname ='testdude'
            ,RecordTypeId = '1111111'
        );
        insert con;


       
        Test.startTest();
        Profile p = [SELECT Id FROM Profile WHERE Name='Standard User']; 
            User u1= new User(Alias = 'standt', Email='testemail@junkmail.com', 
                        EmailEncodingKey='UTF-8', LastName='Tester', LanguageLocaleKey='en_US', 
                        LocaleSidKey='en_US', ProfileId = p.Id, 
                        TimeZoneSidKey='America/Los_Angeles', UserName='testemail@junkmail.com');
            
            System.runAs(u1) {
      // The following code runs as user 'u'  
       // create test contact
        Contact c1 = new Contact(FirstName='Jane',LastName='Doe', Account=acc);
        insert c1;
        
        //assert your results using system.assert and system.asserEquals

        //reload objects to make sure values are loaded
        c1 = [select id, name,  OwnerId from contact where id=:con.id];
        con = [select id, name, OwnerId from contact where id=:con.id];

        acc= [select id, ownerId from Account where id=:acc.id];
       // system.assert(c1.OwnerID = acc.OwnerID);
            
            
            
        Test.stopTest();
        }
    }
}
global class UpdateContactOwnerToAccountOwnerBatch implements Database.Batchable<sObject>, Schedulable{

        
    List<contact> contactsToChangeOwner = new List<contact>();
    global final String Query ='SELECT Id, AccountId, Ownerid, Account.ownerid from contact where AccountId != null';
       global Database.QueryLocator start(Database.BatchableContext BC){
          return Database.getQueryLocator(query);
       }
       
       global void execute(Database.BatchableContext BC, List<contact> scope){
        
        for(contact con: scope){     ----  No Coverage
            if(con.ownerid!=con.Account.ownerid){    ----  No Coverage
                con.ownerid = con.Account.ownerid;     ----  No Coverage
                contactsToChangeOwner.add(con);    ----  No Coverage
            }           
        }
        update contactsToChangeOwner;      ----  No Coverage
       }
       
    global void finish(Database.BatchableContext BC){}
    
    global void execute(SchedulableContext sc)
    {
      Database.executeBatch(new UpdateContactOwnerToAccountOwnerBatch ());
    } 
    
    
    
}

If someone would review my Test Class it would be greatly appreciated.
Cheers,
M
 
VisualForce Page Code:

<apex:page standardController="Contact" extensions="contactExtension" standardStylesheets="true" sidebar="false">
<apex:sectionHeader title="Insert Realted Contact Deatil in Account" subtitle="{!Contact.Name}" help="/help/doc/user_ed.jsp?loc=help" /> 

<script>
function myFunction() {
  var txt;
  if (confirm("Press a button!")) {
    txt = "You pressed OK!";
  } else {
    txt = "You pressed Cancel!";
  }
  document.getElementById("demo").innerHTML = txt;
}
</script>

<apex:form >

<apex:pageBlock title="Select Account for Inserting Realted Contact Record" mode="edit">

<apex:pageBlockButtons >
<apex:commandButton action="{!save}" onclick="myFunction()" value="Save"/> 
<apex:commandButton action="{!cancel}" value="Cancel"/> 
</apex:pageBlockButtons>

<apex:pageBlockSection title="Account Detail" columns="1" >

<apex:pageBlockSectionItem >
<apex:outputLabel value="Account Name" for="accts" />  <!-- for - The ID of the component with which the label should be associated.  -->
<apex:selectList id="accts" value="{!Contact.AccountId}" size="1" title="Account">
<apex:selectOptions value="{!accts}" />
</apex:selectList>
</apex:pageBlockSectionItem>

</apex:pageBlockSection>

<apex:pageBlockSection title="Contact Deatil" columns="2">
<apex:inputField value="{!Contact.FirstName}" />
<apex:inputField value="{!Contact.LastName}" />
<apex:inputField value="{!Contact.Department}" />
<apex:inputField value="{!Contact.Phone}" />
<apex:inputField value="{!Contact.Email}" />
<apex:inputField value="{!Contact.Birthdate}" />
</apex:pageBlockSection>

</apex:pageBlock>

</apex:form>
</apex:page>


Controller Code:

public class contactExtension {

//Use a StandardController when defining an extension for a standard controller.

private final Contact c; 

// The extension constructor initializes the private member
// variable c by using the getRecord method from the standard
// controller.

public contactExtension(ApexPages.StandardController stdController) {
this.c = (Contact)stdController.getRecord();
}


public List<selectOption> getaccts() {
List<selectOption> options = new List<selectOption>(); 

options.add(new selectOption('', '- None -')); 

for (Account account : [SELECT Id, Name FROM Account]) { 

options.add(new selectOption(account.id, account.Name)); 

}
return options; 
}
}
Hello,
I have a trigger that is not not reaching the 75% threshold.
I have 2 lines of code where I am calling another Class.  Any help would be greatly appreciated.
trigger warrantyValueCalculation on Warranties_and_Surveys__c (before insert, before update) {
    for (Warranties_and_Surveys__c warRec: trigger.new)
    {
         if((trigger.isInsert) && (warRec.Warranty_Survey_Account__c=='123' || warRec.Warranty_Survey_Account__c=='456' || warRec.Warranty_Survey_Account__c=='789' || warRec.Warranty_Survey_Account__c=='136' || warRec.Warranty_Survey_Account__c=='764' || warRec.Warranty_Survey_Account__c=='111')&&(warRec.Project_Country__c=='US')){
         warrantyAmountCalculation.beforeInsert(trigger.new); ---no coverage
        }
        //if((trigger.isUpdate) && ((trigger.oldMap.get(warRec.Id).Registration_Status__c == 'Registered') && (warRec.Registration_Status__c == 'Registered'))){
         if((trigger.isUpdate) && (warRec.Warranty_Survey_Account__c=='001f100001M2FVP' || warRec.Warranty_Survey_Account__c=='876' || warRec.Warranty_Survey_Account__c=='590' || warRec.Warranty_Survey_Account__c=='327' || warRec.Warranty_Survey_Account__c=='970' || warRec.Warranty_Survey_Account__c=='327')&&(warRec.Project_Country__c=='US')){
         warrantyAmountCalculation.beforeInsert(trigger.new); ---no coverage
        }
    }

}

 
Hi all, 
            I am trying to invoke Lead assignment rule when ever certain criteria meets the trigger should fire.
        But I am getting the following error :  execution of AfterInsert caused by: System.DmlException: Update failed. First exception on row 0; first error: MISSING_ARGUMENT, Id not specified in an update call: []: 
        Can anyone guide me where I am donig wrong.Thanks in advance.
My Trigger:
trigger LeadAssignment on Lead (After insert,After update) {
    
    List<Lead> updateLeads = new List<Lead>();
    
    Lead newLead = new Lead();
    for(Lead l : trigger.new)
    {
        if(l.Status == '01-New' || l.Status == '50-Qualified')
        {
            AssignmentRule AR = new AssignmentRule();
            AR = [select id from AssignmentRule where SobjectType = 'Lead' and Active = true limit 1];
            
            Database.DMLOptions dmlOpts = new Database.DMLOptions();
            dmlOpts.assignmentRuleHeader.assignmentRuleId= AR.id;
            system.debug('dmlOpts***********'+dmlOpts);
             
             newLead.setOptions(dmlOpts);
           // updateLeads.add(newLead);
             
                    }
      
    }
    update newLead;
    system.debug('updateLeads************'+newLead);

}
  • September 04, 2019
  • Like
  • 0
 Hi friends
My requirement is place a component in opportunity detail page (get the record details by using  {!v.recordId}) when change and save the Stage(StageName) picklist values in details page  then my component is need to refresh
Here I don’t want to use any button ,link
So I just used  aura:handler    in this action function I used
$A.get('e.force:refreshView').fire();     but is not working 
location.reload();        it is working but problem is entire page will reload number of times i.e it is reload the page continuously it does not stop

    <lightning:input label="current record id" aura:id="recid" value="{!v.recordId}" />
    <aura:handler name="init" value="{!this}" action="{!c.show}" />

({
 
    show : function(component, event, helper)
    {
        var recid=component.find("recid").get("v.value");
        //alert(recid);
        var ledmethod=component.get("c.opprecordidmethod");
        ledmethod.setParams({
            idd:recid,
        }); 
        ledmethod.setCallback(this, function(res){
            if (res.getState() === "SUCCESS")
            {
                var resultval = res.getReturnValue();
                component.set("v.stagename",resultval);
                if(resultval == "Prospecting"){
                    component.set("v.Prospectingcurrent", "resultval");
                    
                }
                if(resultval == "Qualification"){
                    component.set("v.Qualificationcurrent", "resultval");
                    
                    component.set("v.Prospectingcomplete", "resultval");
                }
                 $A.get('e.force:refreshView').fire();     
                //location.reload();
            }
        });
        $A.enqueueAction(ledmethod);  
    }
})

Please help me friends

Thanks in advance

 

I am a beginner developer so I'm sorry if the solution is obvious but I cannot get the Account details that I have added to the outputFields to show under the column that I have created. 

I have created a button on the account object. When clicked, a pop up window opens the visualforce page that I am creating. I believe the issue is that the VF page is not pulling the Account ID since it is opening a new page. So essentially I open an account record, click the button and the table shows up blank. What do I need to do?

Button OnClick JavaScript:

var win = window.open('/apex/ecard?oppId={!Account.Id}&retURL=/apex/ForceWindowClose', 'Popup Name' ,"width=1200, height=2100, scrollbars=yes");
var timer = setInterval(function() {
    if(win.closed) {
        clearInterval(timer);
        window.location.reload();
    }
}, 500);


VF Page:

<apex:page id="pg" standardController="Account" sidebar="false">
<apex:form>
    <apex:pageBlock title="Account">
        <apex:pageBlockTable value="{!Account}" var="a" columns="1">
            <apex:column headerValue="Customer Details">
                <apex:outputField value="{!a.Name}" />
                <apex:outputField value="{!a.Phone}" />
            </apex:column>
        </apex:pageBlockTable>
    </apex:pageBlock>
</apex:form>

</apex:page>
Reposted - Date/Time field Formula help
 
I have an existing date/time field
 
RegistrationDate_c = example value 31/12/2019 14:34
 
I would like to create a new date/time formula field based on the date from RegistrationDate__c, so need a formula here.
 
New field is ProcessDate__c
 
ProcessDate__c = the date from RegistrationDate__c and time must be always 23:59
 
So if RegistrationDate__c = 01/12/2019 15:45 then ProcessDate should be 01/12/2019 23:59
 
Can anyone help? I have searched documentation online but cannot find the syntax for the formula.
 
Yes, you guessed this field will be used to trigger a process.
 
Regards Dave
Hi all,

Please find below a sample of a batch apex code I am trying to update :;

global class BatchDeleteEmailAttachV2 implements Database.Batchable<sObject> {
    
  global Database.QueryLocator start(Database.BatchableContext BC){
        
        String query = 'SELECT Id FROM Attachment where Parent.Type = \'EmailMessage\' AND CreatedDate > 2016-01-01T00:00:00.000+0000 AND CreatedDate < 2017-01-01T00:00:00.000+0000';
       return Database.getQueryLocator(query);
     }
    
global void execute(Database.BatchableContext BC,List<sObject> attachments){
    Database.delete(attachments);
     }

This is working correctly, however I would like to use custome labels, so the date range can easily be updated. Here is what I have tried but the 

global class BatchDeleteEmailAttachV2 implements Database.Batchable<sObject> {
    
  global Database.QueryLocator start(Database.BatchableContext BC){
        
        String query = 'SELECT Id FROM Attachment where Parent.Type = \'EmailMessage\' AND CreatedDate > Label.BatchDeleteEmailAttach_FROM AND CreatedDate < Label.BatchDeleteEmailAttach_TO';
       return Database.getQueryLocator(query);
     }
    
global void execute(Database.BatchableContext BC,List<sObject> attachments){
    Database.delete(attachments);
     }

This is working with the value (2016-01-01T00:00:00.000+0000) but not with the custom label (Label.BatchDeleteEmailAttach_FROM).

Can anyone help please?

Thanks,

Nordine.
I wrote a trigger to count number of open cases for contacts. 
To reduce complexity and obey governor limits, how can I use Map instead of inner for loop in this case? 
 
trigger CountOpenCases on case (after insert, after update) {
  List<Case> caseList = trigger.new;
  set<Id> contactIdSet = new set<Id>();
  for(Case cs: caseList ){
     contactIdSet .add(cs.contactId);
  }
  if(contactIdSet.size() > 0){
    List<contact> lstcontact = [select id, (select id, status from Cases)from contact where id IN: contactIdSet ];
       if(lstcontact.size() > 0){
          for(contact acc: lstcontact)
          { 
             Integer openCases = 0;
             for(Case c : acc.cases){
                 if(c.Status != 'Closed')
                   openCases++;
             }
             acc.Open_Cases__c = openCases; 
          }
          update lstcontact;
       }
  }
}

 
Hi, i want to print follwing lines in lightning component.

""please email us on email vikuemail.com or call us on 234 567 890""

1. i want email to show in highlighted in email format, so that when i click on email, it should be direct email. and also phone number highlighted in different color.
2. i want to use this in custom settings, so that based on requirement this statement can be changed.

i wrote a list of String returning both these values in apex, which will be returned to JS and then will be used by component.

but confused, how to implemnt this.
Can anyone please help.
Hi everyone, 
I am trying to write a Trigger (before insert, before update) that will create  a composite key on a Purchases__c custom object. The data is coming in, but has no unique ID. Purchases__c has custom fields like Event_name, section_Name, row_name etc, that I need to concatenate into a custom field Key__c which is an external ID. I am fairly new to triggers and was hoping for some guidance on how to start going about it. I am pretty sure I am way off and probably overthinking this. Any sort of suggestion would help. Here is what I have so far:

trigger Composite_Key on Purchases__c (before insert, before update) {
    //need to assign Key__c field with concatenated values
            //Event_name
            //section_Name
            //row_name
            //seat_num
            //num_seats
            //add_datetime
    if(Trigger.isBefore)
    {
        if(Trigger.isInsert)
        {
           Key__c key = new Key__c();
           key.Event_name = Trigger.new[0].name;
        }
        else if(Trigger.isUpdate)
        {
           //code here
        }
    }
}
<apex:page >
  
  <apex:form >
  
  <html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
 $(document).ready(function() {

    $("#name").focusout(function() {
       
         var value =$('#name').val();
         
          if(value==""){
          
                   $('#name_Error').html(" name is Required!");

          }else{
           $('#name_Error').empty();
          
          return true;
          }
    });

});
</script>
</head>
<body>


 <input type="text"  id="name"/><span id="name_Error" class="Errormessage"></span>
 
 <br/>
<apex:inputText styleClass="form-control" html-placeholder="Name"  id="name" /><span id="name_Error" class="Errormessage"></span>

</body>
</html>
</apex:form>
</apex:page>

Hi , here iam using the html input  , the jquery is working , when iam using the apex:input text, the value is not working ?? may i get any solution ?
Hi Friends

I am facing a issue with how can to get  one components attribute value to another component

 
 I have Two components 1) FormComponent and 2) PrintComponent
 
 I need FormComponent's OppId attribute in PrintForm's Java script controller.
 
 How can i get the attribute?
 
 Below is the code skeleton
 
 FormComponent.cmp
 ----------------
 
 <aura:component controller="FormController">
 <aura:attribute name="oppId" type="String" default=""/> 
    <lightning:layout>
 
 <lightning:layoutItem padding="horizontal-small" largeDeviceSize="3" mediumDeviceSize="3" smallDeviceSize="12" size="12">
                    <lightning:button variant="brand" label="Print Forms" title="Print Loan Agreement" onclick="{!c.printForms}" />
                     
                   </lightning:layoutItem>
                   
                   </lightning:layout>
  
    
</aura:component>



FormComponentcontroller.js
------------------------------


({
    doInit: function(component, event, helper){
},

 printForms : function(component, event, helper){
 
 // need to send oppId to another component PrintForm
 
 }
})



PrintForm.cmp
-------------

<aura:component implements="force:appHostable,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction"
                access="global"
                controller="PrintController">
    
     <aura:attribute name="oppId" type="String" default=""/>
     
     <!--  logic to implement the datatable to view the data -->
     
</aura:component>


PrintFormController.js
-----------------------


{
    doInit: function(component, event, helper){
// how can i get the oppId value from Form component
},

 
We have the managed package which is created by us so we are try to install this package  some other org.

It works fine in all orgs but in one org we have the error message like below:

 (UpdateAcc-2) myrule_1_A1(Action Call) – We can’t find an action with the name and action type that you specified

The UpdateAcc is the Process builder which call the Apex Class.

In the package also we have these components but we got the Error!!!

Any one please help on this!!!

Thanks,
Raj
Hi Experts,

Hope some one wil help me:

Salesforce going to update the certificates. Please refer the below Link.

https://help.salesforce.com/articleView?id=000269027&language=en_US&type=1

So Here i have to do the test compatibility  in my environment for MiddleWare and Integration:

Can any one please let me know how to perform the below steps: 

For Middleware/Integrations
To test the compatibility of an API client that uses SOAP to communicate with Salesforce:
  • Set up an API client in a test environment.
  • In that test environment, change the API client's login endpoint hostname fromlogin.salesforce.com or [MyDomain].my.salesforce.com tohttps://certtest.force.com.
  • As an example, changehttps://login.salesforce.com/services/Soap/u/32.0 to https://certtest.force.com/services/Soap/u/32.0 while leaving the path as-is.
  • Log in with that API client.
  • If you see an error message that resembles the following: "INVALID_LOGIN: Invalid username, password, security token; or user locked out." or “Content is not allowed in prolog.”, then this test passed and your integration trusts DigiCert-signed certificates.
    • The presence of this response means that the underlying TLS connection was successful, despite the higher-level error. The TLS connection is the focus of this test.
  • If you instead see an error message that involves TLS or HTTPS, then the test has failed. Your API client will require adjustments to its list of trusted certificate authority certificates to trust DigiCert-signed certificates.
 
To test the compatibility of an API client that uses REST to communicate with Salesforce: Thanks,
Raj

 
We are using the chatter answers in community which is going to retire after Winter 18 release. Wanted some suggestions to perform the migration...below are the research...
Investigated on Q&A Migration App but wanted to know if someone has used this and its outcome. Was there any data impact? If yes, then how can we overcome that?.
What is the alternative? Is data loader an option?
Hi All,

Please help me to get a job. Currently am working as Salesforce Developer with 2.7 years of experience.

Am ready to join immedialy to any where(Job Location : Any where).

Please some one can help me!!!

i got 50+ best answers in this forum and member from 2015.

Thanks,
Maharajan.C
+91-9042584107
maharaja0393@gmail.com
Hi All,

Please help me to get a job. Currently am working as Salesforce Developer with 2.7 years of experience.

Am ready to join immedialy to any where(India or Any Country).

Please some one can help me!!!

i got 50+ best answers in this forum and member from 2015.

Thanks,
Maharajan.C
+91-9042584107
maharaja0393@gmail.com
 
Hi All,

Can you please help me to find unused apps in my salesforce instance to Metadata Cleanup

Thanks,
Raj
Hi All,

Can anyone please give a example third party app name to calculate the Opportunity Stage Duration (inbetween stages also).
Example : Proposal,Qualified,Ready Invoice,Negoatiation,Closed won.
In there i want to calculate the stage duration from Qualified to Closed won.Starting stage must be Qualified End stage Closed won
Qualified to Ready Invoice =?
Ready Invoice to Negoatiation =?
Negoatiation to Closed won =?

And also for Sales vs Quota report third party App.

Thanks,
Raj
Hi All,

Can you please anyone give a test class for me to the below Apex Class.

Public class AccountDisplatRecClsExtn{
Public id Current_Acc_Id;
    public AccountDisplatRecClsExtn(ApexPages.StandardController controller) {
Current_Acc_Id = controller.getRecord().id;
    }
     

  public List<Question__c> getcontList(){
   List<Question__c> accList = [select id,Name,AssessmentId__c,AssessmentId__r.Name,External_ID__c,Friendly_Name__c,Question_Plain__c,Question_Style__c,Sort_Order__c,(Select Id,Name,Red_Flag__c,Scoring__c from answers__r) from Question__c where AssessmentId__c=:Current_Acc_Id ORDER by Sort_Order__c ASC];
   return accList;
  
  }
    }

Thanks,
Raj
 
Hi,

In my salesforce org when i convert a lead it creates multiple account,contacts and opportunities at the same time and when i see the created by timings and created by user both are same.

http://docs.releasenotes.salesforce.com/en-us/spring16/release-notes/rn_sales_leads_edit_converted_leads.htm

In above link there is an article i studied about permission set which will enalble us to create multiple account,contacts and opportunities and we can able to view lead again in salesforce detail page but i disabled this options.

Even though i disabled this option i have duplicates created in my salesforce org and i have lead which i can edit on detail page after it converted...I didn't have any trigger.

Please help !!!!!!!!

Thanks,
Raj
Hi Friends,

Is there any way to retrieve my SF Dev Org Because i lost my Org Due to the Authenticator App in my Mobile i.e, am uninstalled the Authenticator App in my Phone which have a link with my Dev Org.

Thanks,
Raj.
Hi All,

Please Help!!!
Evaluation Criteria : Evaluate the rule when a record is created, and any time it's edited to subsequently meet criteria
Rule Criteria Opportunity :  StageEQUALSClosed Won
Workflow Action : Email Alert

>Here First my record meet the above rule criteria based on the evaluation criteria it sends an an Email i.e Opportunity stage equals Closed   Won
>After that in that same record i change the Opportunity stage to Need Analysis so now the record dont met the criteria so there is a no        Email
>Then i changed that Opportunity record stage to Closed Won now the record meet the criteria so its send an email again but i want to stop    the Sending an Email Now.


Thanks in Advance!!!
Raj.
Hi All,

Any One  please help me to code coverge because i got only 43% coverage

ApexTrigger :-
trigger sendNotificationTrigger on CampaignMember (after insert) {
    Set<Id> LeadIds = new Set<ID>();
    Lead_Campaign__c tm;//Assinging Custom setting To the variable tm
    tm=Lead_Campaign__c.getorgdefaults();
    String Template=tm.Email_Template_ID__c;
    Decimal Days=tm.Threshold_Days__c;
     
    list <CampaignMember> theCampaignMembers = new list<CampaignMember>();
    for(CampaignMember campMem : Trigger.new){//
    if(test.isRunningTest()){
        
        Days = 0;
    }
        if(campMem.leadid != null){
            LeadIds.add(campMem.leadid);
            theCampaignMembers.add(campMem);
         
            }
    // List containing Campaign Member records to be inserted  
    List<Messaging.SingleEmailMessage> mails =new List<Messaging.SingleEmailMessage>();   
    for(Lead ld : [select id, Status,Lead_age__c, owner.email from Lead where id IN : LeadIds])
    try
    {

    if(ld.Status!='Qualified'&&ld.Lead_age__c>=Days)
    //Checking Condition Status not equal to Qualified and Lead_Age_In_days__c greater than equal to 30
    {
 
     Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();// For Email
                             
      List<String> sendTo = new List<String>();
      sendTo.add(ld.Owner.Email);//sending message via Email to the Owner of the lead
      mail.setToAddresses(sendTo);
      mail.saveAsActivity = false;
      mail.setTemplateId(Template);//Using custom setting field template as template id
      mail.setTargetObjectId(ld.OwnerId);    
      mail.setWhatId(ld.id);
      mails.add(mail);
      Messaging.sendEmail(mails);
  
}
}
 catch (Exception e)
{

  ApexPages.addMessages(e);
  Profile adminProfile = [Select id From Profile Where Name='System Administrator' Limit 1];

     Messaging.SingleEmailMessage mail=new Messaging.SingleEmailMessage();
     List<String> toAddresses = new List<String>();
     toAddresses.add(adminProfile.id);
     mail.setToAddresses(toAddresses);
     mail.setSenderDisplayName('Apex error message');
     mail.setSubject('Error from Org : ' + UserInfo.getOrganizationName());
     mail.setPlainTextBody(e.getMessage());
     Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
}
  
}
}


Test Class -:

@isTest(SeeAllData = true)
public class sendNotificationTrigger
{
static testMethod void sendNotificationTrigger ()
{
     Test.startTest();      //Creates Contact to be linked to Campaign Member
Campaign cp =  [SELECT Id FROM Campaign LIMIT 1];
       //Creates a new campaign memeber, associaites it with 1 campaign
 Lead t1 = new Lead(Company= 'TestLead', LastName= 'TestL', Email = 'none@test.com',Status = 'Open' );
 insert t1;
 CampaignMember newMember = new CampaignMember (LeadId = t1.id, status='Sent', campaignid = cp.id);
 insert newMember;
 system.assertequals(t1.status,'Open')  ;

  
 
   
 Test.stopTest();
 }


Thanks,
Raj.
Hi All,

Can any one Please help to write a test class to my Trigger


trigger sendNotificationTrigger on CampaignMember (after insert) {
    Set<Id> LeadIds = new Set<ID>();
    Test_Setting__c tm;//Assinging Custom setting To the variable tm
    tm=Test_Setting__c.getorgdefaults();
    String Template=tm.Template__c;
    Decimal Days=tm.Threshold_Days__c;
     
    
    for(CampaignMember campMem : Trigger.new){//
        if(campMem.leadid != null){
            LeadIds.add(campMem.leadid);
         
            }
            
    List<Messaging.SingleEmailMessage> mails =new List<Messaging.SingleEmailMessage>();   
    for(Lead ld : [select id, Lead_age__c, Status, owner.email from Lead where id IN : LeadIds])
    if(ld.Status!='Qualified'&&ld.Lead_Age_In_days__c>=Days)
    //Checking Condition Status not equal to Qualified and Lead_Age_In_days__c greater than equal to 30
    {
     Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();// For Email
                             
      List<String> sendTo = new List<String>();
      sendTo.add(ld.Owner.Email);//sending message via Email to the Owner of the lead
      mail.setToAddresses(sendTo);
      mail.saveAsActivity = false;
      mail.setTemplateId(Template);//Using custom setting field template as template id
       mail.setTargetObjectId(ld.Ownerid);                           
      mails.add(mail);
  Messaging.sendEmail(mails);
}
}
}

Thanks
​Raj.
Hi Friends,

Is there any way to retrieve my SF Dev Org Because i lost my Org Due to the Authenticator App in my Mobile i.e, am uninstalled the Authenticator App in my Phone which have a link with my Dev Org.

Thanks,
Raj.
Hello,

I'm trying to test the trigger below, however my test is not passing in the IF condition.

Trigger
trigger ValidateLead on Lead (before insert, before update){

	if (Trigger.isBefore) {
    	for(Lead led : trigger.new){

    		Lead leds = [SELECT Id, Name FROM Lead WHERE id=: led.Id];
    		
    			if(ValidaDocumento.isCNPJ(led.CNPJ__c))
    				led.CNPJ__c = ValidaDocumento.imprimeCNPJ(led.CNPJ__c);
    			else
    				led.addError('O CNPJ informado é Inválido');
	    }
    }
}

test class:
public static testMethod void createLead() {
	    
	    Lead prospect = new Lead(
	        
			LastName = 'TestProspect',
			CNPJ__c = 'teste',
			Company = 'TestCompany',
			Estado__c = 'SP'
		);
		ValidaDocumento.isCNPJ(prospect.CNPJ__c);
		ValidaDocumento.imprimeCNPJ(prospect.CNPJ__c);
		insert prospect;
		
		Lead prospect2 = new Lead(
	        
			LastName = 'TestProspect',
			CNPJ__c = '68119173000167',
			Company = 'TestCompany',
			Estado__c = 'SP'
		);
		ValidaDocumento.isCNPJ(prospect2.CNPJ__c);
		insert prospect2;
		
		Lead prospect3 = new Lead(
	        
			LastName = 'TestProspect',
			CNPJ__c = '00000000000000',
			Company = 'TestCompany',
			Estado__c = 'SP'
		);
		insert prospect3;
		ValidaDocumento.isCNPJ(prospect3.CNPJ__c);
		
		Lead prospect4 = new Lead(
	        
			LastName = 'TestProspect',
			CNPJ__c = '11111111111111',
			Company = 'TestCompany',
			Estado__c = 'SP'
		);
		insert prospect4;
		ValidaDocumento.isCNPJ(prospect4.CNPJ__c);
		
		Lead prospect5 = new Lead(
	        
			LastName = 'TestProspect',
			CNPJ__c = '681191730001',
			Company = 'TestCompany',
			Estado__c = 'SP'
		);
		insert prospect5;
	    ValidaDocumento.isCNPJ(prospect5.CNPJ__c);
	}
}
I'm in doubt how to make the test pass through my if conditional.
 
Hi All,

Can any one help me to calculate number of sunday's in a given month and year using apex and vf page.

Ex: If i select March 2017 from vf page, i need to calculate number of sunday's from selected month and year.

Thanks in advance.
Can anyone let me know if im doing this correctly?

Need a validation rule that prevents a Sales user from updating a picklist to a Certain Value on a Certain Record Type.

For this excample, i want to prevent Sales User from updating picklist to Value1 (and allow all other values for them) for that record type

(AND( $User.ProfileId <> "Sales User",,$RecordType.Name = "Record Type Name",
ISCHANGED(Status__c),
NOT(ISPICKVAL(Status__c, 'Value2')),
NOT(ISPICKVAL(Status__c, 'Value3')),
NOT(ISPICKVAL(Status__c, 'Value4')),
)
)
Hello, 

I have a validation rule where the Picklist value = Yes, the text area field Assets Items should not be blank. The below VR is prompting that "Data Missing" Asset items are missing! when I complete the Assets Items field. 
Any idea how to modify the VR? 
Thank you!
 
AND(
    ISPICKVAL( Assets__c , 'Yes'),
    ISBLANK( Asset_Items__c )
)


 
  • September 16, 2019
  • Like
  • 0
Hello ,

Just got in a new instance and i have a question.
There is an integration with an other system and my instance send notification to it.
I looked into the class that make the call an i can observe that the URL of the other system is not used directly. And parameters also ( authentication , id ..) 
Here a sample of the variables used
public static String API_URL = 'callout:Api'

Where can i find the content of "API"?

Thank you
 
Hi All,
My requirement is share the leads owned by specified business Division SalesReps to other sales reps.
Below are my settings:
1. OWD for Lead Object is Private.
2. Profile -->Object Settings -> Read,Create,Edit.
As the Lead OWD is private, sales Reps are able to view the leads owned by them.
So I have created a Lead Sharing Rule.
With the above settings,  Sales Reps are able to view other sales reps leads, but they are able to edit the lead fields they don't own. Is any setting I am missing?.

If I change the Profile Object Settings -> Read,Create, then Actual Owner of Lead is not able to edit the fields.
Appreciated your help.

Thanks,
Naren
 
  • September 13, 2019
  • Like
  • 0
Hey there,

I'm new to APEX and curious about converting Apex Triggers to Apex Classes in order to be in line with the One-Trigger-per-Object pattern. 

Let's say I have the following, very simple Trigger: Whenever an Account gets updated, the number of related contacts gets populated in the custom field Number_of_Contacts__c. The Trigger code looks like this:
 
trigger relatedContacts on Account (before update) {  
   
   List<Contact> relatedContacts = [SELECT Id
                                    FROM   Contact
                                    WHERE  AccountId IN :Trigger.new];
        
   for (Account a : Trigger.new) {
        a.Number_of_Contacts__c = relatedContacts.size();
    }            
    
}
First question: How would the Apex Class for this Trigger look like?

Second question: How shall I reference the Apex Class in the Master Trigger for the Account object? At least I already know where to put it:
trigger MasterOpportunityTrigger on Opportunity (
  before insert, after insert, 
  before update, after update, 
  before delete, after delete) {

  if (Trigger.isBefore) {
    if (Trigger.isInsert) {

    } 
    if (Trigger.isUpdate) {
      // MY TRIGGER WILL GO HERE ;)
    }
    if (Trigger.isDelete) {

    }
  }

  if (Trigger.isAfter) {
    if (Trigger.isInsert) {

    } 
    if (Trigger.isUpdate) {

    }
    if (Trigger.isDelete) {

    }
  }
}

I would highly appreciate if someone could teach me this best practice!

Best, 
David
  • September 11, 2019
  • Like
  • 0
I am trying to create a formula that compares a date field Like Acme_Date__c = TODAY() then display "TODAY" for atext value. 

I'm not sure how to accomplish this result without getting errors 
How to update or remove the Campaign Member Status fields this differs from production to sandbox which is not correct. Please help to short out this cases?

While I am checking the field values in the sandbox showing the same value as such in the prod. but while adding/updating this is not same which is showing some default value in the pick list(sent, responded)

Sandbox having 2 status which is not correctWe need to update same like this in sandbox

I have a page that contains two lightning components. One is a calendar, the other is a list view. 

On the calendar lightning component, a user will click, a hidden modal will be displayed so the user can create a record. Upon save success, I want *just the calendar component* to refresh. Not the entire page. 

I've tried using $A.get('e.force:refreshView').fire(); on the callback in the calendar component. The result is both components refreshing. Same result when I create and fire a refresh event in the calendar component. 

I can't seem to find much documentation in regards to refreshing single components on a page. Any ideas?

Hello All,
I have a Batch Class where I am updating all of the Contact Owners to Match the Account owners.
I am unable to cober the condition in Class.
Here are the Classes.
@isTest

private class TestBatchContactownerUpdate 
{
    static List<Account> aList;
    static testMethod void myUnitTest() 
   
    {
        UpdateContactOwnerToAccountOwnerBatch bat = new UpdateContactOwnerToAccountOwnerBatch();
     
        bat.finish(null);
    }
    static testMethod void testSchedulable()
    {
        Test.startTest();        
        String cron = '0 0 0 17 11 ? 2033';
        System.schedule('BATR99zz', cron, new UpdateContactOwnerToAccountOwnerBatch());
        Test.stopTest();
    }
  
    {
     Account acc = new Account(
            Name = 'testaccount'
            ,BillingPostalCode='22821'      
            ,RecordTypeId = '222222' 
        );
        insert acc; 

      
        Account sacc= [SELECT Id, Name,OwnerID from Account Where name = 'testAccount' limit 1];
       
        Contact con = new Contact(
            AccountId = sacc.id
            ,Lastname = 'testcontact'
            ,Firstname ='testdude'
            ,RecordTypeId = '1111111'
        );
        insert con;


       
        Test.startTest();
        Profile p = [SELECT Id FROM Profile WHERE Name='Standard User']; 
            User u1= new User(Alias = 'standt', Email='testemail@junkmail.com', 
                        EmailEncodingKey='UTF-8', LastName='Tester', LanguageLocaleKey='en_US', 
                        LocaleSidKey='en_US', ProfileId = p.Id, 
                        TimeZoneSidKey='America/Los_Angeles', UserName='testemail@junkmail.com');
            
            System.runAs(u1) {
      // The following code runs as user 'u'  
       // create test contact
        Contact c1 = new Contact(FirstName='Jane',LastName='Doe', Account=acc);
        insert c1;
        
        //assert your results using system.assert and system.asserEquals

        //reload objects to make sure values are loaded
        c1 = [select id, name,  OwnerId from contact where id=:con.id];
        con = [select id, name, OwnerId from contact where id=:con.id];

        acc= [select id, ownerId from Account where id=:acc.id];
       // system.assert(c1.OwnerID = acc.OwnerID);
            
            
            
        Test.stopTest();
        }
    }
}
global class UpdateContactOwnerToAccountOwnerBatch implements Database.Batchable<sObject>, Schedulable{

        
    List<contact> contactsToChangeOwner = new List<contact>();
    global final String Query ='SELECT Id, AccountId, Ownerid, Account.ownerid from contact where AccountId != null';
       global Database.QueryLocator start(Database.BatchableContext BC){
          return Database.getQueryLocator(query);
       }
       
       global void execute(Database.BatchableContext BC, List<contact> scope){
        
        for(contact con: scope){     ----  No Coverage
            if(con.ownerid!=con.Account.ownerid){    ----  No Coverage
                con.ownerid = con.Account.ownerid;     ----  No Coverage
                contactsToChangeOwner.add(con);    ----  No Coverage
            }           
        }
        update contactsToChangeOwner;      ----  No Coverage
       }
       
    global void finish(Database.BatchableContext BC){}
    
    global void execute(SchedulableContext sc)
    {
      Database.executeBatch(new UpdateContactOwnerToAccountOwnerBatch ());
    } 
    
    
    
}

If someone would review my Test Class it would be greatly appreciated.
Cheers,
M
 
Write a lightning component to display the open cases related to the logged in user

Hello,

Did anyone else notice that the view state limit in Visualforce pages has been increased from 135 to 170 KB in the new release of Spring 2019