• Maharajan C
  • ALL STAR
  • 14553 Points
  • Member since 2015
  • Consultant
  • Infosys


  • Chatter
    Feed
  • 474
    Best Answers
  • 4
    Likes Received
  • 43
    Likes Given
  • 16
    Questions
  • 1596
    Replies
Controller:public class AppointmentsViewController {


    public List<Doctor__c> doctorList {get;set;}
    public List<SelectOption> doctorSelectOptionList{get;set;}
    public List<Appointment__c> apointmentList{get;set;}
    public String doctorId {get;set;}
    public List<Patient__c> patientList{get;set;}
    public List<SelectOption> patientSelectOptionList{get;set;}
    public Integer noOfRecords{get; set;}
    public Integer size{get;set;}
    
    public AppointmentsViewController() {
       doctorList = [
           SELECT Id, Name, Working_Hours_Start__c, Working_Hours_End__c
           FROM Doctor__c
           ORDER BY Name ASC
       ];
        
        patientList = [
            SELECT Id, Name
            FROM Patient__c
        ];
        
        patientSelectOptionList = new List<SelectOption>();
        
        for(Patient__c item :patientList)
        {
            patientSelectOptionList.add(new SelectOption(item.Id, item.Name));
        }
        doctorId = doctorList.isEmpty() == FALSE ? doctorList[0].Id : NULL;
        
       doctorSelectOptionList = new List<SelectOption>();
        
        for(Doctor__c item :doctorList) {
            doctorSelectOptionList.add(new SelectOption(item.Id, item.Name));
        }
        getAppointments();
       
        
    }
    
    public void getAppointments () {
        apointmentList = [
            SELECT Id, Name, Doctor__c, Patient__c, Appointment_Date__c, Duration_in_minutes__c
            FROM Appointment__c
            WHERE Doctor__r.Id = :doctorId
        ];
    }



    public List<Appointment__c> Appointment { get{

        return (List<Appointment__c>)setCon.getRecords();

    } set; }



    public ApexPages.StandardSetController setCon {

        get{

            if(setCon == null){

                size = 20;

                List<Appointment__c> Appointment = [
                    SELECT Id, Name, Doctor__c, Patient__c, Appointment_Date__c, Duration_in_minutes__c
                    FROM Appointment__c];

                setCon = new ApexPages.StandardSetController(Appointment);

                setCon.setPageSize(size);

                noOfRecords = setCon.getResultSize();

            }

            return setCon;

        }set;

    }






}




Test:
@isTest
private class AppointmentsViewControllerTest {
    
    @isTest static void AppointmentsViewControllerTest1() {
        
        Doctor__c doctor = new Doctor__c(
        );
        
        insert doctor;
        
        AppointmentsViewController controller = new AppointmentsViewController();
        
        Appointment__c Appointment = new Appointment__c(
        );
        insert Appointment;
        
            ApexPages.standardSetController sc = new ApexPages.standardSetController(doctor

        
        
     // ApexPages.StandardSetController standardSetController = new ApexPages.StandardSetController(doctor);
        
    }
    
       
    

}
Hi,
I have added opportunity as a lookup in contact. I want my description on contact to be updated with the related opportunity's stage name. My following code is not working. Please let me know where I went wrong:

trigger populateOppStage on Contact (before insert, before update) {
   Set<ID> opps = New Set<ID>();
    for (contact con:trigger.new){
        opps.add(con.opportunity__r.Id);
    }
    Map<Id, String> mapOppToStage = New Map<Id, String>();
    for(opportunity opp:[SELECT ID, stagename 
                      FROM opportunity WHERE ID IN:opps]){
        mapOppToStage.put(opp.id, opp.stagename);
    }

    for (contact c:trigger.new){
        if(mapOppToStage.containsKey(c.opportunity__r.Id)){
                c.Description= mapOppToStage.get(c.Opportunity__r.id);
        }
    }
}
NOT(

     OR(
   
    Country  = 'US',
    Country  = 'USA',
    Country  = 'United State of America',
     ISBLANK(Country) 

     ) 

     )  
     
 AND(
     LEN(State)= 2,
     CONTAINS(State, "AB"},
     CONTAINS(State, "CD"},
     CONTAINS(State, "EF"}
)
im trying to do the test class for this code

public class Claseprogramadausuario {
    
public static void obtenerinfo(){

List<User> nlist = [SELECT Id, Username, FirstName, LastName, EmployeeNumber, UserRole.Name, Profile.Name, CreatedDate, LastModifiedDate, LastLoginDate, isActive FROM User WHERE Profile.Name != 'SelfService'];
string header = 'Id, Username , FirstName, LastName, EmployeeNumber, UserRole.Name,  Profile.Name, Created Date, LastModifiedDate, LastLoginDate, isActive \n';
string finalstr = header ;
for(User u: nlist)
{

       string recordString = u.id+','+u.Username +',' + u.FirstName +','+ u.LastName +','+ u.EmployeeNumber+','+ u.UserRole.name +','+ u.profile.name +','+ u.CreatedDate +','+ u.LastModifiedDate +','+ u.LastLoginDate +','+ u.IsActive +'\n';

       finalstr = finalstr +recordString;
}

Messaging.EmailFileAttachment csvAttc = new Messaging.EmailFileAttachment();
blob csvBlob = Blob.valueOf(finalstr);
string csvname= 'Userinfo.csv';
csvAttc.setFileName(csvname);
csvAttc.setBody(csvBlob);
Messaging.SingleEmailMessage correo = new Messaging.SingleEmailMessage();
correo.toAddresses = new String[] {'javierandoni@gmail.com', 'dlramirez@izzi.mx'};
correo.subject = 'Clase programada test';
correo.plainTextBody = 'Clase programada test';
Messaging.SingleEmailMessage[] correos =   new List<Messaging.SingleEmailMessage> {correo};
correo.setPlainTextBody('Account CSV ');
correo.setFileAttachments(new Messaging.EmailFileAttachment[]{csvAttc});
Messaging.SendEmailResult[] results = Messaging.sendEmail(correos);

if (results[0].success) 
{
System.debug('The email was sent successfully.');
} else 
{
System.debug('The email failed to send: ' + results[0].errors[0].message);
}
}
}

And the test class im trying to do is this

// Test Class
@IsTest
Public class ClaseprogramadausuarioTest {
    @isTest static void testenviomail(){
        string pri= Claseprogramadausuario.obtenerinfo();
        System.assertEquals('The email was sent successfully.', pri);
    }
}

but i get this message: Illegal assignment from void to String.
 
Hi, 
I have an APEX Class that is updating a list and later I am presenting that list via LWC on the Lightning Record Page. 
I would like to write a test Class for the APEX Class. 
APEX Class:
public class PriceBookEntriesFromAccount {
    
    @AuraEnabled
    public static List<BB_Produkt__c> getPriceBookEntries(String artId) {
        List<BB_Produkt__c> bb = 
            [SELECT Name, Id, Berichsartikel__c, Berichsartikel_Copy__c, Produkt__r.Name, Verkostung__c, Kaufinteresse__c, Unternehmen__r.Name, CreatedDate 
             FROM BB_Produkt__c 
             WHERE Unternehmen__r.Id = :[SELECT Unternehmen__r.Name FROM Besuchsbericht__c WHERE Id =:artId].Unternehmen__r.Id
            ORDER BY CreatedDate DESC];
        //Add isAccessible() check
        return bb;
    }
    
    @AuraEnabled
	public static void updateRelatedList(List<BB_Produkt__c> Bblist)
    {
        if(Bblist!= null && Bblist.size()>0)
        {
            update Bblist;
            Bblist.sort();
        }
    }
}
So far this is what I have written, but I am getting 0% code coverage:
@isTest(SeeAllData=true)
public class testPriceBookEntriesFromAccount {
    
    public static testMethod void testBB_Produkt()
	{

		Account createAccount =new Account(Name='TestA');
		insert createAccount;
        
        Product2 createProduct2 =new Product2(Name='TestP');
		insert createProduct2;

		BB_Produkt__c createBB_Produkt =new BB_Produkt__c(Produkt__c=createProduct2.ID, Unternehmen__c=createAccount.Id);
		insert createBB_Produkt;

		createBB_Produkt.Feedback_Verkostung_1_5__c = 2;
		update createBB_Produkt;
	}
}


 
HI,
I have Create a page like account form and add some related contacts
and i want make that contacts editable.
Can someone help i am practicing on it.
code...on standardcontroller
<apex:page standardController="Account">
    <style>
        .s1{Background-Color: LightBlue;}
        .s2{Background-Color: Pink;}
    </style>
    <apex:form >
        <apex:sectionHeader title="Account" subtitle="Account Form"/>
        <apex:pageBlock title="Account Form" >
            <apex:pageBlockSection title="Account Information" columns="2">    
                <apex:inputField value="{!Account.Owner.Name}" styleClass="s1"/>
                <apex:inputField value="{!Account.Rating}" style="BackGround-Color:Pink; color: blue;"/>
                <apex:inputField value="{!Account.Name}" styleClass="s1"/>
                <apex:inputField value="{!Account.Phone}" styleClass="s2"/> 
                <apex:inputField value="{!Account.ParentId}" styleClass="s1"/>
                <apex:inputField value="{!Account.Fax}" styleClass="s2"/> 
                <apex:inputField value="{!Account.AnnualRevenue}" styleClass="s1"/>
                <apex:inputField value="{!Account.NumberOfEmployees}" styleClass="s2"/>  
                <apex:inputField value="{!Account.Ownership}" styleClass="s1"/>
                 <apex:inputField value="{!Account.website}" styleClass="s2"/>  
                
