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


  • Chatter
    Feed
  • 436
    Best Answers
  • 3
    Likes Received
  • 27
    Likes Given
  • 16
    Questions
  • 1482
    Replies
I want to write a trigger on Contact , when a contact insert an email should be sent to contact email id.

I have written the below code and when I try to create a new contact, contact is not receiving an email. Can anyone help me.

trigger conss on Contact (before insert) {
    set<id> conlist = new set<id>();
    for(contact cons : trigger.new){
       conlist.add(cons.id);
    }
    public static void emailsent(){
        list<Messaging.SingleEmailMessage> maillist = new list<Messaging.SingleEmailMessage>();
        EmailTemplate et = [select id,
                             subject,
                             body from EmailTemplate where DeveloperName = 'contact_test' ];
        contact cont = [select id,email from contact where id in : conlist];
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage ();
        mail.setTemplateId(et.id);
        mail.setTargetObjectId(cont.Id);
        maillist.add(mail);
        
        if(!maillist.isEmpty()){
            Messaging.sendEmail(maillist);
        }
    }
   
}

this is my code i want to give count of contacts associate with account but when i changed contacts account(lookup) it update new owner count value but not updating the value in old account count

this is my code
handler:
public class ContactRollupSummaryHandler {
    public static void afterInsert(list<Contact> contacts){
        NumberofContacts(contacts);
    }
    public static void afterUpdate(list<Contact> contacts,Map<Id,Contact> oldMap){
        list<Contact> conlist = new list<Contact>();
        for(Contact c: contacts){
            if(c.AccountId != oldMap.get(c.Id).AccountId){
                conlist.add(c);
            }
        }
        if(conlist.size()>0){
            NumberofContacts(conlist);
        }
    }
    public static void afterDelete(list<Contact> contacts){
        NumberofContacts(contacts);
    }
    public static void afterUndelete(list<Contact> contacts){
        NumberofContacts(contacts);
    }
    
    
    public static void NumberofContacts(list<Contact> con){
        set<id> accIds = new set<id>();
        for(Contact c: con){
            if(c.AccountId != null){
            accIds.add(c.AccountId);
            } 
        }
        
        if(accIds.size()>0){
            list<Account> acclist = new list<Account>();
        for(Account ac: [SELECT id,Number_of_Contacts__c,(SELECT id from Contacts) from Account where id IN:accIds]){
            ac.Number_of_Contacts__c = ac.Contacts.size();
            acclist.add(ac);
        }
            if(acclist.size()>0){
                update acclist;
            }    
        
        }
    }

}

Trigger:
trigger ContactTrigger on Contact (after insert,after update,after delete, after undelete) {
    if(Trigger.isAfter && Trigger.isInsert){
       ContactRollupSummaryHandler.afterInsert(Trigger.new);
    }
    if(Trigger.isAfter && Trigger.isUpdate){
       ContactRollupSummaryHandler.afterUpdate(Trigger.new,Trigger.oldMap);
    }
    if(Trigger.isAfter && Trigger.isDelete){
       ContactRollupSummaryHandler.afterDelete(Trigger.old);
    }
    if(Trigger.isAfter && Trigger.isUndelete){
       ContactRollupSummaryHandler.afterUndelete(Trigger.new);
    }
    
}
CLASS:
public class Currencyconverter {
    public static decimal CurrencyconverterfromEUROtoINR(decimal eur){
        decimal inr = 0.0;
        HTTP http = new HTTP();
        HTTPRequest req= new HTTPRequest();
        req.setEndpoint('https://api.exchangeratesapi.io/latest');
        req.setMethod('GET');
        HTTPResponse res = http.send(req);
        Map <string,object> Jsonbody=(Map <string,object>)Json.deserializeUntyped(res.getBody());
        system.debug(Jsonbody);
        Map <string,object> rates=(Map<string,object>)Jsonbody.get('rates');
        decimal conversionrate= (decimal)rates.get('INR');                    
        inr = eur * conversionrate;      
        return inr;
    
}
}

Testing at anonymous window:
decimal conversionrate = Currencyconverter.CurrencyconverterfromEUROtoINR(150);
system.debug('conversionrate'+conversionrate);

ERROR:
System.NullPointerException: Attempt to de-reference a null object
  • July 22, 2021
  • Like
  • 0
public class Duplicate {
    public Account acc {set;get;}
    public Duplicate(){
        acc=new Account();
    }
    public PageReference create(){
        PageReference p;
        try{
          integer count=[select count() from Account where name=:acc.name];
              if(count>0){
                Apexpages.Message msg=new Apexpages.Message(Apexpages.Severity.ERROR,'Duplicate Record found');
                Apexpages.addMessage(msg);
               }
              else{
                insert acc;
                p=new PageReference('/'+acc.Id);
               }
             }
         catch(Exception e){
            Apexpages.Message msg=new ApexPages.Message(ApexPages.Severity.ERROR,e.getMessage());
            ApexPages.addMessage(msg);
        }
        return p;
    }
}
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;
        }
    }
}
User-added imageUser-added imageglobal class Email2 {
    @HttpGet
    global static void sendMail(){
list<Messaging.SingleEmailMessage> mail = new list<Messaging.SingleEmailMessage>();
Messaging.SingleEmailMessage mails = new Messaging.SingleEmailMessage();
 
list <String> toAddresses = new list<String>();
 toAddresses.add('varsha.dustakar7@gmail.com');
 mails.setToAddresses(toAddresses);
 
List<Contact> con = [SELECT Id, firstname FROM Contact];
 List<Id> lstids= new List<Id>();
 for(Contact c:con) {
  lstids.add(c.id);
 }
EmailTemplate et = [SELECT id FROM EmailTemplate WHERE developerName = 'gmail_salesforce'];
mails.setTargetObjectId(lstids); 
mails.setTemplateId(et.id);
mail.add(mails); 
Messaging.sendEmail(new Messaging.singleEmailMessage[] { mails });
    }
}
Hi there!
I'm looking for a solution about that case =>
When an opportunity is created, the name must have the following format: Automatic Number – Account Name – Creation Date.
Any advices?  :)
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

whenver a contact is Inserted update the Email with test@test.com 
please help me to write a trigger for this requirment.
I am getting the following error when i try to save and activate a flow

f_EndDateTime (Formula) - The formula expression is invalid: Incorrect parameter type for function 'YEAR()'. Expected Date, received DateTime

Here is the formula below:

how would I adjust this formula to stop that error
DATETIMEVALUE(TEXT(YEAR({!End_Date_Time}))+"-" +TEXT(MONTH({!End_Date_Time}))+"-"+TEXT(DAY({!End_Date_Time}))+" 12:00:00")

 
Hello, I build a List button that Includes a Visualforce Page. When I chose Accounts in List view and click account I only see the blank Page without the account fields. Please tell me how to change it.

<apex:page standardController="Account" renderAs="pdf" recordSetVar="accounts" >
 

<h1>Welcome to APP!</h1>
 
<p>Thank you, <b><apex:outputText value=" {!Account.Name}"/></b>, for 
   working with APP.</p>
 
<p>Your account details are:</p>
 
<table>
<tr><th>Account Name</th>
    <td><apex:outputText value="{!Account.Name}"/></td>
    </tr>
<tr><th>Account Rep</th>
    <td><apex:outputText value="{!Account.Owner.Name}"/></td>
    </tr>
<tr><th>Customer Since</th>
    <td><apex:outputText value="{0,date,long}">
        <apex:param value="{!Account.CreatedDate}"/>
        </apex:outputText></td>
    </tr>
</table>
    
</apex:page>

User-added image


Result:

User-added image
Hi, I want to write a test class for Batch Callout. The code is below:

global class BatchSync implements Database.Batchable<sObject>, Database.AllowsCallouts{
     
    global Database.QueryLocator start(Database.BatchableContext bc){
    
        String query = 'SELECT id, Name, Type From Account WHERE Type='Prospect';
       
        return Database.getQueryLocator(query);
    }
     
    
    global void execute(Database.BatchableContext bc, List<Account> scope){
         
       for (Account acc : scope){  
         
                try{
                    HttpRequest request = new HttpRequest();
                    HttpResponse response = new HttpResponse();
                    Http http = new Http();                    
                    String username = 'Username';
                    String password = 'Password';
                    Blob headerValue = Blob.valueOf(username + ':' + password);
                    String authorizationHeader = 'BASIC ' + EncodingUtil.base64Encode(headerValue);
                     
                    request.setHeader('Authorization', authorizationHeader);
                    request.setHeader('Content-Type', 'application/json');
                          
                    request.setEndpoint(enpointurl);
                    request.setMethod('GET');
                    response = http.send(request);                      
                        if (response.getStatusCode() == 200) {
                        String jsonResponse = response.getBody();                                           acc.Type='Customer';
                        
                    }
                    JSONParser parser = JSON.createParser(response.getBody());
                    HttpResponse res = http.send(request);
                    //list of header names keys
                    string[] headerkeys = res.getHeaderKeys();
                    Map<string, string> headers = new map<string, string>();
            
                    //iterate through they keys, and populate your map
                    for(string s : headerkeys){
                    headers.put(s,res.getHeader(s));
                    system.debug('header: ' + s + ' value: ' + res.getHeader(s));
                    }
                    }
                     
                                   
                catch(Exception e){
                   System.debug('Error-' + e.getMessage());   
                } 
                      update scope;
                        }
        }
                   
            
        
    }
 
    global void finish(Database.BatchableContext bc)
    { 
         
    }
}
public class DynamicQuery {
public static void GetContactsBySearch(string searchtext)
  {
     if(searchtext != null && searchtext != '')
     {
         string contactquery = 'select id, Firstname, Lastname, Email from contact';
        if(pattern.matches('^[a-zA-Z0-9._|\\\\%#~`=?&/$^*!}{+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,4}$' , searchtext))
           {
               system.debug('If user input is email');
               contactquery += 'Where Email =: searchtext';
           }
         else
         {
             system.debug('If user input is text value');
             searchtext += '%';
             contactquery += 'Where Lastname like : searchtext';
         }
          List<contact> lstcon =  Database.query(contactquery);  
           if(!lstcon.isempty())
           {
               system.debug('Collection size is..:'+ lstcon.size());
            for(contact con : lstcon)
            {
               system.debug('Contact records are ..:'+ con);
           }               
           }
     }
  }
}