            </apex:pageBlockSection>
            <apex:pageBlockSection title="Additional Information" columns="2">    
                <apex:inputField value="{!Account.Site}" styleClass="s1"/>
                <apex:inputField value="{!Account.AccountNumber}" styleClass="s2"/>
                <apex:inputField value="{!Account.Industry}" styleClass="s2"/>
                <apex:inputField value="{!Account.Type}" styleClass="s1"/> 
            </apex:pageBlockSection>           
            <apex:pageBlockSection title="Address Information" columns="2">  
                <apex:inputField value="{!Account.BillingStreet}" styleClass="s1"/>
                <apex:inputField value="{!Account.ShippingStreet}" styleClass="s2"/>
                <apex:inputField value="{!Account.BillingState}" styleClass="s1"/>
                <apex:inputField value="{!Account.ShippingState}" styleClass="s2"/>
                <apex:inputField value="{!Account.BillingCity}" styleClass="s1"/>
                <apex:inputField value="{!Account.ShippingCity}" styleClass="s2"/>
                <apex:inputField value="{!Account.BillingPostalCode}" styleClass="s1"/>
                <apex:inputField value="{!Account.ShippingPostalCode}" styleClass="s2"/>
                <apex:inputField value="{!Account.BillingCountry}" styleClass="s1"/>
                <apex:inputField value="{!Account.ShippingCountry}" styleClass="s2"/>
            </apex:pageBlockSection>            
            <apex:pageBlockSection title="Description" columns="2">    
                <apex:inputField value="{!Account.Description}" styleClass="s1"/>
            </apex:pageBlockSection> 
            <apex:pageBlock title="Related Contacts">
    
                <apex:pageBlockTable value="{!Account.contacts}" var="con">
                    <apex:column value="{!con.firstName}"/>
                    <apex:column value="{!con.LastName}"/>
                    <apex:column value="{!con.Phone}"/>
                    <apex:column value="{!con.AccountId}"/>         
                </apex:pageBlockTable>

                </apex:pageBlock>
            
            <apex:pageBlockButtons location="Bottom">
                <apex:commandButton action="{!Save}" value="Save"/>
                <apex:commandButton action="{!Cancel}" value="Cancel"/>          
            </apex:pageBlockButtons>
        </apex:pageBlock>
    </apex:form>
</apex:page>

 
  • September 27, 2021
  • Like
  • 0
What is this type of error means: what is possible solution?
trigger ApexTrigger10 on Contact (After insert,After Delete) {
    
    set<id> contactSet = new set<id>();
    List<Account> newAccountList = new List<Account>();
    
    if(trigger.isInsert && trigger.isAfter){
        for(Contact con:trigger.new){
            contactSet.add(con.Account);
         }
    }

    if(trigger.isDelete && trigger.isAfter){
        for(Contact con:trigger.old){
            contactSet.add(con.Account);
         }
    }
    List<Account> Acc= [SELECT id, name,(SELECT id,name from contacts) FROM Account WHERE id IN:contactSet];
    for( Account a : Acc)
    {
        a.Total_number_of_contacts__c= a.contacts.size();
        newAccountList.add(a);
    }
    update newAccountList;
}
 
I have the following requirement. I have to change styles of the second element rendered of this list, i tried a solution to do that but doesn't work, can you help me please?

data = {
                  issues: [
                                  {
                                         'chapter' :  'something1'
                                         'posiion':  '2A'
                                  },
                                 {
                                          'chapter': 'something2',
                                          'position' : '3A'
                                 },
                                 {
                                           'chapter : 'something3',
                                           'position': '4A'
                                 }
                                      ]
             }

html code:

<template for:each={data.issues} for:item="item" for-index="index">
             <h3 class ={dinamicClass} > {index} {item.chaper} </h3>
             <h3 claas ={dinamicClass} >{index} {item.position} </h3>
</template>

output: 
                          0 something1     0 2A
                          1 something2     1 3A
                          2 something3     3 3A

the idea is to modificate the second row, in bold and bigger.

I try this in JS but doesnt not work

@api index;

get dinamicClass(){
  return this.index == 2 ? 'slds_xxxxxxx_large' : slds_xxxxxxx_small'
}


Any idea to can implement to solve this?  Thanks
I have a picklist with values : 5%, 10%, 15%
And I want to use it in the formula field in percent format only like 5/100.
So please suggest what syntax should I write?
 
Hello

My Requirement is to, whenever there is Phone Number entered in case Object, then in that case, if User enters any Special Characters, then it should ignore the Special Characters and display only the Digits.

I wrote a Trigger on it. Seems to be Correct. But, not working while I am testing.Please someone test in your Org and let me know, where I did mistake.

trigger PhNumValidation on Case (before insert,before update) {
    list<case> clist=new list<case>();
    for(Case c:Trigger.new){
      if (c.Phone_Number__c != null ) {
           string phone =c.Phone_Number__c;
          string newph=phone.replaceAll('\\D','');
          system.debug('Ph: '+newph);
        }   
          
           
        }
        
    }


Thanks
GSN
I have followed numerous guides on creating Apex Test Classes, however I am using the class to reference data on my LWC and I am unsure how to go about testing.

Please see current Apex Code:
public class AccountContactController{
      
    @AuraEnabled(cacheable=true)
    public static List<AccountContactListWrapper> getAllAccountWithContacts(string searchKey){
        string searchKeyword = '%' + searchKey + '%';
        List<AccountContactListWrapper> accWrapperList = new List<AccountContactListWrapper>();
        List<Account> accList = [SELECT Id, Name, 
                                (SELECT Id, Name, Email, Phone, Title FROM Contacts), 
                                (SELECT Id, Name, Region_picklist__c, Total_Units__c FROM ChildAccounts) 
                                FROM Account WHERE Active__c = TRUE AND RecordTypeId = '0122K000001Dio1QAC' ORDER BY Name];
        if(!accList.isEmpty()){
            for(Account acc : accList){
                AccountContactListWrapper accWrapper = new AccountContactListWrapper();
                accWrapper.accRecord = acc;
                accWrapper.contactList = acc.Contacts;
                accWrapper.contactCount = acc.Contacts.size();
                accWrapper.NumberOfChildAccounts=acc.ChildAccounts.size();
                accWrapperList.add(accWrapper);
            }
        }
        return accWrapperList;
    }
    
    // wrapper class with @AuraEnabled and {get;set;} properties 
    public class AccountContactListWrapper{
        @AuraEnabled
        public Account accRecord{get;set;}
        @AuraEnabled
        public List<Contact> contactList{get;set;}
        @AuraEnabled
        public Integer contactCount{get;set;}
        @AuraEnabled
        public Integer NumberOfChildAccounts{get;set;}
    }
}

Can anyone help guide me on the proper method to testing this code so that we can push it to production with over 75% coverage?
Hi there, I am trying to learn deployment but couldn't find outbound change sets.
Even tried to check mark "create and upload change sets" under administrative permissions in my profile but couldn't find that too :(


Thanks.
Hi everyone,am trying to create a contact related to paritcular account in lightning .tried so far..,and embeded this component in accountrecord page ,but unable to save. can someone help me out .

Thanks in Advance.
apex:
public class QuickCreatecontact {
@AuraEnabled
    public static void createcontact(contact con,Id AccountId){
        con.AccountId=AccountId;
        insert con;
    }
}

component:
<aura:component controller="QuickCreatecontact" implements="flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,force:lightningQuickAction" access="global" >
    <aura:attribute name="createcontact" type="contact"/>
    <aura:attribute name="accountId" type="string"/>
   <!-- <aura:handler name="init" value="{!this}" action="{!c.doinit}"/>-->
    <div>
        <lightning:input type="text" name="{!v.createcontact.LastName}" label="Enter LastName" />
        <lightning:input type="text" name="{!v.createcontact.FirstName}" label="Enter firstName"/>
        <lightning:input type="phone" name="{!v.createcontact.phone}" label="Enter phone"/>
        
    </div>
    <div>
        <lightning:button label="save" variant="brand" onclick="{!c.dosave}"/>
     </div>
</aura:component>

js:
({
    dosave : function(component, event, helper) {
        var action=component.get("c.createcontact");
        action.setParams({
            con:component.get("v.createcontact"),
            Id:component.get("v.accountId")
        });
        action.setCallback(this,function(response){
            var state=response.getState();
           
            if(state==='SUCCESS'){
                var result=response.getReturnValue();
               alert('SUCCESS');
                
               
            }else if(state==='INCOMPLETE'){
                
            }
        });
        $A.enqueueAction(action);
    }
})
I want to know how to parse the URL params from a get request
/services/apexrest/Endpoint/?subject=test&status=active&priority=1&origin=?subject=test&status=active&priority=1
I want to parse the url params in the class below
@HttpGet
    global static void getStatus() {
        RestRequest request = RestContext.request;
        System.debug(request.requestURI); 
        
    }

Please help!
"When an account is inserted ou update must show a view for the user to write the destiny email and after this, the apex trigger is shoot sending an email to the destination email that the user wrote."
 
I don't know how to make this... Is possible to make front-end interact with a trigger? How to?? Please sharing some documentation or trailhead about this with me 
 
 

Hi All, I'm looking for some advice on best practice. I want to loop through Options and I've come up with the following solution which actually works. What I want to know is whether or not my method of a loop within a loop is best practice or if there is a better way?

String json = '{'+
    '  \"TrackingCategories\": ['+
    '    {'+
    '      \"Name\": \"Region\",'+
    '      \"Status\": \"ACTIVE\",'+
    '      \"TrackingCategoryID\": \"351953c4-8127-4009-88c3-f9cd8c9cbe9f\",'+
    '      \"Options\": ['+
    '        {'+
    '          \"TrackingOptionID\": \"ce205173-7387-4651-9726-2cf4c5405ba2\",'+
    '          \"Name\": \"Eastside\",'+
    '          \"Status\": \"ACTIVE\"'+
    '        },'+
    '        {'+
    '          \"TrackingOptionID\": \"6eb12fdf-63de-4033-98df-be679d84e3c2\",'+
    '          \"Name\": \"North\",'+
    '          \"Status\": \"ACTIVE\"'+
    '        },'+
    '        {'+
    '          \"TrackingOptionID\": \"6159bdd4-b634-4338-a664-e929aa73f70f\",'+
    '          \"Name\": \"South\",'+
    '          \"Status\": \"ACTIVE\"'+
    '        },'+
    '        {'+
    '          \"TrackingOptionID\": \"161ad543-97ab-4436-8213-e0d794b1ea90\",'+
    '          \"Name\": \"West Coast\",'+
    '          \"Status\": \"ACTIVE\"'+
    '        }'+
    '      ]'+
    '    }'+
    '  ]'+
    '}';
TrackingOptionsResponse obj = TrackingOptionsResponse.parse(json);
System.debug('obj='+obj);



for(TrackingOptionsResponse.TrackingCategories r :obj.TrackingCategories){
    system.debug('r='+r.Name);
    System.debug('r2='+r.Options);
    for(TrackingOptionsResponse.Options l :r.options){
        System.debug('l='+l.Name);
    }
}

Thanks,

Dan

facing trouble to one object to to another in trigger to solve that query
 
  • If Candidate is applying for a job whose status is Not Active(deactivate job). He should get an error, “This Job is not active. You can not apply for this job.

in this queston candidate object have a lookup field to select job  and according to job object  field active status . candidate shold able to select .

how to write query to check from old job data to a new candidate User-added imageUser-added image
Hello, I am trying to get the User->Id field using a custom field (Id_SAP__c) that i have in the user object. 
To do this i have created a map with those two fields in order to get the id of the user but i am receiving an error and i dont know how to solve it.
Please, can anyone help me?

This my code:

public static void fillOwnerField(List<Promoci_n__c> lstPromociones){
        Set<String> setResources = new Set<String>();
        for(Promoci_n__c p :lstPromociones){
            if(p.Comercial_Id_SAP__c != null){
                setResources.add(p.Comercial_Id_SAP__c);
            }   
        }
        System.debug('***setResources = '+setResources);
        if(setResources.size() > 0){
            Map<Id, User> mapSR = new Map<Id, User>([Select Id, Id_SAP__c From User where Id_SAP__c in: setResources]);
            System.debug('***mapSR = '+mapSR);
            for(Promoci_n__c p :lstPromociones){
                System.debug('***p.Comercial_Id_SAP__c = '+p.Comercial_Id_SAP__c);
                System.debug('***Comercial_Asignado__c = '+mapSR.values());
                System.debug('***Comercial_Asignado__c = '+mapSR.get(p.Comercial_Id_SAP__c).Id_SAP__c);
                p.Comercial_Asignado__c = mapSR.get(p.Comercial_Id_SAP__c).Id_SAP__c;
            }

        }
    }

I get the error in line

System.debug('***Comercial_Asignado__c = '+mapSR.get(p.Comercial_Id_SAP__c).Id_SAP__c);

thank you in advance
Handle force:refreshView Event in LWC: (<aura:handler event="force:refreshView" action="{! c.action }"/> in LWC)

For $A.get('e.force:refreshView').fire(); we have some alternate in LWC  --->  eval("$A.get('e.force:refreshView').fire();");
https://www.sfdcpanther.com/how-to-refresh-page-using-lightning-web-component/
https://salesforce.stackexchange.com/questions/251299/force-refresh-view-in-lwc


But force:refreshView Event handle there is no alternate as of now in LWC. If there is any find out please post below.

For this i have three working idea:

1. using broker Aura and broker LWC Compoenent, pubsub communication. 
https://github.com/mitchspano/LWCRefreshDemo
2. Using Aura Component and Lightning Messaging Service.
3. using Platform Event to directly refresh the LWC Component.


For a demo purpose i have took the below scenario:

1. Created the standard quick action to create contact from Account Page.
2. Created the custom LWC Lightning datatable to show the related contacts under account and placed this component in Lightning Account Detail Page.
3. So, whenever i create contact from quick action my datatable needs to refresh without any manual page refresh.

If this post helps any one give me your likes on this post.

Code is added in below same post.

Thanks,
Maharajan.C
Hi Guys,

From last month itself I am not recieving any replies from Salesforce developer forum if i posted answers for someones's questions.

Before a month it's working fine. And also forum page not  loading fully only am able to see 10 - 20 Questions. Number of replies and Solved button also not visible in questions.

Any idea how to solve this...

Thanks,
Maharajan.C
Hi All,

Add/Remove Records using LWC.

If any one want to create Add/Remove multiple records in lightning web component dynamically then please refer this post. 

Features:
1. Add rows using plus( + ) button.
2. Dynamic Add/Remove record row.
3. Proper Serial Number in table. For each index starts from 1.
4. Clear All Feature.
5. Save button label change button.
6. Toast Message after record succesfully inserted.

Refer the code in below post...

Like this Post if it's helps to any one !!!

Thanks,
Maharajan.C
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.
Handle force:refreshView Event in LWC: (<aura:handler event="force:refreshView" action="{! c.action }"/> in LWC)

For $A.get('e.force:refreshView').fire(); we have some alternate in LWC  --->  eval("$A.get('e.force:refreshView').fire();");
https://www.sfdcpanther.com/how-to-refresh-page-using-lightning-web-component/
https://salesforce.stackexchange.com/questions/251299/force-refresh-view-in-lwc


But force:refreshView Event handle there is no alternate as of now in LWC. If there is any find out please post below.

For this i have three working idea:

1. using broker Aura and broker LWC Compoenent, pubsub communication. 
https://github.com/mitchspano/LWCRefreshDemo
2. Using Aura Component and Lightning Messaging Service.
3. using Platform Event to directly refresh the LWC Component.


For a demo purpose i have took the below scenario:

1. Created the standard quick action to create contact from Account Page.
2. Created the custom LWC Lightning datatable to show the related contacts under account and placed this component in Lightning Account Detail Page.
3. So, whenever i create contact from quick action my datatable needs to refresh without any manual page refresh.

If this post helps any one give me your likes on this post.

Code is added in below same post.

Thanks,
Maharajan.C
Hi All,

Add/Remove Records using LWC.

If any one want to create Add/Remove multiple records in lightning web component dynamically then please refer this post. 

Features:
1. Add rows using plus( + ) button.
2. Dynamic Add/Remove record row.
3. Proper Serial Number in table. For each index starts from 1.
4. Clear All Feature.
5. Save button label change button.
6. Toast Message after record succesfully inserted.

Refer the code in below post...

Like this Post if it's helps to any one !!!

Thanks,
Maharajan.C
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.

I'd like to create a formula field that update a custom field Net Sales with the TM Total Amount if the Created date is equal to today. I am unable to create a workflow or process builder because the Net Sales Field is already formula field with different criteria. 

IF (Created_Date__c=Today()), Net_Sales_Field__c = TMTotalAmount__c

Any help would be greatly appreciated.
 
  • October 20, 2021
  • Like
  • 0
Hi
I am new to salesforce development. 
How can add trigger logic in below helperclass. 

this is the helperclass. 
public class Service_CaseTriggerHelper {
    public static void HelperMethod(List<Case> Caselist) {
    Set<Id> contactIds = new Set<Id>();
    Set<Id> acctIds = new Set<Id>();
    for (Case c : Caselist) {
     contactIds.add(c.ContactId);
     acctIds.add(c.AccountId);
 }
 List <EntitlementContact> entlContacts =
     [Select e.EntitlementId,e.ContactId,e.Entitlement.AssetId
      From EntitlementContact e
      Where e.ContactId in :contactIds
      And e.Entitlement.EndDate >= Today
      And e.Entitlement.StartDate <= Today];
 if(entlContacts.isEmpty()==false){
     for(Case c : Caselist){
         if(c.EntitlementId == null && c.ContactId != null){
             for(EntitlementContact ec:entlContacts){
                 if(ec.ContactId==c.ContactId){
                     c.EntitlementId = ec.EntitlementId;
                     if(c.AssetId==null && ec.Entitlement.AssetId!=null) c.AssetId=ec.Entitlement.AssetId;
                    break;
                 }
             }
         } 
     }

 }else{
     List <Entitlement> entls = [Select e.StartDate, e.Id, e.EndDate,
                                 e.AccountId, e.AssetId
                                 From Entitlement e
                                 Where e.AccountId in :acctIds And e.EndDate >= Today
                                 And e.StartDate <= Today];
     if(entls.isEmpty()==false){
         for(Case c : Caselist){
             if(c.EntitlementId == null && c.AccountId != null){
                 for(Entitlement e:entls){
                     if(e.AccountId==c.AccountId){
                         c.EntitlementId = e.Id;
                         if(c.AssetId==null && e.AssetId!=null)
                             c.AssetId=e.AssetId; break;
                     }
                 }
             }
         }
      }

     }

 }
}
This is the trigger. 
trigger Service_CaseTrigger on Case (Before Insert, Before Update) { 

    Switch on Trigger.operationType {

        when BEFORE_INSERT {

            Service_CaseTriggerHelper.HelperMethod(TRIGGER.NEW);

        }

        when BEFORE_UPDATE {

            Service_CaseTriggerHelper.HelperMethod(TRIGGER.NEW);

        }

    }

}

The below trigger to be add in above helperclass and trigger. 
trigger CompleteResolutionTimeMilestoneopen on Case (after update) {
Id recId = Schema.SObjectType.Case.getRecordTypeInfosByName().get('Incident').getRecordTypeId();
    if (UserInfo.getUserType() == 'Standard'){
        DateTime completionDate = System.now(); 
            List<Id> updateCases = new List<Id>();
            for (Case c : Trigger.new){
                    if (((c.RecordTypeId == recId)&&(c.Status == 'open'))&&((c.SlaStartDate 
                        <= completionDate)&&(c.SlaExitDate == null)) )
        updateCases.add(c.Id);
        }
    if (updateCases.isEmpty() == false)
          milestoneUtils.completeMilestone(updateCases,'Initial Response', completionDate);
         
    

    }
}
Apex class code:
public with sharing class TrackOrderController {
    public string ordernum {get; set;}
    public date orderDate {get; set;}
    public List<Order> Order {get; set;}
    public List<OrderItem> status {get; set;}
    public List<string> vrs {public get; private set;}
    public List<string> pro {public get; private set;} 
    public List<integer> index {public get; private set;}
    
    public PageReference findOrder()
    {
        try{
      
        Order = [SELECT id FROM Order where PoNumber=:ordernum and PoDate =: orderdate ];
        status = [SELECT Product_name__c,Vehicle_Request_Status1__c FROM OrderItem WHERE OrderId =: Order[0].Id];
        system.debug('size-->'+status.size());
        vrs = new List<String>();
        index = new List<integer>();   
        for(integer i=0; i<status.size(); i++){
            index.add(i);
            if(status[i].Vehicle_Request_Status1__c != null){
            vrs.add(status[i].Vehicle_Request_Status1__c);
            }else{
                vrs.add('Null');
            }
        }
           
        system.debug(status);
        system.debug('vrs list--->'+vrs);
        system.debug('index list--->'+index);
        pro = new List<string>();
        for(integer i=0; i<status.size(); i++){
             pro.add(status[i].Product_name__c);
        }

        system.debug('pro list--->'+pro);
        return null;
        }
        catch(Exception ex){ ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR,'Please check purchase number and date')); return null; }
    }
    public PageReference reset() {
        PageReference newpage = new PageReference(System.currentPageReference().getURL());
    newpage.setRedirect(true);
    return newpage;
    }
}