Hi, 
I'm using JSON.deserializeUntyped method, I tested it through dev console in 2 unrelated orgs and both of them gave the same strange result.
I run this code through anonymous window, which basically takes a JSON and through deserializeUntyped method, breaks it to pieces: 

string ex='{"Quote Line_Repeating":[{"Quote Line":{"Line ID":"1","Discount":"true","Discount Type":"Regular","Sell Multiplier":1,"Rep Net Multiplier":0.75,"Pricing":"true","Base List Price":866,"Base Currency":"USD","Quote List Price":866,"Quote Currency":"USD","Exchange Rate":1}}]}';

Map<String, Object> m = (Map<String, Object>)JSON.deserializeUntyped(ex);

List<Object> a = (List<Object>)m.get('Quote Line_Repeating');System.debug('ex: '+ex);System.debug('m: '+m);
 


 The result that I got for ex variable:

USER_DEBUG [6]|DEBUG|ex: {"Quote Line_Repeating":[{"Quote Line":{"Line ID":"1","Discount":"true","Discount Type":"Regular","Sell Multiplier":1,"Rep Net Multiplier":0.75,"Pricing":"true","Base List Price":866,"Base Currency":"USD","Quote List Price":866,"Quote Currency":"USD","Exchange Rate":1}}]}
 

The results which I got for m variable:

USER_DEBUG [7]|DEBUG|USER_DEBUG [7]|DEBUG|m: {Quote Line_Repeating=({Quote Line={Base Currency=USD, Base List Price=866, Discount=true, Discount Type=Regular, Exchange Rate=1, Line ID=1, Pricing=true, Quote Currency=USD, Quote List Price=866, Rep Net Multiplier=0.75, ...}})}
 

If you compare carefully the 2 logs, you'll see that after going through JSON.deserializeUntyped method, the "Sell Multiplier":1 value just vanished from the view and the log shows
It's seems that the 'deserializeUntyped' sorted the attributes and omitted all attributes after the 10th attribute. 

In addition, I tweaked the JSON by adding and removing attributes and always the result was the same, the first 10 alphabetical attributes appeared and the other were omitted.
I think that it's a bug, as I didn't find any documentation about this kind of SF limit, but maybe I'm missing something.
I'll be happy for assistance Thanks
Victor

Hello, I build a trigger, but nobody could help me with the test class. I have a picklist called Dokumentenklasse that is on Content Version. In this picklist there are 3 values ('Geschäftsbrief', 'Vertragsdokument' and 'Wichtige Dokumentation oder Entscheidung') when these values are selected the file can't be deleted.

Please help me with the code of the testclass and try it out too. I had 0% with the last classes I used. The trigger code:


trigger DokumentenklasseDelete on ContentDocument (before delete) {       
    map<id,ContentDocument> documentMap = new map<id,ContentDocument>([SELECT id,(SELECT Id,FileType,Dokumentenklasse__c from ContentVersions) from ContentDocument where id IN :trigger.old]);          

  for(ContentDocument con : Trigger.old){          

  List<ContentVersion> versionList = documentMap.get(con.Id).ContentVersions;         

if (versionList.size() > 0) {        

for (contentVersion cv : versionList) {                   

if(cv.Dokumentenklasse__c =='Geschäftsbrief' || cv.Dokumentenklasse__c == 'Vertragsdokument' || cv.Dokumentenklasse__c == 'Wichtige Dokumentation oder Entscheidung' ) {                         
    con.adderror('ERROR: Dokumente der Dokumentenklassen "Geschäftsbrief", "Vertragsdokument", "Wichtige Dokumentation oder Entscheidung" dürfen aus rechtlichen Gründen vor Ablauf der Aufbewahrungsfrist nicht gelöscht werden.');                    

 }              

    }            

 }                    

  } }

I have problem with my unit test class. 