Test class:
@isTest(SeeAllData=true)
public class TrackOrderControllerTest {
    
static testMethod void findOrder(){
  
      Account acc = New Account();
        acc.name = 'test';
        acc.CR_Number__c = '1234567890';
        acc.CustomerName__c = 'test acc';
        acc.CR_Date_English__c = Date.newInstance(2016, 12, 9);
        acc.CR_Capital__c = 12426;
        acc.Current_Revenue__c = 1233;
        acc.Special_Admin_Rate__c = 123456;
        acc.Security_Type__c = 'ghayth';
        acc.ID_Issuer__c = 'asdasd';
        acc.CR_City__c = 'asdasd';
        acc.Workforce__c = 'sdadad';
        acc.In_Business__c = 'sdasdasdas';
        acc.Nationality_of_Business__c = 'India';
        acc.Arabic_Date__c = Date.newInstance(2016, 10, 7);
        acc.Company_Establishment__c = 'sdads';
        acc.Bank2__c = 'sdfdsf';
        acc.City_Region__c = 'sadf';
        insert acc;  
        
        Product2 newProduct = new Product2();
        newProduct.name = 'abc';
        newProduct.Varient__c = 'asd';
        newProduct.Make__c = 'AMI';
        newProduct.Model__c = 'SEMI TRAILER';
        newProduct.ModelYear__c = 2018;
        newProduct.Fuel_Type__c = 'Petrol';
        newProduct.Transmission__c = 'Powershift';
        newProduct.Internal_Purchase_Price__c = 25;
        newProduct.Registration_Fee__c = 25;
        Insert newProduct;
        
         Pricebook2 customPB = new Pricebook2(Name='Custom Pricebook', isActive=true);
        insert customPB;
        
        PricebookEntry customPrice = new PricebookEntry(
            Pricebook2Id = customPB.Id, Product2Id =newProduct.Id,
            UnitPrice = 12000, IsActive = true);
        insert customPrice;
        
    Order ord = new Order ();
    ord.AccountId =acc.Id;
        ord.PoNumber='PO67543';
        ord.PoDate = Date.newInstance(2016, 10, 5);
        ord.Status ='Draft';
        ord.EffectiveDate= system.today();
        ord.Pricebook2Id = customPB.Id;
    insert ord;
    
    OrderItem orditem = new OrderItem();
    orditem.OrderId = ord.Id;
        Orditem.Vehicle_Request_Status1__c ='PO Approved';
        orditem.PricebookEntryId =customPrice.Id;
        orditem.UnitPrice= 678;
        orditem.Quantity= 7;
    insert orditem;
        
      
    /*  list<OrderItem>status=new List<OrderItem>();
        list<integer>index=new List<integer>();
        status = [SELECT Product_name__c,Vehicle_Request_Status1__c FROM OrderItem WHERE OrderId =: ord.Id];
    for(integer i=0; i<status.size(); i++){
            index.add(i);
        } */
         PageReference testPage = Page.TrackOrder;
         Test.setCurrentPage(testPage);
         testPage.getParameters().put('Id', String.valueOf(ord.Id));
    Test.StartTest(); 
      ApexPages.StandardController sc = new ApexPages.StandardController(ord);
            TrackOrderController  testord = new TrackOrderController();
      testord.findOrder();
      testord.reset ();

    Test.StopTest();
        
  }
}
Hi Guys ,
I want to replace the Old Admin User with a newly created Admin User.
I don't have any idea where this user is being used or in what setings.
So I there any specific settings where I should look.
few of them I found.
Scheduled Jobs, Email Alerts, and Lead and Support setting default owner.
Any other settings?

Thanks,
Rahul
 
Controller:public class AppointmentsViewController {


    public List<Doctor__c> doctorList {get;set;}
    public List<SelectOption> doctorSelectOptionList{get;set;}
    public List<Appointment__c> apointmentList{get;set;}
    public String doctorId {get;set;}
    public List<Patient__c> patientList{get;set;}
    public List<SelectOption> patientSelectOptionList{get;set;}
    public Integer noOfRecords{get; set;}
    public Integer size{get;set;}
    
    public AppointmentsViewController() {
       doctorList = [
           SELECT Id, Name, Working_Hours_Start__c, Working_Hours_End__c
           FROM Doctor__c
           ORDER BY Name ASC
       ];
        
        patientList = [
            SELECT Id, Name
            FROM Patient__c
        ];
        
        patientSelectOptionList = new List<SelectOption>();
        
        for(Patient__c item :patientList)
        {
            patientSelectOptionList.add(new SelectOption(item.Id, item.Name));
        }
        doctorId = doctorList.isEmpty() == FALSE ? doctorList[0].Id : NULL;
        
       doctorSelectOptionList = new List<SelectOption>();
        
        for(Doctor__c item :doctorList) {
            doctorSelectOptionList.add(new SelectOption(item.Id, item.Name));
        }
        getAppointments();
       
        
    }
    
    public void getAppointments () {
        apointmentList = [
            SELECT Id, Name, Doctor__c, Patient__c, Appointment_Date__c, Duration_in_minutes__c
            FROM Appointment__c
            WHERE Doctor__r.Id = :doctorId
        ];
    }



    public List<Appointment__c> Appointment { get{

        return (List<Appointment__c>)setCon.getRecords();

    } set; }



    public ApexPages.StandardSetController setCon {

        get{

            if(setCon == null){

                size = 20;

                List<Appointment__c> Appointment = [
                    SELECT Id, Name, Doctor__c, Patient__c, Appointment_Date__c, Duration_in_minutes__c
                    FROM Appointment__c];

                setCon = new ApexPages.StandardSetController(Appointment);

                setCon.setPageSize(size);

                noOfRecords = setCon.getResultSize();

            }

            return setCon;

        }set;

    }






}




Test:
@isTest
private class AppointmentsViewControllerTest {
    
    @isTest static void AppointmentsViewControllerTest1() {
        
        Doctor__c doctor = new Doctor__c(
        );
        
        insert doctor;
        
        AppointmentsViewController controller = new AppointmentsViewController();
        
        Appointment__c Appointment = new Appointment__c(
        );
        insert Appointment;
        
            ApexPages.standardSetController sc = new ApexPages.standardSetController(doctor

        
        
     // ApexPages.StandardSetController standardSetController = new ApexPages.StandardSetController(doctor);
        
    }
    
       
    

}
Hi,
I have added opportunity as a lookup in contact. I want my description on contact to be updated with the related opportunity's stage name. My following code is not working. Please let me know where I went wrong:

trigger populateOppStage on Contact (before insert, before update) {
   Set<ID> opps = New Set<ID>();
    for (contact con:trigger.new){
        opps.add(con.opportunity__r.Id);
    }
    Map<Id, String> mapOppToStage = New Map<Id, String>();
    for(opportunity opp:[SELECT ID, stagename 
                      FROM opportunity WHERE ID IN:opps]){
        mapOppToStage.put(opp.id, opp.stagename);
    }

    for (contact c:trigger.new){
        if(mapOppToStage.containsKey(c.opportunity__r.Id)){
                c.Description= mapOppToStage.get(c.Opportunity__r.id);
        }
    }
}
Hello Guys,

I have to show the details from the contact object to the visualforce page with the help of record ID but unfortunately it is not showing me anything on the visual force page, kindly check the code and help me out.

VF Code:
<apex:page showHeader="false" standardcontroller ="Contact" extensions="MyContactController">
    <apex:form >
        <apex:pageBlock title="Tenant Details"> 
            <apex:pageBlockSection columns="2">
                <apex:outputField value="{! Contact.FirstName}" label="First Name"/>
                <apex:outputField value="{! Contact.LastName}" label="Last Name"/>
             </apex:pageBlockSection>
            <br/>
            <br/>
            
            <apex:pageBlockSection columns="3">
                    <apex:outputField label="Status" value="{! Contact.Approval_Status__c}"/>
                    
                    <apex:outputField label="Effective Date" value="{! Contact.RegistrationDate__c}"/>
                    
                    <apex:outputField label="Expiry Date" value="{! Contact.ExpiryDate__c}"/>
            </apex:pageBlockSection>
            
            <apex:outputText value=""/>
            <div align="center" >
                <apex:commandButton value="Renew" />
            </div>
            
            
            
        </apex:pageBlock>
    </apex:form>
    
</apex:page> 

Apex Class:
public class MyContactController{
public String currentRecordId {get;set;}
public list<Contact> lstcon = new list<Contact>();
 
    public MyContactController(ApexPages.StandardController controller) 
    {
        currentRecordId  = ApexPages.CurrentPage().getparameters().get('id');
        lstcon = [SELECT Id, FirstName, LastName, Approval_Status__c, RegistrationDate__c, ExpiryDate__c FROM Contact where id =: currentRecordId ];
        
    }
  
}
NOT(

     OR(
   
    Country  = 'US',
    Country  = 'USA',
    Country  = 'United State of America',
     ISBLANK(Country) 

     ) 

     )  
     
 AND(
     LEN(State)= 2,
     CONTAINS(State, "AB"},
     CONTAINS(State, "CD"},
     CONTAINS(State, "EF"}
)
I am hoping someone can help me :(

I have a test class that just keeps failing and I do now know what is wrong? When I run the test class, this is the error I get:
"System.AuraHandledException: Script-thrown exception" and the stack trace: Class.CaseFileFormServerController.insertCasesFile: line 56, column 1
Class.CaseFileFormServerControllerTest.insertCasesFileTest: line 55, column 1

Any help is GREATLY appreciated. Thank you!!!
@IsTest
public class CaseFileFormServerControllerTest {
	@TestSetup
    private static void setupTestData() {
        Case mockCase = new Case();
        insert MockCase;
        
        Case_File__c mockCaseFile = new Case_File__c(
        	Case__c = mockCase.Id,
        	Department__c = 'Logistics');
        insert mockCaseFile;
        
        ContentDocumentSelectorTest.createMockContentDocument();
    }
    
    private static testmethod void linkFileToCaseFile_success() {
        Id mockDocumentId = fetchContentDocumentId();
        Id mockCaseFileId = fetchMockCaseFileId();
        Id caseId = fetchCaseId();
        
        String result = CaseFileFormServerController.linkFileToCaseFile(mockDocumentId, mockCaseFileId);
        System.assertEquals('SUCCESS', result, 'An exception was caught: ' + result);
    }
    
    private static testmethod void linkFileToCaseFile_exceptionWasCaught() {
        Id mockAccountId = Id.valueOf('0014B00000WUh5tQAD');
        Id mockCaseFileId = fetchMockCaseFileId();
        Id caseId = fetchCaseId();
        
        String result = CaseFileFormServerController.linkFileToCaseFile(mockAccountId, mockCaseFileId);
        System.assert(result.contains('Exception:'), 'No exception was caught');
    }
    
   
    private static testmethod void insertCasesFileTest() {
        test.startTest();
        PricebookTestDataGenerator.generatePriceBookData();
        Id priceBookEntryId = [SELECT Id FROM PricebookEntry LIMIT 1].Id;
        Id product2Id = [SELECT Id FROM Product2].Id;
        Account account = new Account(Name = 'Test Account');
        INSERT account;
        Order__c order1 = new Order__c(AccountId__c = account.Id);
		INSERT order1;
        
        Order_Line__c orderLine1 = new Order_Line__c();
        orderLine1.Order__c = order1.Id;
        orderLine1.Quantity__c = 1;
        orderLine1.Salesperson__c = UserInfo.getUserId();
        orderLine1.Product2Id__c = product2Id;
        INSERT orderLine1;
        Id mockDocumentId = fetchContentDocumentId();
        Id mockCaseFileId = fetchMockCaseFileId();
        Id caseId = fetchCaseId();
        List<ContentDocument> mockDocument = [SELECT Id, Title FROM ContentDocument LIMIT 1];
        CaseFileFormServerController.insertCasesFile('Test',String.valueOf(caseId),'00022334','Driver',orderLine1.Id,'Product Damage','','Stone Cracked/Chipped','Test',mockDocument);
       	test.stopTest();
        // System.assertEquals('SUCCESS', result, 'An exception was caught: ' + result);
    }
    public static Id fetchContentDocumentId() {
        ContentDocument mockDocument = [SELECT Id, Title FROM ContentDocument LIMIT 1];
        System.assertNotEquals(null, mockDocument, 'Mock document came in as null');
        return mockDocument.Id;
    }
    
    public static Id fetchMockCaseFileId() {
        Case_File__c mockCaseFile = [SELECT Id, Case__c, Department__c FROM Case_File__c LIMIT 1];
        System.assertNotEquals(null, mockCaseFile, 'Mock case file came in as null');
        return mockCaseFile.Id;
    }
    
    public static Id fetchCaseId() {
        Case mockCase = [SELECT Id, CaseNumber FROM Case LIMIT 1];
        System.assertNotEquals(null, mockCase, 'Mock case came in as null');
        return mockCase.Id;
    }
}



 
public class ShowAllOpportunityAMountTOAccount {
    
    public static void getOpportunities(List<Opportunity> opportunityList){
        set<ID> setOFAccId=new set<ID>();
        for(Opportunity opp:opportunityList){
            setOFAccId.add(opp.AccountId);
        }
        Map<ID,Opportunity> mapOFOpp=new Map<Id,Opportunity>();
        List<Opportunity> opplist=[select id,Name,AccountId,Amount from Opportunity  where AccountID IN:setOFAccId ORDER BY Name DESC];
        for(Opportunity op:opplist){
            mapOFOpp.put(op.AccountId,op); 
        }
        //  system.debug(''+mapOFOpp[0].get(o.Amount););
        list<Opportunity> oplist=new List<Opportunity>();
        for(Opportunity o:opportunityList){
            Account acc=new Account();
            acc.Id=o.AccountId;
            acc.Opp1_Amount__c=mapOFOpp[0].get(o.Amount);
            acc.Opp2_Amount__c=mapOFOpp[1].get(o.Amount);
            acc.Opp3_Amount__c=mapOFOpp[2].get(o.Amount);
        }
    }
}

Error: Expression must be a list type: Map<Id,Opportunity>
Hii all,
i need to convert Lead(standard Object) to accounts, contacts and opportunity using visualforce page. Can anyone provide me the code please

Thanks in advance
Controller:
public class Traing_Trainingdeal_records_apex {
    public list<trainingWrapperclass> trdList{get;set;}
    public void getTrainings(){
        trdList = new list<trainingWrapperclass> ();
        for(Training_deal__c trd1:[SELECT Name,Deal_Risk_Status__c from Training_deal__c limit 5]){
                trdList.add(new trainingWrapperclass(trd1));
            } 
    }
    public class trainingWrapperclass{
        public Training_deal__c trd1{get;set;}
        public trainingWrapperclass(Training_deal__c trd1){
            this.trd1=trd1;            
        }
    }
}

VF page:
<apex:page controller="Traing_Trainingdeal_records_apex" showHeader="true">
    <apex:form >
        <apex:pageBlock title="Traning deal details">
            <apex:pageBlockSection title="Traing deal records" showHeader="true">
                <apex:pageBlockTable value="{!trdList}" var="trd" title="All Training deal records">
                    <apex:column value="{!trd.trd1.Name}" />
                </apex:pageBlockTable>
            </apex:pageBlockSection>
        </apex:pageBlock>
    </apex:form>
</apex:page>
Hi, I have a requirement :  I have account and a custom object (Account Plan) with field Active which is a checkbox . Now i have to write a validation rule to make sure there should be only one active field checked in for one account.Note:they are in master detail relation
Hi! 

I am trying to do a workflow field update VIA formula. The premise is when the task "status" field is changed I want to track the date and time of when it was changed and what user changed it. I am running into issues getting the user part into the formula and the error messages when trying to save my formula:

Error Message: Error: Field Status is a picklist field. Picklist fields are only supported in certain

Formula:

Date_Time_Status_Change__c  &
IF(NOT ISBLANK(Date_Time_Status_Change__c ), BR(), '') & 
TEXT(NOW()) + ' - ' +  Status

Any input would be great thank you!
im trying to do the test class for this code

public class Claseprogramadausuario {
    
public static void obtenerinfo(){

List<User> nlist = [SELECT Id, Username, FirstName, LastName, EmployeeNumber, UserRole.Name, Profile.Name, CreatedDate, LastModifiedDate, LastLoginDate, isActive FROM User WHERE Profile.Name != 'SelfService'];
string header = 'Id, Username , FirstName, LastName, EmployeeNumber, UserRole.Name,  Profile.Name, Created Date, LastModifiedDate, LastLoginDate, isActive \n';
string finalstr = header ;
for(User u: nlist)
{

       string recordString = u.id+','+u.Username +',' + u.FirstName +','+ u.LastName +','+ u.EmployeeNumber+','+ u.UserRole.name +','+ u.profile.name +','+ u.CreatedDate +','+ u.LastModifiedDate +','+ u.LastLoginDate +','+ u.IsActive +'\n';

       finalstr = finalstr +recordString;
}

Messaging.EmailFileAttachment csvAttc = new Messaging.EmailFileAttachment();
blob csvBlob = Blob.valueOf(finalstr);
string csvname= 'Userinfo.csv';
csvAttc.setFileName(csvname);
csvAttc.setBody(csvBlob);
Messaging.SingleEmailMessage correo = new Messaging.SingleEmailMessage();
correo.toAddresses = new String[] {'javierandoni@gmail.com', 'dlramirez@izzi.mx'};
correo.subject = 'Clase programada test';
correo.plainTextBody = 'Clase programada test';
Messaging.SingleEmailMessage[] correos =   new List<Messaging.SingleEmailMessage> {correo};
correo.setPlainTextBody('Account CSV ');
correo.setFileAttachments(new Messaging.EmailFileAttachment[]{csvAttc});
Messaging.SendEmailResult[] results = Messaging.sendEmail(correos);

if (results[0].success) 
{
System.debug('The email was sent successfully.');
} else 
{
System.debug('The email failed to send: ' + results[0].errors[0].message);
}
}
}

And the test class im trying to do is this

// Test Class
@IsTest
Public class ClaseprogramadausuarioTest {
    @isTest static void testenviomail(){
        string pri= Claseprogramadausuario.obtenerinfo();
        System.assertEquals('The email was sent successfully.', pri);
    }
}

but i get this message: Illegal assignment from void to String.
 
Hello All,
I have written a Trigger on OrderItems (before Insert) and now writing a test class for the same. 
I am getting an error as:
System.DmlException: Insert failed. First exception on row 0; first error: FIELD_INTEGRITY_EXCEPTION, Pricebook Not Set on Order: []

My Trigger:
trigger UnitPrice on OrderItem (before insert) {

    for (OrderItem orderItem: Trigger.new) {
    if(orderItem.UnitPrice == NULL){
            orderItem.UnitPrice= 0; // Dummy Value
            }
    }

}

Test Class:
@isTest(SeeAllData=true)
public class testUnitPrice {
    
    public static testMethod void testorderproduct(){

    // Insert Account

    Account a = new Account();
    a.Name = 'Test Account';
    insert a;

    // Insert Product
    Product2 p = new Product2();
    p.Name = ' Test Product ';
    p.Description='Test Product Entry 1';
    p.productCode = 'ABC';
    p.isActive = true;
    insert p;
    

    Pricebook2  standardPb = [select id, name, isActive from Pricebook2 where IsStandard = true limit 1];
    
    // Insert PricebookEntry

    PricebookEntry standardPrice = new PricebookEntry();
    standardPrice.Pricebook2Id = standardPb.Id;
    standardPrice.Product2Id = p.Id;
    standardPrice.UnitPrice = 1;
    standardPrice.IsActive = true;
    standardPrice.UseStandardPrice = false;
    insert standardPrice ;
    
    // Insert Order
    
    Order o = new Order();
    o.Name = 'Test Order ';
    o.Status = 'Draft';
    o.EffectiveDate = system.today();
    o.EndDate = system.today() + 4;
    o.AccountId = a.id;
    o.Pricebook2Id =  standardPb.Id ;
    insert o;
    
    // Insert Order Item

    OrderItem i = new OrderItem();
    i.OrderId = o.id;
    i.Quantity = 5;
    i.UnitPrice = 0;
    i.Product2id = p.id;
    i.PricebookEntryId=standardPrice.Id;
    insert i;

	}
}

I am very new to programming. Any help would be appreciated.

Thank you!
Maitreyee Dingare​​​​​​​​​​​​​​

I'm doing a REST API call to get the global value set and trying to deserialize the JSON result to get the picklist values in a List<String>.

Here is the JSON:

{
  "size": 1,
  "totalSize": 1,
  "done": true,
  "queryLocator": null,
  "entityTypeName": "GlobalValueSet",
  "records": [
    {
      "attributes": {
        "type": "GlobalValueSet",
        "url": "/services/data/v53.0/tooling/sobjects/GlobalValueSet/0Nt59000000AAAAAAA"
      },
      "Metadata": {
        "customValue": [
          {
            "color": null,
            "default": false,
            "description": null,
            "isActive": null,
            "label": "USA",
            "urls": null,
            "valueName": "USA"
          },
          {
            "color": null,
            "default": false,
            "description": null,
            "isActive": null,
            "label": "Canada",
            "urls": null,
            "valueName": "Canada"
          }
        ],
        "description": null,
        "masterLabel": "US States & Territories",
        "sorted": false,
        "urls": null
      },
      "Id": "0Nt59000000AAAAAAA"
    }
  ]
}
I need help in fixing the error and also how to get valueNames in a List<String>

Error: System.JSONException: Malformed JSON: Expected '{' at the beginning of an object.

Here is what I have tried so far:

Wrapper:
    public class GlobalValueSetWrapper{
        Metadata metadata;

    public class Metadata {
        public List<CustomValue> customValue;
    }
    
    public class CustomValue {
        public String label;  
        public String valueName;
    }
    }


Class:
//calling API to get the JSON result
HttpResponse res = GlobalValueSetAPIHandler.getResponse('Countries');
GlobalValueSetWrapper wrapper = (GlobalValueSetWrapper) JSON.deserialize(res.getBody(), GlobalValueSetWrapper.class);
  • September 22, 2021
  • Like
  • 1
Hi, I have created a class for processing opportunity object based on the custom object "staging__c". But the issue is I'm executing SOQL inside for loop which is a bad practice. Can anyone help me to avoid it?
Here is my code for the same please have a look.
Note: My code is working. The only issue is soql which I am executing in the loop. I have commented on the issues in my code for better understanding.
global class BatchAssignment implements Database.Batchable<sObject>{
    global Database.QueryLocator start(Database.BatchableContext BC){     
        return Database.getQueryLocator([SELECT Id, Individual_or_organization__c ,Orgganization_Name__c,First_Name__c,Last_Name__c,Postal_Code__c,Date_Recieved__c,Amount__c,Error_Message__c,Description__c 
                                         FROM staging__c]);
    }    
    
  global void execute(Database.BatchableContext BC, List<staging__c> scope){
        List<Opportunity> newOpptyList = new List<Opportunity>();
   
      for(staging__c sc:scope){
          system.debug('in for loop');
        if(sc != null && sc.Individual_or_organization__c  == 'I') {
            system.debug('in if == I');
            // calling custom method that executes soql inside loop and storing output here
            Account objAccount = searchAccount(sc);
            if(objAccount != null) {
                 // calling custom method that executes soql inside loop and storing output here
                List<Contact> linkContactList = searchContact(objAccount, sc);
                system.debug('contact'+linkContactList);
                try{
                    if(linkContactList != null && !linkContactList.isEmpty()) {
                        upsert linkContactList;
                        system.debug('creating opp');
                        //Create new opportunity;
                        for(Contact objCon : linkContactList) {
                            newOpptyList.add(new Opportunity(Name = objCon.LastName,
                                                             StageName = 'Prospecting',
                                                             AccountId = objAccount.Id,
                                                             ContactId = objCon.Id,
                                                             CLOSEDATE=Date.today()
                                                            ));                       
                            
                        }
                        
                        if(newOpptyList != null && !newOpptyList.isEmpty()) {
                            system.debug('insert opp');
                            insert newOpptyList;
                        }
                    }
                }catch(Exception ex) {
                    system.debug('---Exception--' + ex);
                }
                
            }
        }
      }
    }
    // this method is getting called inside the loop of execute method which is bad
    private Account searchAccount(staging__c scope) {
        Account acc= new Account();
        if(scope.Orgganization_Name__c != null && scope.Postal_Code__c != null) {
            system.debug('acc not zero');
            acc= [SELECT Id, Name FROM Account WHERE Name = :scope.Orgganization_Name__c AND BillingPostalCode = :scope.Postal_Code__c];
        }
        return acc;
    }
    
    // this method is getting called inside the loop of execute method which is bad
    private List<Contact> searchContact(Account objAccount, staging__c scope) {
        List<Contact> linkContactList = new List<Contact>();
        if(scope.First_Name__c != null && scope.Last_Name__c != null && scope.Postal_Code__c != null) {
            List<Contact> existingContactList = [SELECT Id, FirstName, LastName, MailingPostalCode FROM Contact 
                                                 WHERE FirstName = :scope.First_Name__c AND LastName = :scope.Last_Name__c AND MailingPostalCode = :scope.Postal_Code__c];
            //For existing contacts
            system.debug('existing contact'+existingContactList);
            if(existingContactList.size()>0 ) {
                for(Contact objCon : existingContactList) {
                    objCon.AccountId = objAccount.Id;
                    linkContactList.add(objCon);
                }
            } else {
                //create new contact
                system.debug('into else');
                linkContactList.add(new Contact(FirstName = scope.First_Name__c, 
                                                LastName = scope.Last_Name__c,
                                                MailingPostalCode = scope.Postal_Code__c,
                                                AccountId = objAccount.Id));
                system.debug('linked contact2'+linkContactList);
            }
            
        }
        return linkContactList;
    }
    
    global void finish(Database.BatchableContext BC){   
        system.debug('finished:::');
    }
}


 
I want to know how to parse the URL params from a get request
/services/apexrest/Endpoint/?subject=test&status=active&priority=1&origin=?subject=test&status=active&priority=1
I want to parse the url params in the class below
@HttpGet
    global static void getStatus() {
        RestRequest request = RestContext.request;
        System.debug(request.requestURI); 
        
    }

Please help!
Hello everyone,
 
I want to get all the current user's notifications to display them in a LWC component. For this, I tried to make a REST API callout from Salesforce to the same Salesforce org using Connect REST API Resources (/connect/notifications — documentation: https://developer.salesforce.com/docs/atlas.en-us.chatterapi.meta/chatterapi/connect_resources_notifications_resources.htm)
I tried to make the callout using first Workbench, then an apex class, but I always get the same result, an empty list of notifications. The current user has both custom and standard notifications, so I don't understand why I always get an empty list.
 
Does anyone have any idea why I receive an empty list of notifications?
User-added imageUser-added image
I want only one value from the json but i'm getting all the values how can i stop iteration or is there any way to show only one row like keeping size please help to find the solution

Thank you in Advance,

<tbody>
                        <aura:iteration items="{!v.jsonValues}" var="item" indexVar="rowIndex">  
                            <tr data-data="{!rowIndex}">
                                <td role="gridcell" tabindex="-1" data-label="Record Type Name">                            
                                    <span class="slds-grid slds-grid_align-spread">
                                        <div class="slds-truncate">                                        
                                            <span class="slds-truncate">{!item.firstName}</span>
                                        </div>
                                    </span>                            
                                </td>
                            </tr>
                        </aura:iteration>
                    </tbody>

Original Output:-
      Ramesh
      Suresh
      Rakesh

Expected Output:-
    Ramesh
  • August 25, 2021
  • Like
  • 1
The AccountTeamMember widget (Lightning Component) displays the Role API Name instead of the Role Label.

How do i change the lightning component so it will display the role label instead of the role API name?

Here is the component code:
<aura:component implements="flexipage:availableForRecordHome,force:hasRecordId" access="global" controller="AccountTeamHelper">
    <aura:handler name="init" value="{!this}" action="{!c.doInit}" />
    <aura:attribute name="TeamMembers" type="AccountTeamMember[]" /> 	  
    <lightning:card title="Account Team" iconName="custom:custom103">
        <div style="margin: 0px 5px">
            <p class="slds-p-horizontal_small">
                <aura:if isTrue="{!v.TeamMembers.length > 0}">
                <aura:iteration items="{!v.TeamMembers}" var="member">
                    <!-- <span style="display: inline-block; margin: 3px;"><lightning:avatar src="{!member.User.SmallPhotoUrl}" alternativeText="(Avatar)" fallbackIconName="standard:avatar" variant="circle" /></span> -->
                    <span><a href="{!'/one/one.app#/sObject/' + member.User.Id + '/view'}">{!member.User.FirstName}&nbsp;{!member.User.LastName}</a> - {!member.TeamMemberRole}</span><br/>
                </aura:iteration>
                <aura:set attribute="else">
                    No account team members have been assigned to this account.
                </aura:set>
                </aura:if>
        	</p>
        </div>
    </lightning:card>
</aura:component>

 
public class Api4 {
   public static void api(){
    Http h = new Http();
HttpRequest req = new HttpRequest();
req.setMethod('GET');
req.setEndpoint('https://demo1691926.mockable.io/Api12');
req.setHeader('Content-Type', 'application/json');
HttpResponse response = h.send(req);
system.debug('response  : '+response.getBody());
String json1= response.getBody();

       
DesearlizingJson desearilize1=(DesearlizingJson) Json.deserialize(json1,DesearlizingJson.Class);
System.debug('Phone is ' +desearilize1.phone);
System.debug('name is ' +desearilize1.Name);
System.debug('mobile is ' +desearilize1.MobilePhone);
      
 //trying to update deserialized json       
list<contact> lcon= new list<contact>();

List<contact> lcon1 = [select id,Name,MobilePhone,Phone from contact where LastName=:desearilize1.Name];
       for(contact c1:lcon1){
        
        c1.Phone=desearilize1.phone;
           lcon.add(c1);}
        update c1;
       
  }
}

Wrapper class

public class DesearlizingJson {
    public Decimal Phone;
    public String Name;
    public Decimal MobilePhone;

}

Thanks in Advance
if(requestId != null) {
        
               List<GLOBAL_Request__c> requestObj = [select id, business_unit__c, recordtype.developername from GLOBAL_Request__c where id=:requestId AND recordtype.developername = 'Send_Survey' Limit 1];
            if (requestObj != null){        
            List<User> usrRec =[select id, NT_Login_Name__c from User where id=:UserInfo.getUserId() And NT_Login_Name__c != null Limit 1];
                    if(usrRec != null){
                    List<Contact> contactRec = [select id, contactRec.NT_Login_Name__c from contact where NT_Login_Name__c=:usrRec.NT_Login_Name__c ORDER by LastModifiedDate DESC Limit 1];         
                        if (contactRec != null){
                          List<Participant__c> participantRec = [select Id, Name,Survey_Taken_Date__c from Participant__c where Participant__c=:contactRec.Id AND Request__c=:requestObj.Id ORDER by CreatedDate DESC LIMIT 1];
                            if(participantRec != null && participantRec.Survey_Taken_Date__c == null){
                                ParticipantId = participantRec.Id;
                                contactId = contactRec.Id;
                                requestId = requestObj.Id;
                                Participant__c updateSurveyTakenDate = new Participant__c(id = ParticipantId, Survey_Taken_Date__c = System.now());            
                                       upsert updateSurveyTakenDate;  
                            } else if(participantRec != null && participantRec.Survey_Taken_Date__c != null){
                                Apexpages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, System.Label.LABS_SF_You_have_already_taken_this_survey));
                                return false;
                            } else {
                                Apexpages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, System.Label.LABS_SF_Participant_Not_Part_Of_This_Pool));                    
                                 return false;
                            }
                        }
                    }
            }
        }
  