@RestResource(urlMapping='/magnolia/account/*')
global with sharing class MCH_MagnoliaAccountRest {


    @HttpGet
    global static List<AccountWrapper> getAccount(){//what do you need to get ? Single row ?
        String idsParam = RestContext.request.params.get('ids');
        List<String> ids = new List<String>();
        ids = idsParam?.split(',');
        List<AccountWrapper> accountsResult = new List<AccountWrapper>();
        for(Account a : [Select 
                         	 Id,
                             mch_MCH_Login_ID__pc,
                             Type,
                             Name,
                             Description,
                             PersonMailingStreet,
                             PersonMailingPostalCode,
                             PersonMailingCountry,
                             Phone,
                             PersonEmail,
                             Website,
                             Industry,
                             mch_interests__c
                         From Account
                         WHERE Id IN :ids
                         Limit 1]){
            accountsResult.add(
                wrapAccount(a)
            );
        }
        return accountsResult;
    }
    @HttpPost
    global static String insertAccount(List<AccountWrapper> accounts){
        List<Account> accountList = new List<Account>();
        for(AccountWrapper aw : accounts){
            accountList.add(
                aw.getAccount()
            );
        }
        if(!accountList.isEmpty()){
            dmlErrorHandling(
                Database.insert(accountList, false)
            );
        }
        return 'ok';
    }
    @HttpPatch
    global static String updateAccount(List<AccountWrapper> accounts){
        List<Account> accountList = new List<Account>();
        for(AccountWrapper aw : accounts){
            accountList.add(
                aw.getAccount()
            );
        }
        if(!accountList.isEmpty()){
            dmlErrorHandling(
                Database.update(accountList, false)
            );
        }
        return 'ok';
    }
    @HttpPut//what do you need to delete ? Single row ?
    global static String deleteAccount(List<AccountWrapper> accounts){
        List<Account> accountList = new List<Account>();
        for(AccountWrapper aw : accounts){
            accountList.add(
                aw.getAccount()
            );
        }
        if(!accountList.isEmpty()){
            dmlErrorHandling(
                Database.delete(accountList, false)
            );
        }
        return 'ok';
    }

Unit test code

@isTest
public class MCH_MagnoliaAccountRestTest 
{   
    @isTest
    static Account TestGetAccount()
    {
        Account account = McH_MockupFactory.createAccount();
        if(true)
        {
            insert account;
        }
        return account;
    }
    
    @isTest 
    static void InsertAccount()
    {
        Account account = McH_MockupFactory.createAccount();
        insert account;
    }
    
    @isTest 
    static void UpdateAccount()
    {
        List<MCH_MagnoliaAccountRest.AccountWrapper> aw = new List<MCH_MagnoliaAccountRest.AccountWrapper>();
        
        Account account = McH_MockupFactory.createAccount();
        insert account;
    }
    
    @isTest 
    static void deleteAccount()
    {   
        List<MCH_MagnoliaAccountRest.AccountWrapper> aw = new List<MCH_MagnoliaAccountRest.AccountWrapper>();
        
        Account account = McH_MockupFactory.createAccount();
        insert account;
        account = MCH_MagnoliaAccountRest.deleteAccount(aw); // Here I have the error.
        delete account;
    }
}

Need help to finish it.
Hi Developer Community , 


Can u please write test class for this apex code
public class RSSFeedUtil {
    public static List<RSSObject> getGoogleRSSObjects(String theUrl) {
        List<RSSObject> returnList = new List<RSSObject>();
        
        Http h = new Http();
        HttpRequest req = new HttpRequest();        
        req.setEndpoint(theUrl);
        req.setMethod('GET');
        HttpResponse res = h.send(req);
        
        Dom.Document doc = res.getBodyDocument();
        Dom.XMLNode feed = doc.getRootElement();
        String namespace = feed.getNamespace();
        
        for(Dom.XMLNode child : feed.getChildElements()) {
            if(child.getName() == 'entry') {
                RSSObject returnListItem = new RSSObject(
                    child.getChildElement('title', namespace).getText().unescapeHtml4(),
                    child.getChildElement('link', namespace).getAttribute('href', ''),                    
                    child.getChildElement('content', namespace).getText().unescapeHtml4(),
                    child.getChildElement('published', namespace).getText()
                );
                System.debug(returnListItem);
                returnList.add(returnListItem);
            }
            System.debug(returnList);
        }
        return returnList;        
    }
}

Thanks in Advance
Hi Developer community , 

i have an apex class , i am having only little knowledge on test classes , 
can u please write test class for below apex code
public class RSSFeedCtrl {
    @AuraEnabled
    public static String getURL(String URLField, ID recordId, String objectName) {
        String queryString = 'select ' + URLField + ' from ' + objectName + ' where Id = \'' + recordId + '\'';
        String returnValue = '';
        
        try {
            sObject s = Database.query(queryString);
            returnValue = (String)s.get(URLField);
        }
        catch (Exception e) {
            throw new AuraHandledException('Error in getURL method of RSSFeedCtrl: ' + e.getMessage());    
        }
        
        return returnValue;
    }

    @AuraEnabled
    public static List<RSSObject> getRSSFeed(String url) {
        List<RSSObject> toReturn = new List<RSSObject>();
        try {
            if(url != null){
                toReturn = RSSFeedUtil.getGoogleRSSObjects(url);
            } 
        }
        catch (Exception e) {
            throw new AuraHandledException('Error in getRSSFeed method of RSSFeedCtrl:' + e.getMessage());    
        }
               
        return toReturn;
    }
}

Thanks in Advance
Trigger will close Opportunity if no valid phone numbers exist.

Opportunity has Primary_Contact__c and Secondary_Contact__c

On Contact 3 phone fields to check:
Phone__c
Work_phone__c
Mobile_phone__c

On Contact 3 Phone Status Fields:  
Phone_Status__c
Work_Status__c
Mobile_Status__c.

After Insert/Update of a Contact, the Trigger will check all Opportunities associated with the Contact.  If there are no valid (meaning having a number and corresponding status is not equal to "Do Not Call"), then close the Opportunity.

I have created the Trigger and Test Class but I don't understand why the lines in the test class are not executing.

Thank you.

Trigger:
trigger Contact_DNC_Opportunity on Contact (after insert, after update){

    

      List<Opportunity> OpportunitiesToClose = new List<Opportunity>();

    List<Opportunity> WorkingOpportunities = [SELECT StageName, Primary_Contact__c, Secondary_Contact__c,

                                              Primary_Contact__r.Phone_Status__c, Primary_Contact__r.Mobile_Phone_Status__c, Primary_Contact__r.Work_Phone_Status__c,

                                              Primary_Contact__r.Phone, Primary_Contact__r.Normalized_Mobile_Phone__c, Primary_Contact__r.Normalized_Work_Phone__c,                                          

                                              Secondary_Contact__r.Phone_Status__c, Secondary_Contact__r.Mobile_Phone_Status__c, Secondary_Contact__r.Work_Phone_Status__c,

                                              Secondary_Contact__r.Phone, Secondary_Contact__r.Normalized_Mobile_Phone__c, Secondary_Contact__r.Normalized_Work_Phone__c

                                              FROM Opportunity WHERE Primary_Contact__c In :Trigger.New OR Secondary_Contact__c In :Trigger.New

                                             ];

     
System.debug(WorkingOpportunities);
    
    for(Opportunity opp: WorkingOpportunities){
        
//Check Primary Contact phone numbers          

            if ((opp.Primary_Contact__r.Phone == Null) || (opp.Primary_Contact__r.Phone_Status__c == 'Do Not Call')&&
                (opp.Primary_Contact__r.Normalized_Mobile_Phone__c == Null) || (opp.Primary_Contact__r.Mobile_Phone_Status__c == 'Do Not Call')&&
                (opp.Primary_Contact__r.Normalized_Work_Phone__c == Null) || (opp.Primary_Contact__r.Work_Phone_Status__c == 'Do Not Call')&&
                (opp.Secondary_Contact__r.Phone == Null) || (opp.Secondary_Contact__r.Phone_Status__c == 'Do Not Call')&&
                (opp.Secondary_Contact__r.Normalized_Mobile_Phone__c == Null) || (opp.Secondary_Contact__r.Mobile_Phone_Status__c == 'Do Not Call')&&
                (opp.Secondary_Contact__r.Normalized_Work_Phone__c == Null) || (opp.Secondary_Contact__r.Work_Phone_Status__c == 'Do Not Call')
                ) {

                    

//Add opp to List if fits criteria

       opportunitiesToClose.add(opp);

           }

}

   

    for (Opportunity opp1 : opportunitiesToClose){

        opp1.StageName = 'Closed Lost';

    }

 

    if(opportunitiesToClose.size() > 0){

        update opportunitiesToClose ;

    }

 

}

Test Class:
@isTest
private class ContactDNCOpportunityTest {
       
    private static testMethod void testCloseOpps(){
        //Create Account
        
        Account newAcc = FlowTestUtils.createHouseholdAccount();
    		insert newAcc;  
        
        
       //Create Contacts
           List<Contact> conList = new List<Contact> {
		new Contact(FirstName='test1',LastName='tester',AccountId = newAcc.Id, Email = 'test1@testing.com', Phone = '1234567891', Phone_Status__c = 'Do Not Call'),  //Has Phone Number - Do not call, Closed Opp
        new Contact(FirstName='test2',LastName='tester',AccountId = newAcc.Id, Email = 'test2@testing.com'), //Blank No Numbers  Closed Opp
        new Contact(FirstName='test3',LastName='tester',AccountId = newAcc.Id, Email = 'test3@testing.com', Normalized_Work_Phone__c = '1234567891',Work_Phone_Status__c = 'Active'), // Has Work Number, Active, Do Not Close Opp
		new Contact(FirstName='test4',LastName='tester',AccountId = newAcc.Id, Email = 'test4@testing.com', Phone = '1234567891', Phone_Status__c = 'Active'), //Has Phone Number, Active, Do not Close Opp
        new Contact(FirstName='test5',LastName='tester',AccountId = newAcc.Id, Email = 'test5@testing.com', Normalized_Mobile_Phone__c = '1234567891', Mobile_Phone_Status__c = 'Do Not Call'), //Has mobile number, DNC, Close Opp      
        new Contact(FirstName='test6',LastName='tester',AccountId = newAcc.Id, Email = 'test6@testing.com', Normalized_Work_Phone__c = '1234567891', Work_Phone_Status__c = 'Do Not Call') //Has Worknumber DNC is checked
            };	
                
            insert conList;
       
        
        Opportunity opptest1 = new Opportunity(Name = 'Opp1', AccountId = newACC.id, StageName = 'Ready to Call/Schedule', CloseDate = Date.today(), Primary_Contact__c = [SELECT Id FROM Contact WHERE FirstName = 'test1'].id);
        Test.startTest();
            insert opptest1;
        Test.stopTest();   
        
        System.assertEquals('Closed', opptest1.StageName);
                
            
        Opportunity opptest2 = new Opportunity(Name = 'Opp2', AccountId = newACC.id, StageName = 'Ready to Call/Schedule', CloseDate = Date.today(), Primary_Contact__c = [SELECT Id FROM Contact WHERE FirstName = 'test2'].id);
        Test.startTest();
            insert opptest2;
        Test.stopTest();   
        
        System.assertEquals('Closed', opptest2.StageName);
          
        
         Opportunity opptest3 = new Opportunity(Name = 'Opp3', AccountId = newACC.id, StageName = 'Ready to Call/Schedule', CloseDate = Date.today(), Primary_Contact__c = [SELECT Id FROM Contact WHERE FirstName = 'test3'].id);
         Test.startTest();
            insert opptest3;
         Test.stopTest();   
        
        System.assertEquals('Closed', opptest3.StageName);
           
        
         Opportunity opptest4 = new Opportunity(Name = 'Opp4', AccountId = newACC.id, StageName = 'Ready to Call/Schedule', CloseDate = Date.today(), Secondary_Contact__c = [SELECT Id FROM Contact WHERE FirstName = 'test4'].id);
         Test.startTest();
            insert opptest4;
         Test.stopTest();   
        
        System.assertNotEquals('Closed', opptest4.StageName);
           
        
         Opportunity opptest5 = new Opportunity(Name = 'Opp5', AccountId = newACC.id, StageName = 'Ready to Call/Schedule', CloseDate = Date.today(), Secondary_Contact__c = [SELECT Id FROM Contact WHERE FirstName = 'test5'].id);  
         Test.startTest();
            insert opptest5;
         Test.stopTest();   
        
        System.assertEquals('Closed', opptest5.StageName);
            
        
         Opportunity opptest6 = new Opportunity(Name = 'Opp6', AccountId = newACC.id, StageName = 'Ready to Call/Schedule', CloseDate = Date.today(), Secondary_Contact__c = [SELECT Id FROM Contact WHERE FirstName = 'test6'].id);
         Test.startTest();
            insert opptest6;
         Test.stopTest();   
        
        System.assertEquals('Closed', opptest6.StageName);
            
         Opportunity opptest7 = new Opportunity(Name = 'Opp7', AccountId = newACC.id, StageName = 'Ready to Call/Schedule', CloseDate = Date.today());                                            
         Test.startTest();
            insert opptest7;
         Test.stopTest();   
        
        System.assertEquals('Closed', opptest7.StageName);
        
    }
             
}

User-added image​​​​​​​
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.
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.
<apex:page showheader="false" sidebar="false" standardController="Account" >
    <apex:pageBlock title="account information">
        <apex:pageBlockSection title="general account detail">
            <apex:outputField  value="{!Account.name}"/>
            <apex:outputField  value="{!Account.fax}"/>
            <apex:outputField  value="{!Account.phone}"/>
        </apex:pageBlockSection>
        <apex:pageBlockSection title="related accounts">
            <apex:relatedList list="contacts"/>
            <apex:relatedList list="opportunities"/>
        </apex:pageBlockSection>
       </apex:pageBlock>
    <apex:pageBlock title="custom table">
        <apex:pageBlockTable value="{!Account.contacts}" var="AC">
          <apex:column headervalue="contact first name" value="{!AC.first name}"/>
            <apex:column headervalue="contact last name" value="{!AC.last name}"/>
            <apex:column  headervalue="contact email" value="{!AC.contact email}"/>
        </apex:pageBlockTable>
    </apex:pageBlock>
  </apex:page>
Hello Friends,

Your thoughts on my issue is highly appreciable. 
The scenario what I am trying to do here using Process Builder is updating child accounts when there is update on Parent account.
I have a custom picklist field Org Type (not used global picklist value set) on Account object. I am trying to set this value to all child accounts in the hierarchy where there is update the same field on Parent account.
I tried all these methods.
1st: I tried directly mapping field reference field [Account].Parent.Organization_Type__c to child account field. 
2nd: Used a formula with CASE (shown below) using both TEXT([Account].Parent.Organization_Type__c) and withouth TEXT. 

CASE(TEXT([Account].Parent.Organization_Type__c),
"Sole Proprietorship", "Sole Proprietorship",
"Partnership", "Partnership",
"Unincorporated", "Unincorporated",
"Limited Liability Company", "Limited Liability Company",
"Other", "Other",
"")

The issue is the custom picklist field update on Parent is not at all updating on child records. Am I doing something wrong here?
Hi,

I have the code which will copy the ''BannerAd'' which is a custom object and shown as a related list on the opportunity, whenever the opportunity is cloned. This is working in the sandbox but I need help with the test class so I can push this to production. Below is the code - 

In order to make it work. I had to define two new Apex classes in the developer console

OppCloneTrigger - a trigger that will file after and Opportunity is saved in the system. Defined like:

trigger OppCloneTrigger on Opportunity (after insert) {
    // Create a variable for adding all the closed opps.
    List<Opportunity>closedOpp = new list<Opportunity>();

    // Run through the list and generated closed opporunities.
    for(Opportunity op : Trigger.new) {
        
        // Only add opportunities that are cloned and either won or closed.

        // (op.StageName != Trigger.oldMap.get(op.Id).StageName) - no need to check for this since it as an insert.
        if(op.isClone()) {
            closedOpp.add(op);
        }
    }

    // Clone the banners
    OppCloneClass.copyBannerAds(closedOpp);
}




and the OppCloneClass - a class that defines a method used to close the banner from original opportunity to the cloned one. Defined:

public class OppCloneClass {
    public static void CopyBannerAds(List<Opportunity> opporunities) {
        // For every opportunity delivered
        for(Opportunity op : opporunities)
        {
            // Only run this for a cloned opportunity.
            if (op.isClone()) {
                // Get the id of the source oppotunity.
                ID sourceId = op.getCloneSourceId();
                
                // Get the banners from the opportunity that the clone originated from. 
                // Need to manually specify the fields retrieved so that clone copy all the fields.
                List<banner__c> banners=[SELECT 
                    Id,
                    IsDeleted,
                    Name,
                    CreatedDate,
                    CreatedById,
                    LastModifiedDate,
                    LastModifiedById,
                    SystemModstamp,
                    LastActivityDate,
                    LastViewedDate,
                    LastReferencedDate,
                    Opportunity__c,
                    Practice_Address__c,
                    Location__c,
                    Inventory_Number__c,
                    Account_or_HCP_Name__c,
                    HS_Contract_GST__c,
                    Competition_Banner__c,
                    Tier__c,
                    Discount__c,
                    Monthly_Banner_Fee__c,
                    Banner_Discount_in__c,
                    Banner_Price_2__c,
                    Group_Purchase_B__c,
                    HS_Total_Price_incl_GST__c,
                    Listing_End_Date__c,
                    HS_Inventory__c,
                    HS_Discount_Price__c,
                    Banner_Region__c,
                    HS_full_Price__c,
                    HS_Specialty__c,
                    HS_Contract_Duration__c,
                 FROM banner__c WHERE Opportunity__c = :sourceId];

                // Create new banner items by cloning all the ones related to the source opportunity. 
                List<banner__c> newBanners = new List<banner__c>();
                for(banner__c banner : banners) {
                    banner__c banclone = banner.clone();
                    banclone.Opportunity__c=op.id;
                    newBanners.add(banclone);
                }
                // Commit new banners into the system.
                insert newBanners;
            }
        }
    }
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. 
I want to write a trigger on Contact , when a contact insert an email should be sent to contact email id.

I have written the below code and when I try to create a new contact, contact is not receiving an email. Can anyone help me.

trigger conss on Contact (before insert) {
    set<id> conlist = new set<id>();
    for(contact cons : trigger.new){
       conlist.add(cons.id);
    }
    public static void emailsent(){
        list<Messaging.SingleEmailMessage> maillist = new list<Messaging.SingleEmailMessage>();
        EmailTemplate et = [select id,
                             subject,
                             body from EmailTemplate where DeveloperName = 'contact_test' ];
        contact cont = [select id,email from contact where id in : conlist];
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage ();
        mail.setTemplateId(et.id);
        mail.setTargetObjectId(cont.Id);
        maillist.add(mail);
        
        if(!maillist.isEmpty()){
            Messaging.sendEmail(maillist);
        }
    }
   
}
i have course field on Training_Deal__c
==============================
public class SearchCourse {
    public string SearchText {set;get;}
     public string query {set;get;}
     public List<Training_Deal__c> deal {set;get;}
    public void fetchData(){
       
        string query = 'SELECT id, Name, Course__c,Discount__c,Student__c,Email_of_Student__c,Trainer_Appointed__c FROM Training_Deal__c WHERE Course__c =:'+SearchText ;
        deal=Database.query(query);
        system.debug(deal);
    }

}
=======================================
<apex:page controller="SearchCourse" >
    <apex:form id="fm">
        <apex:inputText value="{!SearchText}"/>
        <apex:commandButton value="Search" action="{!fetchData}" reRender="fm"/><br/><br/>
        <apex:dataTable value="{!deal}" var="a" cellpadding="5"  rules="Rows" width="20" border="frame">
            <apex:column value="{!a.Name}" headerValue="Deal code"/>
            <apex:column value="{!a.Course__c}" headerValue="Course"/>
            <apex:column value="{!a.Discount__c}" headerValue="Discount"/>
            <apex:column value="{!a.Student__c}" headerValue="Student"/>
            <apex:column value="{!a.Email_of_Student__c}" headerValue="Student Email"/>
            <apex:column value="{!a.Trainer_Appointed__c}" headerValue="Trainer"/>
  
                         
        </apex:dataTable>
    </apex:form>
</apex:page>

classs 


public class LeadHelper 
{
 public void createNewLeadRecord()
 {
     Lead ld = new Lead ();
     ld.FirstName = 'Test';
     ld.LastName ='Lead record';
     ld.Company = 'google';
     ld.Status = 'OPen - Not contacted';
     ld.Rating = 'HOt';
     ld.Industry = 'Banking';
     ld.AnnualRevenue = 4500000;
     ld.Phone = '6765434567';
     ld.Fax = '6776543456789';
     ld.Email = 'sample@gmail.com';
     ld.LeadSource ='web';
     ld.website = 'www.salesforce.com';
     ld.city = 'Hyderabad';
     ld.Country = 'india';
      
     insert ld;
     if(ld.id != null)
         system.debug('lead record inserted with id .....:'+ld.id);
     
         }
     
 
}


execution


LeadHelper ldHelper = new LeadHelper();

ldHelper.createtNewLeadRecord();



 
Helo Everyone,

 I have created two custom field named Amount__c and Connection_Id under the Object 'Order'.

And I have perform callout and get response from the endurl in the form of JSON Data.
Here, the sample JSON file:
 {"data":[{"id":"2911647985786786830357753","connection_id":"291165354723552979434","name":"Simple account 1 MasterCard","nature":"card","balance":2019.4,"currency_code":"EUR", "extra":{ "iban":"DE11100110012612442222",},"created_at":"2020-08-24T05:58:45Z","updated_at":"2021-04-02T07:34:19Z"}

I need to deserialize this file and separate the Balance and connection_id from the json file and store this value in the Amount_c and Connection_Id__c in the 'Order' object.

Is there any suggestion??
Thanks in advance.
Hi all,

We noticed an annoying problem with Events created from Apex.

User-added image

This event was created by a custom Apex class we use in an LWC for scheduling. Here is the code for that. 

User-added image

The subject for the example event was simply "PAD/TCHA/HSA". The Account name gets added automatically which is wanted, but not that many times.

Is there a reason this is happening? I notice now that I am missing (cacheable=true) since this is returning the Id but would that be the cause of the problem?

Any information on Events would be helpful, I feel like this object has barely any helpful documentation out there.
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,

Im trying to create user from contact object by using trigger and method. However, Im getting the below error , could you please help

Variable does not exist: CreateNewUserHandler
Missing  at 'public'


trigger NewUser on Contact (after insert) {

    List<User> userList = new List<User>();
    Set<Id> contactIds = new Set<Id>();
    for(Contact c: Trigger.New){
       if(c.Agent_type__c == 'Member'){
            contactIds.add(c.id);
        }
    }

    if(contactIds.size() > 0){
        CreateNewUserHandler.createNewUserFromContact(contactIds);
    }
}
public with sharing class CreateNewUserHandler {


public static void CreateNewUserHandler(Set<Id> contactIds)
{
    List<User> userList = new List<User>();
    List<Profile> profileList = [Select Id from Profile where Name=: 'Customer Community User' limit 1];
    //List<UserRole> roleList = [Select Id from UserRole where Name=: 'CEO' limit 1];
    for(Contact contactObj : [Select Id, Name, Email,Username__c from Contact where Id IN: contactIds limit 50000]){
        User uObj = new User();
        uObj.Username = contactObj.Username__c;
        uObj.Email = contactObj.Email;
        uObj.Alias = contactObj.Name;
        uObj.UserRoleId = roleList[0].Id;
        uObj.ProfileId = profileList[0].Id;
        uObj.IsActive = true; 
        uObj.TimeZoneSidKey = 'GMT';
        uObj.LanguageLocaleKey = 'en_US';
        uObj.EmailEncodingKey = 'UTF-8';
        uObj.LocaleSidKey = 'en_US';
        uObj.ContactId = contactObj.Id;
        userList.add(uObj);
    }
    try{
           insert userList;  // insert the user record
    }catch(Exception e){
          // Catch Exception
     }
}
Hi All,

I want to fetch the lead mapping in apex i.e. which lead fields are mapped to which fields of Account / Contact / Opportunity.

Any pointers that can be used to approach this?

Thanks
I have the following use case
If a Picklist Field 'Business unit' is 'eBay Plus' then a field 'Accounting' should be set to “Contra Transaction Revenue”. If the picklist 'Business unit' is “Top SKU” then a Field Accounting should be set  to “Marketing”
I have resolved above using standard criteria  in Process builder but having issues with below as I am  trying to use a formula.

If any other Business unit is other than 'eBay Plus Or Top SKU is selected,

And If Any of the 3 picklist fields below 

Has_buyer_committed_to_the_seller__c 
Incentivizing_Selling_Activity__c
Seller_Co_funding__c 

is Set to 'YES', then the  Field Accounting is set to 'Contra Transaction Revenue'.

I have the following but does not seem to work


AND(

OR(
ISPICKVAL([eForm__c].Business_Unit__c <> 'eBay Plus'),
ISPICKVAL([eForm__c].Business_Unit__c <> 'Top SKU'),

)

OR(
ISPICKVAL([eForm__c].Has_eBay_committed_to_the_seller__c = 'Yes'),
ISPICKVAL([eForm__c].Incentivizing_Selling_Activity__c = 'Yes'),
ISPICKVAL([eForm__c].Seller_Co_funding__c = Yes)
)
)

getting Error: Incorrect number of parameters for function 'ISPICKVAL()'. Expected 2, received 3
Would appreciate your help.

Thanks,
TM

this is my code i want to give count of contacts associate with account but when i changed contacts account(lookup) it update new owner count value but not updating the value in old account count

this is my code
handler:
public class ContactRollupSummaryHandler {
    public static void afterInsert(list<Contact> contacts){
        NumberofContacts(contacts);
    }
    public static void afterUpdate(list<Contact> contacts,Map<Id,Contact> oldMap){
        list<Contact> conlist = new list<Contact>();
        for(Contact c: contacts){
            if(c.AccountId != oldMap.get(c.Id).AccountId){
                conlist.add(c);
            }
        }
        if(conlist.size()>0){
            NumberofContacts(conlist);
        }
    }
    public static void afterDelete(list<Contact> contacts){
        NumberofContacts(contacts);
    }
    public static void afterUndelete(list<Contact> contacts){
        NumberofContacts(contacts);
    }
    
    
    public static void NumberofContacts(list<Contact> con){
        set<id> accIds = new set<id>();
        for(Contact c: con){
            if(c.AccountId != null){
            accIds.add(c.AccountId);
            } 
        }
        
        if(accIds.size()>0){
            list<Account> acclist = new list<Account>();
        for(Account ac: [SELECT id,Number_of_Contacts__c,(SELECT id from Contacts) from Account where id IN:accIds]){
            ac.Number_of_Contacts__c = ac.Contacts.size();
            acclist.add(ac);
        }
            if(acclist.size()>0){
                update acclist;
            }    
        
        }
    }

}

Trigger:
trigger ContactTrigger on Contact (after insert,after update,after delete, after undelete) {
    if(Trigger.isAfter && Trigger.isInsert){
       ContactRollupSummaryHandler.afterInsert(Trigger.new);
    }
    if(Trigger.isAfter && Trigger.isUpdate){
       ContactRollupSummaryHandler.afterUpdate(Trigger.new,Trigger.oldMap);
    }
    if(Trigger.isAfter && Trigger.isDelete){
       ContactRollupSummaryHandler.afterDelete(Trigger.old);
    }
    if(Trigger.isAfter && Trigger.isUndelete){
       ContactRollupSummaryHandler.afterUndelete(Trigger.new);
    }
    
}
CLASS:
public class Currencyconverter {
    public static decimal CurrencyconverterfromEUROtoINR(decimal eur){
        decimal inr = 0.0;
        HTTP http = new HTTP();
        HTTPRequest req= new HTTPRequest();
        req.setEndpoint('https://api.exchangeratesapi.io/latest');
        req.setMethod('GET');
        HTTPResponse res = http.send(req);
        Map <string,object> Jsonbody=(Map <string,object>)Json.deserializeUntyped(res.getBody());
        system.debug(Jsonbody);
        Map <string,object> rates=(Map<string,object>)Jsonbody.get('rates');
        decimal conversionrate= (decimal)rates.get('INR');                    
        inr = eur * conversionrate;      
        return inr;
    
}
}

Testing at anonymous window:
decimal conversionrate = Currencyconverter.CurrencyconverterfromEUROtoINR(150);
system.debug('conversionrate'+conversionrate);

ERROR:
System.NullPointerException: Attempt to de-reference a null object
  • July 22, 2021
  • Like
  • 0
public class Duplicate {
    public Account acc {set;get;}
    public Duplicate(){
        acc=new Account();
    }
    public PageReference create(){
        PageReference p;
        try{
          integer count=[select count() from Account where name=:acc.name];
              if(count>0){
                Apexpages.Message msg=new Apexpages.Message(Apexpages.Severity.ERROR,'Duplicate Record found');
                Apexpages.addMessage(msg);
               }
              else{
                insert acc;
                p=new PageReference('/'+acc.Id);
               }
             }
         catch(Exception e){
            Apexpages.Message msg=new ApexPages.Message(ApexPages.Severity.ERROR,e.getMessage());
            ApexPages.addMessage(msg);
        }
        return p;
    }
}
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
Hello, I build a List button that Includes a Visualforce Page. When I chose Accounts in List view and click account I only see the blank Page without the account fields. Please tell me how to change it.

<apex:page standardController="Account" renderAs="pdf" recordSetVar="accounts" >
 

<h1>Welcome to APP!</h1>
 
<p>Thank you, <b><apex:outputText value=" {!Account.Name}"/></b>, for 
   working with APP.</p>
 
<p>Your account details are:</p>
 
<table>
<tr><th>Account Name</th>
    <td><apex:outputText value="{!Account.Name}"/></td>
    </tr>
<tr><th>Account Rep</th>
    <td><apex:outputText value="{!Account.Owner.Name}"/></td>
    </tr>
<tr><th>Customer Since</th>
    <td><apex:outputText value="{0,date,long}">
        <apex:param value="{!Account.CreatedDate}"/>
        </apex:outputText></td>
    </tr>
</table>
    
</apex:page>

User-added image


Result:

User-added image
Hi Developer Community , 


Can u please write test class for this apex code
public class RSSFeedUtil {
    public static List<RSSObject> getGoogleRSSObjects(String theUrl) {
        List<RSSObject> returnList = new List<RSSObject>();
        
        Http h = new Http();
        HttpRequest req = new HttpRequest();        
        req.setEndpoint(theUrl);
        req.setMethod('GET');
        HttpResponse res = h.send(req);
        
        Dom.Document doc = res.getBodyDocument();
        Dom.XMLNode feed = doc.getRootElement();
        String namespace = feed.getNamespace();
        
        for(Dom.XMLNode child : feed.getChildElements()) {
            if(child.getName() == 'entry') {
                RSSObject returnListItem = new RSSObject(
                    child.getChildElement('title', namespace).getText().unescapeHtml4(),
                    child.getChildElement('link', namespace).getAttribute('href', ''),                    
                    child.getChildElement('content', namespace).getText().unescapeHtml4(),
                    child.getChildElement('published', namespace).getText()
                );
                System.debug(returnListItem);
                returnList.add(returnListItem);
            }
            System.debug(returnList);
        }
        return returnList;        
    }
}

Thanks in Advance
I have a requirement to get all the Project Ids of Resource under User Detail page.

Below is my Object Schema:
Parent: Project (Field: ProjectId)
Child: Timecard (Field: Project__c, Resource_Name__c)


Now, if the Resource Name under timecard matches with User Name, the Project Ids from that timecard should be stored on User detail page separated by a semicolon.
Below is my logic that I have achieved so far:
 
list<user> user = [SELECT  name from User where isactive = true]; 
list<string> str = new list<string>();
for(user u1 : user){
    str.add(u1.name);
}

List <Timecard__c> timecard = [
  SELECT ID,Project__c,resource_name__c  
  FROM Timecard__c 
  Where Resource_name__c = :str  and Project__c != null and Resource_Name__c != null];
            
    set<string> allProsset = new set<string>();
    for (Timecard__c timecards : timecard) {
      allProsset.add(timecards.Project__c);
    }
    list<string>allProsList = new list<string>(allProsset);
    list<User> userupdates = new list<user>();
    
    for(User us : user){
     
        us.Project_Ids__c = String.join(allProsList,';');
        userupdates.add(us);
        }
        
    update userupdates;

Now when i execute the above logic, Project Ids under User record is getting updated with some random Project IDs but not from the timecard where the User name is matching. Instead of pulling all the project Ids that the resource is working under, I am seeing some random project ids


Is there anyway that I can update user records with the exact project ids that matches resource name with user name in timecard under a project?


 
  • June 16, 2021
  • Like
  • 1
I'm new to aura components and I cannot figure out when I try to fire a component inside a callback function inside $A.getCallback() according to the documentation I get the error $A.getCallback() [Cannot read property 'setParam' of null]. I'm trying to fire the component inside a strophe.js hanlder function which is a callback function and only takes a single parameter.

LoginPanel.cmp
<aura:component description="Login panel for users to log into their CTI systems."  implements="c:panel">
    <ltng:require scripts="{!$Resource.Strophe}"/>
    <ltng:require scripts="{!$Resource.xml2json}"/>
    <!-- <ltng:require scripts="{!$Resource.jQuery}"/> -->



    <div class="slds-modal__container">
        <div class="logo">
            <img src="/staticresources/demoAdapterLogo.png" align="center"></img>
        </div>
        <div class="slds-form-element slds-p-bottom--medium">
            <label class="slds-form-element__label" for="text-input-01">Username</label>
            <div class="slds-form-element__control">
                <ui:inputText class="slds-input" aura:id="username"/>
            </div>
        </div>
        <div class="slds-form-element slds-p-bottom--medium">
            <label class="slds-form-element__label" for="text-input-01">Password</label>
            <div class="slds-form-element__control">
                <ui:inputSecret class="slds-input" aura:id="password"/>
            </div>
        </div>
        <div class="slds-form-element slds-p-bottom--medium">
            <label class="slds-form-element__label" for="text-input-01">Extension</label>
            <div class="slds-form-element__control">
                <ui:inputNumber class="slds-input" aura:id="extension"/>
            </div>
        </div>
        <button class="slds-button slds-button--brand" aura:id="submitButton" onclick="{!c.handleLogin}">Log In</button>
    </div>
</aura:component>
callInitiatedPanel.cmp
<aura:component description="panel that is shown on dialing, incoming or transferring calls before being connected that displays basic contact info for the call." implements="c:panel">
    <aura:attribute name="state" type="String" />
    <aura:attribute name="label" type="String" />
    <aura:attribute name="recordName" type="String" />
    <aura:attribute name="recordId" type="String" />
    <aura:attribute name="account" type="Object" />
    <aura:attribute name="title" type="String" />
    <aura:attribute name="phone" type="String" />
    <aura:attribute name="presence" type="String" description="Could be Available, Busy or Unavailable"/>
    <aura:handler name="init" value="{!this}" action="{!c.init}" />
    <div class="slds-panel">
        <!--  Top section: Information about the contact, including an avatar -->
        <div class="slds-panel__section">
            <div class="avatar slds-align--absolute-center">
                <div class="slds-avatar slds-avatar--circle slds-avatar--large">
                    <img src="/resource/slds/assets/images/avatar1.jpg" alt="Contact" />
                </div>
            </div>
            <div class="name slds-text-heading--large slds-text-color--weak slds-text-align--center">{!v.recordName}</div>
            <div class="slds-text-heading--x-small slds-text-color--weak slds-text-align--center companyDetails">{!v.account.Name}</div>
            <div class="slds-text-heading--x-small slds-text-color--weak slds-text-align--center companyDetails">{!v.title}</div>
            <div class="incoming slds-text-heading--x-small slds-text-color--weak slds-text-align--center">{!v.state}&nbsp;<ui:outputphone value="{!v.phone}" />...</div>
            <div class="slds-text-heading--x-small slds-text-color--weak slds-text-align--center"> <c:ticker /> </div>
        </div>
        
       <!--  Bottom section: End button on Dialing; Decline and Accept buttons on Incoming or Transferring -->
        <div class="bottom-panel slds-panel__section slds-align-bottom slds-grid">
            <aura:if isTrue="{! v.state == 'Dialing'}">
                <button class="slds-size--1-of-1 slds-button slds-button--destructive" onclick="{!c.end}">End</button>
                <aura:set attribute="else">
                    <button class="slds-size--1-of-2 slds-button slds-button--destructive" onclick="{!c.decline}">Decline</button>
                    <button class="slds-size--1-of-2 slds-button slds-button--brand" onclick="{!c.accept}">Accept</button>
                </aura:set>
            </aura:if>
        </div>
    </div>
</aura:component>

panel.intf
<aura:interface description="Demo Adapter Panel Interface, where every implementation is able to fire the events below.," >
    <aura:registerEvent name="renderPanel" type="c:renderPanel"/>
    <aura:registerEvent name="editPanel" type="c:editPanel"/>
    <aura:registerEvent name="getSettings" type="c:getSettings"/>
</aura:interface>


renderPanel.evt
 
<aura:event type="COMPONENT" description="Event fired to trigger panel rendering/transitioning.">
    <aura:attribute name="type" type="String" required="true" description="The type of panel component to create, e.g. c:ctiLoginPanel."/>
    <aura:attribute name="toast" type="Object" description="A toast to display on rendering. JS object consists of type (normal, success, warning, error) and a message"/>
    <aura:attribute name="attributes" type="Object" description="A map of attributes to send to the component."/>
</aura:event>

LoginPanelController.js
handleLogin: function(cmp, event, helper) {
    connection.connect('xyz.com', password, onConnect);

    var onConnect = setTimeout(() => {
    
    
        // works here 
        // cmp.getEvent('renderPanel').setParams({
        //     type : 'c:callInitiatedPanel',
        //     attributes : {
        //         'state' : 'Incoming',
        //         'recordName' : 'hammad',
        //         'phone' : 'phone',
        //         'title' : 'title',
        //         'account' : 'account',
        //         'recordId' : 'rid',
        //         'presence' : 'presence'
        //     }
        // }).fire()
    
    
    
        connection.send($pres({ to: PUBSUB_JID }).tree());
        connection.addHandler(function (msg) {
            var x2js = new X2JS();
    
            try {
    
                var text = msg['firstElementChild']['firstElementChild']['textContent'];
                var obj = x2js.xml_str2json(text);
                console.log("On Message : ", obj);
    
                window.setTimeout(
                    $A.getCallback(function () {
                        cmp.getEvent('renderPanel').setParams({
                            type: 'c:callInitiatedPanel',
                            attributes: {
                                'state': 'Incoming',
                                'recordName': 'abc',
                                'phone': 'phone',
                                'title': 'title',
                                'account': 'account',
                                'recordId': 'rid',
                                'presence': 'presence'
                            }
                        }).fire()
                    }), 1000
                );
    
    
            } catch (e) {
                console.log("Error: ", e)
            }
    
            return true;
    
        }, null, 'message', null, null, null);
    
    
    }, 1000)
    
}

 
When click on send mail button:
User-added image*************vf page******************
<apex:page Controller="wrapperClassController">
    <apex:form>
    <head>
       <apex:includescript value="https://code.jquery.com/jquery-1.11.1.min.js" / >
       <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/dt/dt-1.10.18/r-2.2.2/rg-1.0.3/sl-1.2.6/datatables.min.css"/>
       <script type="text/javascript" src="https://cdn.datatables.net/v/dt/dt-1.10.18/r-2.2.2/rg-1.0.3/sl-1.2.6/datatables.min.js"></script>
      <link type="text/css" href="//gyrocode.github.io/jquery-datatables-checkboxes/1.2.11/css/dataTables.checkboxes.css" rel="stylesheet" />
      <script type="text/javascript" src="//gyrocode.github.io/jquery-datatables-checkboxes/1.2.11/js/dataTables.checkboxes.min.js"></script>  
        <script>
          j$ = jQuery.noConflict();
         j$(document).ready(function () {
         var conTable = j$('[id$="contacttable"]').DataTable({
                   "pageLength": 50,
                   'columnDefs': [{
                   'targets': 0,
                        'checkboxes': {
                              'selectRow': true
                   },
                        "orderable": false 
                    }
                   ],

               'select': {
               'style': 'multi'
                     }
                  });

            });

        </script>

    </head>
       <apex:pageBlock>
        <apex:pageBlockButtons location="top">
               <apex:outputPanel layout="none" id="buttonsPanel">
                  <apex:commandButton value="send Mail" action="{!sendEmails}"> 
                </apex:commandButton> 
                <apex:commandButton value="Reset" action="{!reset}" immediate="true"/>
               </apex:outputPanel>      
            </apex:pageBlockButtons>
    <body>
        <table id="contacttable" class="display">
            <thead>
                <tr>
                    <th><apex:inputCheckbox/></th>
                    <th>Email</th>
                    <th>Name</th>
                    <th>Phone</th>
                </tr>
            </thead>
            <tbody>
                <apex:repeat value="{!cListWrapper}" var="c">
                    <tr>
                    <td><apex:inputCheckbox value="{!c.selected}" id="inputId"/></td>
                        <td>{!c.con.Email}</td>
                        <td>{!c.con.Name}</td>
                        <td>{!c.con.Phone}</td>
                    </tr>
                </apex:repeat>
            </tbody>
        </table>
     </body>
    </apex:pageBlock>        
   </apex:form>
 </apex:page>
***************************controller**********************
public class wrapperClassController {
       private String recordId;

    public Boolean selected {get; set;}
    public List<Contact> contactList {get;set;}
    public List<cWrapper> cListWrapper {get;set;}

    public wrapperClassController(){
        contactList = [SELECT Id, Name, Phone,Email FROM Contact WHERE AccountId=:recordId limit 1000];
        cListWrapper = new list<cWrapper>();

            for(Contact c: contactList) {
                cListWrapper.add(new cWrapper(c));
            }
    }    
    public class cWrapper {

        public Contact  con {get; set;}
        public Boolean selected {get; set;}


        public cWrapper(Contact  c) {
            con = c;
            selected = false;
        }
    }

    public PageReference reset() {
        PageReference pg = new PageReference(System.currentPageReference().getURL());
        pg.setRedirect(true);
        return pg;
    }

  public PageReference sendEmails(){
         List<Contact> selectedContacts = new List<Contact>();
         //System.debug('==>Inside sendEmail() '+ wrapperConsList);
        for(cWrapper c: cListWrapper) {
            if(c.Selected == true) {
                selectedContacts.add(c.con);

            }
        }
      // System.debug('toaddresses==>'+selectedContacts);
        String []toAddresses = new List<String>();
      //String[] toAddresses = new String[] {};
        
        for(Contact c : selectedContacts) {
            
            toAddresses.add(c.Email);
           
        }
       // System.debug('toaddresses==>'+toAddresses);
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        mail.setToAddresses(toAddresses);
        mail.setSubject('VF page created' );
        mail.setHtmlBody('This SF message!!!!!!   Thank you');
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] {mail});
        //update selectedContacts;
        return null;
    }  

}
 
  • June 03, 2021
  • Like
  • 1
Hi,

I am trying to build a formula in process builder where i need to check if the country's picklist value is either "United States" or "US" or "United States of America" but the thing is only United States is in the picklist(which is ok). But when i try to use the below formula in process builder i get a error message as shown below . Can someone help me out ?
Formula result is data type (Boolean), incompatible with expected data type (Text)




User-added image
ISPICKVAL([Deal_Registration__c].Country__c,"United States")||
ISPICKVAL([Deal_Registration__c].Country__c,"United States of America")||
ISPICKVAL([Deal_Registration__c].Country__c,"US")

 
Hi All,

Can you please help me in achieving the below requirement using Lightning web component.

To show a custom Label as Link and when clicked it has to show value from another custom Label 

Thanks,
Keerthana.
Below is my code. 

<aura:component >
    <aura:attribute name ="item" type= "Camping_Item__c" required="true"/>
    <p> Name : {!v.Camping_Item__c.Name__C} </p> 
    <P> PRICE :
        <lightning:formattedNumber Value="{!v.Camping_Item__c.Price__C}" style= "currency"/> </P> 
   <p> Quantity :
       <lightning:formattedNumber Value="{!v.Camping_Item__c.Quantity__C}" style= "integer " />   </p>
    <p>Packed : {!v.Camping_Item__c.Packed__C} </p>
    
    <lightning:input type = "toggle"
                     lable="Packed "
                     name="Packed"
                     checked="{!v.camping_item__c.Packed__C}"/>                                          
</aura:component>

I am recieving "We can't find the correct component or value for the Quantity field."  Any help is really appriciated. 
I am new to writing validation rules and am stuck.  I need to write a rule so that a person can not change a project status to active unless a picklist field called foundation type is filled out. This would only apply to projects that fall within certain departments.

User-added image
 

Hello,

I am stuck on a validation rule -

If Sub Category is either 'Attestation Form Complete' or 'Attestation Form Incomeplete', all the other fields listed must not be blank.

The current formula will not let me create the record even if all the fields listed are completed.  Any suggestions would be helpful.
 

Thanks!
User-added image

I keep getting the following error while running my Apex Test Class. If I could please get assistance in resolving the problem I would appreciate it. I continue getting the following error:

System.DmlException: Insert failed. First exception on row 0; first error: STRING_TOO_LONG, Alias: data value too large: Sminull90 (max length=8): [Alias]

Below is my code:

Apex Class:

public  class NewUtilStaffProcess {
       @future
       public static void createUtlUser(Id recid) {
            
           Contact gcon = [SELECT Email, Lastname, Firstname, Middlename, AcctId
                            FROM   Contact
                            WHERE  Id = :recid];
           
           Profile p = [SELECT Id FROM Profile WHERE Name='HAVNA City Public Utility Group'];
           
           Id acctsTypeId = [SELECT Id
                            FROM   RecordType
                            WHERE  SObjectType = 'Account'
                            AND    Name = 'Account Source'].Id;
           
           String groleId = [SELECT Id FROM UserRole WHERE Name = 'Utility Staff' LIMIT 1].Id;
           
           
           String formatUsrName;
           String setUsrLoc;
           
           Account retAcct = [SELECT Id, HAVNA_Country__r.HAVNA_Letter_Code__c, Hav_Locality__c, Hav_Street__c
                               FROM   Account
                               WHERE  Id = :gcon.AcctId
                               AND    recordTypeId = :acctsTypeId
                               LIMIT 1];
           
           if (retAcct.Hav_Street__c == 'Local/Surveyor')
              setUsrLoc = retAcct.HAVNA_Country__r.HAVNA_Letter_Code__c+retAcct.Hav_Locality__c;
        
           if (retAcct.Hav_Street__c == 'City/Surveyor')
              setUsrLoc = retAcct.HAVNA_Country__r.HAVNA_Letter_Code__c+'C1';
         
           if (retAcct.Hav_Street__c == 'State/Surveyor')
              setUsrLoc = retAcct.HAVNA_Country__r.HAVNA_Letter_Code__c+'C2';
        
             
           if (gcon.middlename == null) {
               formatUsrName = gcon.Lastname.deleteWhitespace().toLowercase().trim()+'.'+gcon.Firstname.deleteWhitespace().toLowercase().trim()+'.cnastaff'+setUsrLoc+'@HAVNA.gmail';
           } else {
               Integer midSize = gcon.Middlename.length();
               if (midSize == 1) {
                   formatUsrName = gcon.Lastname.deleteWhitespace().toLowercase().trim()+'.'+gcon.Firstname.deleteWhitespace().toLowercase().trim()+'.'+gcon.middlename.deleteWhitespace().toLowercase().trim()+'.cnastaff'+setUsrLoc+'@HAVNA.gmail';
               } else {
                   formatUsrName = gcon.Lastname.deleteWhitespace().toLowercase().trim()+'.'+gcon.Firstname.deleteWhitespace().toLowercase().trim()+'.'+gcon.middlename.deleteWhitespace().trim().substring(0,1).toLowercase()+'.cnastaff'+setUsrLoc+'@HAVNA.gmail';
               }    
           }

           System.debug('Formatted Username: '+formatUsrName);
      
           User u       = new User(Alias    = gcon.Lastname.deleteWhitespace().trim().length() > 4 ? gcon.Lastname.deleteWhitespace().trim().substring(0,3)+setUsrLoc: gcon.lastname+setUsrLoc,
                         Email              = gcon.Email,
                         EmailEncodingKey   = 'UTF-8',
                         LastName           = gcon.Lastname,
                         FirstName          = gcon.Firstname,
                         MiddleName         = gcon.Middlename,         
                         LanguageLocaleKey  = 'en_US',
                         LocaleSidKey       = 'en_US',
                         ProfileId          = p.Id,
                         UserRoleId         = groleid,          
                         TimeZoneSidKey     = 'America/New_York',
                         UserName           = formatUsrName);
          
           Insert(u);
           System.debug(u.id);
           
           UtilStaffPermSet.assgnPermissionSet(recId, u.Id);  
           System.resetPassword(u.Id, True);

      }
}

Apex Test Class:

@isTest
public class NewUtilStaffProcessTest {

   public static testMethod void InitialTest() {

        /* Get Record Id Type */   
        Id conTypeId;
        Id acctTypeId;
        String formatUsrName;
        String setUsrLoc;
        
        conTypeId = [SELECT Id  
                     FROM   RecordType
                     WHERE  SObjectType = 'Contact'
                     AND    Name = 'Utility Staffer'].Id;  

       
        Id acctsTypeId = [SELECT Id
                      FROM   RecordType
                      WHERE  SObjectType = 'Account'
                          AND    Name = 'Account Source'].Id;

        Profile p = [SELECT Id FROM Profile WHERE Name='HAVNA City Public Utility Group'];
        String groleId = [SELECT Id FROM UserRole WHERE Name = 'Utility Staff' LIMIT 1].Id;

        Integer midsize;
       
        //Create new State record; initialize required field(s), then insert
        HAV_State_and_Country__c state  = new HAV_State_and_Country__c();
        state.Name                = 'Oregon';
        state.HAV_Letter_Code__c = 'OR';
        state.HAV_Type__c        = 'State';
        Insert state;
        
        //Create new Account record; initialize required field(s), then insert
        Account acct = new Account(Name='Oregon Local 7');
        acct.Hav_Locality__c     = '90';
        acct.Hav_Street__c     = 'Local/Surveyor';
        acct.RecordTypeId     =  AcctTypeId;
        acct.HAV__Country__c    = state.id;
    insert acct;

        //Create new Contact record; initialize required field(s), then insert
        Contact con  = new Contact();   
        con.FirstName       = 'Ralph';  
        con.LastName        = 'Smith';
        con.Middlename      = 'Otis';
        con.RecordTypeId    =  conTypeId;
        con.email           = 'rsmith8@verizon.com';
        con.AcctId          = acct.id;
          
        //Insert Contact
        Insert con ;
       
          System.debug(con.id);
 
       Account retAcct = [SELECT Id, HAV_Country__r.HAV_Letter_Code__c, Hav_Locality__c, Hav_Street__c
                          FROM   Account
                          WHERE  Id           = :con.AcctId
                          AND    recordTypeId = :nomsTypeId
                          LIMIT 1];
                          
       if (retAcct.Hav_Street__c == 'Local/Surveyor')
              setUsrLoc = retAcct.HAV_Country__r.HAV_Letter_Code__c+retAcct.Hav_Locality__c;
 
       if (con.middlename == null) {
           System.debug('3: '+setUsrLoc);
               formatUsrName = con.Lastname.deleteWhitespace().toLowercase().trim()+'.'+con.Firstname.deleteWhitespace().toLowercase().trim()+'.cnastaff'+setUsrLoc+'@HAVNA.gmail';
           } else {
               System.debug('4: '+setUsrLoc);
               midSize = con.Middlename.length();
               if (midSize == 1) {
                   System.debug('5: '+setUsrLoc);
                   formatUsrName = con.Lastname.deleteWhitespace().toLowercase().trim()+'.'+con.Firstname.deleteWhitespace().toLowercase().trim()+'.'+con.middlename.deleteWhitespace().toLowercase().trim()+'.cnastaff'+setUsrLoc+'@HAVNA.gmail';
               } else {
                   System.debug('6: '+setUsrLoc);
                   formatUsrName = con.Lastname.deleteWhitespace().toLowercase().trim()+'.'+con.Firstname.deleteWhitespace().toLowercase().trim()+'.'+con.middlename.deleteWhitespace().trim().substring(0,1).toLowercase()+'.cnastaff'+setUsrLoc+'@HAVNA.gmail';
               }    
           }
           
 User thisUser = [SELECT Id FROM User WHERE Id = :UserInfo.getUserId()];
 system.runAs(thisUser){
         User u       = new User(Alias      = con.LastName.deleteWhitespace().trim().length() > 4 ? con.LastName.deleteWhitespace().trim().substring(0,4)+setUsrLoc: con.LastName+setUsrLoc,
                         Email              = con.email,
                         EmailEncodingKey   = 'UTF-8',
                         LastName           = con.LastName,
                         FirstName          = con.Firstname,
                         MiddleName         = con.Middlename,         
                         LanguageLocaleKey  = 'en_US',
                         LocaleSidKey       = 'en_US',
                         ProfileId          = p.Id,
                         UserRoleId         = groleid,          
                         TimeZoneSidKey     = 'America/New_York',
                         UserName           = formatUsrName);
          
           Insert(u);
           System.debug(u.id);  

                        
        Test.startTest();
       
        NewUtilStaffProcess.createUtlUser(con.id);
 
        Test.stopTest();
        system.debug('Done');
    }
     }
}

Thanks.
Trying to find out if i can rotate an image once the visualforce page is rendered as a PDF, when it is rendered as HTML the image shows correctly the way you take the image also the css below works with it on HTML but not PDF which is strange because the other style is working for the page when it is in PDF. 
<style type="text/css" media="print">
			@page {
				size: landscape
			}
.imageClass {
				-webkit-transform: rotate(90deg);
				-moz-transform: rotate(90deg);
				-o-transform: rotate(90deg);
				-ms-transform: rotate(90deg);
				transform: rotate(90deg);
				height: 200px;
				width: 200px;
			}

<img src="{!'/sfc/servlet.shepherd/version/download/' + Document_Id__c}" alt="before photo" class="imageClass"


-webkit-transform: rotate(90deg);
-moz-transform: rotate(90deg);
-o-transform: rotate(90deg);
-ms-transform: rotate(90deg);
transform: rotate(90deg);
I am parsing JSON that is coming back from  REST callout, and when running, it is throwing this error: attempt to de-reference null object. The issue seems to be with how I am parsing the JSON, but I am not sure where I am going wrong. Can someone help?

Here is the snippet of the JSON I am parsing:
"result": {
"first_name": "JOHN",
"last_name": "SMITH",
"id_type": "MI",
"subscriber_id": "1234567",
"gender": "M",
"birthdate": "19601119",
"address": {
"info": "123 Main St.",
"city": "New York",
"state": "NY",
"zip_code": "100000"
},
"county:": {
"value": "14"
},
"office": {
"value": "H78"
},
"recert_month": {
"value": "12",
"name": "December"
},
"dates": [
{
"name": "Service",
"qualifier": "472",
"date": "2020-09-29"
},
{
"name": "Plan Begin",
"qualifier": "346",
"date": "2020-09-01"
},
{
"name": "Issue",
"qualifier": "102",
"date": "2020-06-01"
}
],


Here is how I am parsing it (bold part is causing error):
  
        Map<String, Object> wholeResponse = (Map<String, Object>) JSON.deserializeUntyped(response2.getBody());
            Map<String, Object> result = (Map<String, Object>) wholeResponse.get('result');
                Map<String, Object> residentAddress = (Map<String, Object>) result.get('address');
                   Map<String, Object> county = (Map<String, Object>) result.get('county');
                  Map<String, Object> office = (Map<String, Object>) result.get('office');
                 Map<String, Object> recert_month = (Map<String, Object>) result.get('recert_month');
        
       Eligibility__c newEligRec = new Eligibility__c(); 
        newEligRec.Referral_Name__c = ref.id;
        newEligRec.First_Name__c = string.valueof(result.get('first_name'));
        newEligRec.Last_Name__c = string.valueof(result.get('last_name'));
        newEligRec.Name_Id_Type__c = string.valueof(result.get('id_type'));
        newEligRec.Client_ID__c = string.valueOf(result.get('subscriber_id'));
        newEligRec.Gender__c = string.valueOf(result.get('gender'));
        string birthdate;
              if (string.valueof(result.get('birthdate')) != null){
                  birthdate = string.valueof(result.get('birthdate')).remove('-');
                  string year = birthdate.substring(0,4);
                  string month = birthdate.substring(4,6);
                  string day = birthdate.substring(6,8);
                 birthdate = month + '/' + day + '/' + year;
                    }
        newEligRec.Date_of_Birth__c = birthdate;
        newEligRec.Address_Number_and_Street__c = string.valueOf(residentAddress.get('info')); 
        newEligRec.City__c =  string.valueOf(residentAddress.get('city'));    
        newEligRec.State__c =  string.valueOf(residentAddress.get('state'));    
        newEligRec.Zip_Code__c = string.valueOf(residentAddress.get('zip_code'));
        newEligRec.County__c = string.valueOf(county.get('value'));
        newEligRec.Office__c = string.valueOf(office.get('value'));
        newEligRec.Recertification_Month_value__c = string.valueOf(recert_month.get('value'));
        newEligRec.Recertification_Month__c = string.valueOf(recert_month.get('name'));
Hi,
I am having trouble with my Visualforce page and Apex Class. Everything seems to be fine apart from the error Unknown Property 'NFOSDisplayDivisions2Controller.Division_Space2__c'. I can't seem to figure out what is going on, could someone please help me out. Thank you.

Apex Class:
public with sharing class NFOSDisplayDivisions2Controller {
    
    public List<DivisionWrapper> listDivisionWrapper{get;set;}
    public List<Division_Space2__c> selectedDivisions{get;set;}

    public NFOSDisplayDivisions2Controller ()
    {
            listDivisionWrapper = new List<DivisionWrapper>();
            searchRecord();
    }
    
    public void searchRecord()
    {
        listDivisionWrapper.clear();
            for(Division_Space2__c a: [select Id, Name,Number_of_Competitors__c, Availability__c, RecordTypeID ,Active__c from Division_Space2__c limit 30]) 
            {
                listDivisionWrapper.add(new DivisionWrapper(a));
            }
    }

    public void processSelected() 
    {
        selectedDivisions = new List<Division_Space2__c>();
        selectedDivisions.clear();
        for(DivisionWrapper wrapDivisionObj : listDivisionWrapper) 
        {
            if(wrapDivisionObj.selected == true) 
            {
                selectedDivisions.add(wrapDivisionObj.acc);
                // Here you can add the counter or you check the selectedAccounts.size()
            }
        }
    }

    public void ActivateData() 
    {
        for(Division_Space2__c acc : selectedDivisions )
        {
            acc.Active__c= true;
        }
        update selectedDivisions ;
        searchRecord();
    }

    public void DeActivateData() 
    {
        for(Division_Space2__c acc : selectedDivisions )
        {
            acc.Active__c = false;
        }
        update selectedDivisions ;
        searchRecord();
    }
    


    // This is our wrapper/container class. 
    public class DivisionWrapper 
    {
        public Division_Space2__c acc {get;set;}
        public Boolean selected {get;set;}
        public DivisionWrapper(Division_Space2__c a) 
        {
            acc = a;
            selected = false;
        }
    }

}

Visualforce Page:
<apex:page controller= "NFOSDisplayDivisions2Controller">
    
<script type="text/javascript">
        function selectAllCheckboxes(obj,receivedInputID){
            var inputCheckBox = document.getElementsByTagName("input");
            for(var i=0; i<inputCheckBox.length; i++){
                if(inputCheckBox[i].id.indexOf(receivedInputID)!=-1){
                    inputCheckBox[i].checked = obj.checked;
                }
            }
        }
    </script>
    <apex:form >
        <apex:pageBlock id="PB1">
            <apex:pageBlockButtons >
                <apex:commandButton value="Add to Grid" action="{!processSelected}" rerender="table2,PB2"/>
            </apex:pageBlockButtons>

            <apex:pageblockSection title="Division Types" collapsible="false" columns="1">
                <apex:pageBlockTable value="{!listDivisionWrapper}" var="accWrap" id="table" title="Division Types">
                    <apex:column >
                        <apex:facet name="header">
                            <apex:inputCheckbox onclick="selectAllCheckboxes(this,'inputId')"/>
                        </apex:facet>
                        <apex:inputCheckbox value="{!accWrap.selected}" id="inputId"/>
                    </apex:column>
                    <apex:column value="{!Division_Space2__c.acc.Name}" />
                    <apex:column value="{!Division_Space2__c.acc.Number_of_Competitors__c}" />
                    <apex:column value="{!Division_Space2__c.acc.Availability__c}" />
                    <apex:column value="{!Division_Space2__c.acc.Active__c}" />
                </apex:pageBlockTable>


            </apex:pageblockSection>
        </apex:pageBlock>
        
        <apex:pageBlock id="PB2" >
            <apex:pageBlockButtons >
                <apex:commandButton value="Activate" action="{!ActivateData}" rerender="PB1,PB2"/>
                <apex:commandButton value="DeActivate" action="{!DeActivateData}" rerender="PB1,PB2"/>
            </apex:pageBlockButtons>

                <apex:pageBlockTable value="{!selectedDivisions}" var="c" id="table2" title="Selected Divisions">
                    <apex:column value="{!c.Name}" headerValue="Division Type"/>
                    <apex:column value="{!c.Number_of_Competitors__c}" headerValue="Number of Competitors"/>
                    <apex:column value="{!c.Availability}" headerValue="Availability"/>
                    <apex:column value="{!c.Active__c}" headerValue="Active"/>
                </apex:pageBlockTable>
        </apex:pageBlock>

        
    </apex:form>
</apex:page>
Can someone help me with a report formula?  How can I get a net of the PAYMENT - REFUND for each payment type?   



User-added image
trigger Opps_trigger1 on Opportunity (after insert) {
List<Contact>conlist=new List<Contact>();
List<Opportunity>oppslist=new List<Opportunity>([SELECT Id,Name,CloseDate FROM Opportunity WHERE AccountID IN:Trigger.new]);
for(Opportunity o:Trigger.new)
{
c.AccountID=o.AccountID;
c.FirstName='aryan';
c.LastName='jha';
conlist.add(c);
}
insert conlist;
}