And I am getting the following error.


1.Variable does not exist: NT_Login_Name__c
2.Variable does not exist: Id
3.Variable does not exist: Survey_Taken_Date__c
4.Variable does not exist: Id
5.Variable does not exist: Survey_Taken_Date__c

Will appreciate your help.

Thanks,
TM
      
Hello- I'm writing a scheduled Apex class that grabs all Accounts that are listed as 'Active' in a custom field, find's the most recent closed won Opportunity and passes a value from a lookup field on that opp back to another lookup on the Account. The class isn't flagging any problems for me, but throws an error when it tries to run upon being scheduled.

The error seems to indicate that it couldn't find any records to update. I verified that there are records that meet the criteria, and when I run the SOQL query in isolation it finds those records. When I try to debug it in the Execute Annonymous window, it also doesn't return any system.debug messages. I appreciate any help figuring out where I'm going wrong! 
The error:
Sandbox

Apex script unhandled exception by user/organization: 0053i000002hKdg/00D1g0000002qa7
Source organization: 00D3i000000ttF8 (null)
Scheduled job 'Se Update2' threw unhandled exception.

caused by: System.QueryException: List has no rows for assignment to SObject

Class.UpdateSEOnAccount.execute: line 8, column 1
The Apex Class:
global class UpdateSEOnAccount implements Schedulable{
    global void execute (SchedulableContext ctx){
        UpdateSE();
    }
    public void UpdateSE(){
        List<Account> Actlst = new list<account>();
        for(Account a : [SELECT Id FROM Account WHERE Customer_Status__c = 'Active']){    
             a.Sales_Engineer__c = [SELECT Id, SE__c, AccountId 
                          FROM Opportunity 
                          WHERE AccountId = : a.id AND StageName = 'Closed Won'
                          ORDER BY CloseDate DESC LIMIT 1].SE__c;
           system.debug('a is '+ a.Id);
           if(a.SE__c <> NULL){
           Actlst.add(a);
           }
            system.debug('size of list is '+ Actlst.size());
        }
        if(Actlst.size()>0){
            update Actlst;
        }
    }
}


 
Unexpectedly werid behavior, I deleted an opportunity on frontend and queried for the deleted opportunity id, the record row was completed deleted from the opportunity table. When I restored the record from Recycle Bin, the row was back. I was expecting instead of record row completely disappearing from the table, the IsDeleted field would be updated. 

 
Hi everyone, can someonehelp how to write testclass for the below class

@RestResource(urlmapping='/v1/Accountmanager/')
global class Integration_Example {
@HttpGet
    //which is used to get the records or query the records
    global static Account doget(){
        //intilaise the object
       Account a=new Account();
        //get the req parameters in map
        map<string,string> paramsmap=Restcontext.request.params;
        //get the id
        string accid=paramsmap.get('Id');
        //query the records
        a=[select id ,name from Account where id=:accid];
        return a;
    }
    @HttpDelete
    global static Account doDelete(){
       RestRequest req = RestContext.request;
        RestResponse res = RestContext.response;
        String AccNumber = req.requestURI.substring(req.requestURI.lastIndexOf('/')+1);
        Account result = [SELECT Id, Name, Phone, Website FROM Account WHERE AccountNumber = :AccNumber ];
        delete result;
        return result;
    }
   @Httppost
    //post method is used to create the record
    global static Account docreate(string name){
        Account a = new Account(name=name);
        insert a;
        return a;
    }
     @Httpput
    global static Account doupdate(string name){
        map<string,string> paramsmap=Restcontext.request.params;
        //get the id
        string accid=paramsmap.get('Id'); 
        Account a = new Account(name=name, id=accid);
        update a;
        return a;
    }
}

Thanks in Advance
Hi,

Dear folks,

Here is what i want to do and thankfully was able to get answer using thread below with List
https://developer.salesforce.com/forums/ForumsMain?id=9062I000000BjjoQAC
,but now i am rewriting the same code using Map,but am getting error as 
 
Method does not exist or incorrect signature: void get(String) from the type Map
Here is what the end goal is 
 
For example, if s = "zbax" and k = 2, then the resulting integer would be 8 by the following operations:

Convert: "zbax" ➝ "(26)(2)(1)(24)" ➝ "262124" ➝ 262124
Transform #1: 262124 ➝ 2 + 6 + 2 + 1 + 2 + 4 ➝ 17
Transform #2: 17 ➝ 1 + 7 ➝ 8

Here is code with Map
public class SDASMapConvert {
    

    
    
public static Integer returnInteger(String z, integer k){
        Integer retInt;
        String key = 'abcdefghijklmnopqrstuvwxyz';

        List<String>myAlphabets = z.split('');
        Map<String, String> myMap = new Map<String, String>();
        String strarr = '';

       for (integer i = 0; i < myAlphabets.size(); i += 2) {
        myMap.put(myAlphabets[i], myAlphabets[i + 1]);
    }

    for (String s : myMap.keySet()) {
        System.debug(s + ' is ' + map.get(s));
        strarr += string.valueOf(s);
    }
        
        system.debug('strarr --> ' + strarr);
        String s = '';
        for(integer i = 0; i < k ; i++){
            system.debug(' strarr --> ' + strarr);
            Integer total = 0;
            for(String s1 : strarr.split('')){
                total += integer.valueOf(s1);
            }
            system.debug(' total --> ' + total);
            strarr = string.valueOf(total);
        }
        
        system.debug(' ************* ' + strarr);
        if(!string.isEmpty(strarr))
            retInt = integer.valueOf(strarr);
        
        system.debug(' ************* ' + retInt);
        
        return retInt;
    }
    


}

Regards
Fiona
Dear folks,

Here is what i want to do
 
For example, if s = "zbax" and k = 2, then the resulting integer would be 8 by the following operations:

Convert: "zbax" ➝ "(26)(2)(1)(24)" ➝ "262124" ➝ 262124
Transform #1: 262124 ➝ 2 + 6 + 2 + 1 + 2 + 4 ➝ 17
Transform #2: 17 ➝ 1 + 7 ➝ 8



Hence ,Wrote a apex class for To  convert string into an integer by replacing each letter with its position in the alphabet,but it doesnt seems working,error i get on Anonymus Console Window for below command
is 
Line: 14, Column: 1
System.TypeException: Invalid integer: a
Here is anonymous code
SDSAfterConvert.returnInteger();

Here is apex code
 
public class SDSAfterConvert {
    
    
public static List<Integer> returnInteger(){


List<Integer> inputList = new List<Integer>();
             
String[] myAlphabets = new String[]{'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'g'};
 
for (String s1 : myAlphabets) {
   
    System.debug(s1);
    Integer d = integer.ValueOf(s1);
    inputList.add(d);
}
        
return inputList;
             
}
    
}



Regards,
Fiona​​​​​​​
 
I'm using a Lightning Component to update a field called "Observations__c" in Account Object.
User-added image

It's working fine, but when I try to use it inside another component, I receive the following error:

EXCEPTION_THROWN [9]|System.NullPointerException: Attempted to upsert a null list

Component: 

<aura:component implements="force:lightningQuickActionWithoutHeader,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes" access="global" controller="getAccount">

<aura:handler name="init" action="{!c.init}" value="{!this}" />
<aura:attribute name="accounts" type="Account" />
<aura:attribute name="recordId" type="Id" />

<ltng:require styles="/resource/slds103/assets/styles/salesforce-lightning-design-system.min.css"/>

 <form>
    <ui:inputText aura:id="client"
                  label="{!$ObjectType.Account.fields.Observations__c.Label}"
                  class="form-control"
                  value="{!v.accounts.Observations__c}"
                  placeholder="Insira, caso necessário, comentários adicionais"
    />
    <br />
    <ui:button class="form-control" aura:id="button" label="Anexar observação" press="{!c.save}"/>
</form>

 </aura:component>

Controller js:
({
init : function(component, event, helper) {
    var accId = component.get("v.recordId");
    var action = component.get("c.getAcct");

    action.setParams({
        "accountId": component.get("v.recordId")
    });

    action.setCallback(this, function(data) {
        component.set("v.accounts", data.getReturnValue());
    });

    $A.enqueueAction(action);
}, 
save : function(component, event, helper) {

    var action = component.get("c.saveAcct");
    var accounts = component.get("v.accounts");

    action.setParams({"act": accounts});
    $A.enqueueAction(action);

    console.log('save ran');

}
})

Apex Controller:
public class getAccount {
    @AuraEnabled 
    public static Account getAcct(Id accountId){
        return (Account) Database.query( ' SELECT Name, Observations__c FROM Account WHERE Id =: accountId LIMIT 1 ' )[0];
    }

    @AuraEnabled 
    public static Account saveAcct(Account act){
        upsert act;
        return act;
    }  
}

I'm calling <c:sparkAccount/> in my second component, but it is not working.
User-added image

What am I doing wrong? 
Need help with test class for the below trigger
 
trigger updateCampaignTypeonLead on CampaignMember (after insert) {
 set<Id> leadIds = new set<Id>();
              
        list<Lead> leadList = new list<Lead>();
        set<Id> campIds = new set<Id>();
        
        map<Id, CampaignMember> leadCampaign = new map<Id, CampaignMember>();  
    
        for (CampaignMember camMember : System.Trigger.New)
        {
            leadIds.add(camMember.LeadId);
            
            campIds.add(camMember.CampaignId);
            
            leadCampaign.put(camMember.LeadId, camMember);
        
        }

 map<Id,Campaign> campmap = new map <Id,Campaign>([select Id, Type from Campaign where id in: campIds]);
 
 for(Lead thisLead : [Select Id, Campaign_Type__c from Lead where Id in : leadIds and isConverted=false])
        {
          
          Campaign camp = campmap.get(leadCampaign.get(thisLead.Id).CampaignId);    

            thisLead.Campaign_Type__c = camp.Type;
            Update thisLead;
            
                       }

}

 
Hello,

I have created a custom field (checkbox) under the opportunity object. I would like to prevent any files from being uploaded to the opportunity if the box is checked. I am having trouble creating the apex trigger. 
Send an email using triggers to contacts related to the accounts when account is updated. If 2 contacts has same email than send only 1 mail to that contacts having similar emails. In the email body mention the name of contacts having similar emails in a tabular format. For example if the Account A1 has 5 contacts c1, c2, c3, c4, c5 and c1, c2, c3 has similar emails and other having unique email than the names of the contact should be show in the table in the email body of the contacts having similar emails.
Hi everyone,can someone help how to write testclass for the below code..
Thanks in Advance.

public class Displayrelatedlists {
    //1.list of wrapperclass
     public list<AccountContactWrapper> lstAccountContactWrapper { get; set; }
    public list<AccountContactWrapper> lstSelectedAccountContactWrapper { get; set; }
    //list for selecting the account records
    public list<account> selectedAccounts{get;set;} 

    public Displayrelatedlists () {
        //Allocating the memory for the list
        lstSelectedAccountContactWrapper = new list<AccountContactWrapper>();
        if(lstAccountContactWrapper == null) {
            //allocate memory for the wrapperlist
            lstAccountContactWrapper = new list<AccountContactWrapper>();
            for(account a:[select id,name,phone,(select id,name from contacts)from account limit 10]) {
                lstAccountContactWrapper.add(new AccountContactWrapper(a));
            }
        }
    }
 
    public void ProcessSelected() {
        lstSelectedAccountContactWrapper =new list<AccountContactWrapper>();
        selectedAccounts =new list<Account>();
        for(AccountContactWrapper wrapobj:lstAccountContactWrapper){
            if(wrapobj.isSelected==true) {
                selectedAccounts.add(wrapobj.acc);
            } 
        }
       
        for(Account acc:[select id,name,phone,(select id,name from contacts) from account where id in:selectedAccounts]) {
            lstSelectedAccountContactWrapper.add(new AccountContactWrapper(acc)); 
        }
             
    }
    public class AccountContactWrapper {
 
        public Account acc {get;set;}
        public boolean isSelected {get;set;}
   
        public AccountContactWrapper(account a) {
            acc = a;
            isselected=false;
        }
    }
}
Hello! 
There is code (that I did not originally write) that I have been digging through to try to find out how to make a field required. What this code is doing: On a case, the user can select an option to "Tag Images". This will take them to a component and they can fill out specified fields. After the select "Submit", this will create a Case File record and it will be linked to the case. On the component screen, there are about 6 fields. Two of them need to be required to move forward. One is currently required and I will provide screenshots below.
They select a photo to tag:
User-added image
They then get taken to a screen to fill out information about the image(s). Primary Reason (Return_Reason__c) and Secondary Reason (Return_Reason_Secondary__c) need to be required just like Order Line (Order_Line__c) is. I was able to add the asterisks in the code but I cannot get it to error on null. Here is the screen:
User-added image
When you leave Order Line blank, here is the error:
User-added imageI need this to happen when Primary Reason and Secondary Reason are left blank as well. After looking through all of the code, I found the component screen and added the highlighted text to show the asterisks on the two fields:
User-added imageThe only other thing I could find was in the Helper, I believe this is where the error message comes from for the Null Order Line:
} else if(state === "ERROR"){
                var errors = action.getError();
                if (errors) {
                    if (errors[0] && errors[0].message) {
                        //alert(errors[0].message);
                        var toastEvent = $A.get("e.force:showToast");
                        toastEvent.setParams({
                            title : 'Error',
                            message:'There is an error '+errors[0].message+'',
                            mode: 'sticky',
                            key: 'info_alt',
                            type: 'error'
                        });
                        toastEvent.fire();

But what I cannot find is the middle piece here. Where would it state in the code that IF Order Line is null - Display this error? Full Component in comments.
Thank you very much!!!!


 
Hi All,
I am getting Null Pointer Exception: Attempting to de-reference a null object at this line only-----> DealsMap.put(deal.id,deal)

Screenshot of the Null Pointer Exception

User-added image

It's not displaying any values in tabular format from Map Collection in my VF Page also.
How do I fix this issue?Please help me!

Apex Class:

public with sharing class searchname1 {

    public PageReference edit() {
       
        return null;
    }

   public String name { get; set; }
    public list<Training_Deal__c> lstdeal { get; set; }
    public list<Course_Master__c> lstcourse { get; set; }
    public Map<id, Training_Deal__c> DealsMap { get; set; }
   
    
    public boolean searched{get;set;}
    
    //default constructor
    public searchname1(){
    searched=false;
    string namestr=apexpages.currentpage().getparameters().get('name');
    if(null!=namestr){
    name=namestr;
    }
               
    }
    public PageReference search() {
    searched=true;
     string searchstr1=('%'+name+'%');
         
           
        System.debug('-----------before for loop');
        try{
        for ( Course_Master__c crs : [select ID,Name,Course_Name__c,
                                      (select ID,Name,Course__c,Fees_Finalized__c from Training_Deals__r) from Course_Master__c 
            where Course_Name__c LIKE :searchstr1] ) {
                            for ( Training_Deal__c deal : crs.Training_Deals__r ) {
                                  System.debug(deal.Course__c + ' - ' + deal.Name + ' - ' + deal.Fees_Finalized__c );
                                 DealsMap.put(deal.id,deal);
                                 System.debug('Map of Deals-----'+DealsMap);  
                                }
                 
                            }
             System.debug('----------After for loop');   
        }catch(Exception e){
            System.debug('Exception occured'+e);
        }                    
          
              return null;
    }


    
}
VF Page:
<apex:page controller="searchname1" >
  <apex:form >
   <apex:pageblock id="one" >
    <apex:pageblockSection >
    <apex:pageblocksectionitem >
       <apex:outputlabel >Course to Search</apex:outputlabel>
         <apex:inputtext value="{!name}"/>
         </apex:pageblocksectionitem>
         <apex:commandButton value="Search" action="{!search}"/>
          </apex:pageblockSection>
      </apex:pageblock>       
           <apex:pageBlock id="SearchResults" rendered="{!searched}" >
               
           <!-- <apex:pageblocktable value="{!lstcourse}" var="c">
            <apex:column value="{!c.Name}"/>
                
             <apex:column value="{!c.Course_Name__c}"/>
            
               </apex:pageblocktable>
<apex:pageblocktable value="{!DealsMap}" var="d">
           
             <apex:column value="{!d.Name}"/>  
             <apex:column value="{!d.Course__c}"/>
             <apex:column value="{!d.Fees_Finalized__c}"/>     
            </apex:pageblocktable>
--> 
               

    <apex:pageBlock >
        <apex:repeat value="{!DealsMap}" var="d">
       {!d}<br/><br/>
         <apex:repeat value="{!DealsMap[d]}" var="d1">
        {!d1.name} <br/><br/>
         </apex:repeat>

    </apex:repeat>

               </apex:pageBlock>
        
   
     <apex:pageblockbuttons >
             <apex:commandButton value="edit" action="{!edit}"/>
            </apex:pageblockbuttons>
      </apex:pageBlock>
  </apex:form>
</apex:page>

 
  • July 13, 2021
  • Like
  • 1