+ Start a Discussion
Sowmya YakkalaSowmya Yakkala 
Hi i want to display the data in newline and i tried with <br/> and </n> but it was not working. And my code is

for( Opportunity oppLst : [Select Id,Name,Cart_Grand_Total__c, (Select Product_SKU__c,DeliveryDate__c from  Shopping_cart_line_items__r where DeliveryDate__c >Today )
                                 from Opportunity where AccountId =:accountId  and  StageName='Closed Won' ])
       {
             for(Shopping_cart_line_item__c scL : oppLst.Shopping_cart_line_items__r){
              DateTime DeliveryDate = scL.DeliveryDate__c;
              upcmngDeleviries += DeliveryDate.format('MM/dd/yyyy')+'\n';
          }
           upcmngDeleviries +='$'+oppLst.Cart_Grand_Total__c +'\n';
       }
       return upcmngDeleviries ;

Actual Output: 01/23/2020 $660.29 01/22/2020 01/22/2020 $1373.84

Expected Output : 01/23/2020 $660.29
                              01/22/2020 01/22/2020 $1373.84
Best Answer chosen by Sowmya Yakkala
Maulik D ShahMaulik D Shah
Hello Sowmya,

Include a line break within a String with the use of '< br/>' and displaying it on the component as follows
<aura:unescapedHtml value="{!v.yourString}" />

https://developer.salesforce.com/docs/component-library/bundle/aura:unescapedHtml/specification

I hope this helps you.
Wesley HWesley H 
We are attempting to move a simple Apex Class and Apex Test Class from Sandbox to Production, and blocked by Code Coverage Failure error. Our Code Coverage is showing 100% in Production (via Developer Console), yet we are seeing a Code Coverage Failure Error (coverage = 33%) even on "Validate" (not "Deploy") of non-apex change set. We have followed instructions in Knowledge Article 000335222 (https://help.salesforce.com/articleView?id=000335222&type=1&mode=1) carefully to reset Code Coverage numbers and are still seeing the above error on validation of non-apex change set as well as on attempt to deploy an apex-loaded change set including test class. Apex Class and Apex Test Class code below for reference, any help greatly appreciated!
 
Public class AutoConvertLeads
{
    @InvocableMethod
    public static void LeadAssign(List<Lead> LeadIds)
    {
        LeadStatus CLeadStatus= [SELECT Id, MasterLabel FROM LeadStatus WHERE IsConverted=true Limit 1];
        List<Database.LeadConvert> MassLeadconvert = new List<Database.LeadConvert>();
        for(Lead currentlead: LeadIds){
                Account[] matchedaccount = [SELECT Id, Name FROM Account WHERE Name=:currentlead.Company LIMIT 1];
                if(matchedaccount.size() > 0) {
                Database.LeadConvert Leadconvert = new Database.LeadConvert();
                Leadconvert.setLeadId(currentlead.id);                
                Leadconvert.setConvertedStatus(CLeadStatus.MasterLabel);
                Leadconvert.setDoNotCreateOpportunity(TRUE); //Remove this line if you want to create an opportunity from Lead Conversion
                Leadconvert.setAccountId(matchedaccount[0].id);
                MassLeadconvert.add(Leadconvert);
                }
        }
        
        if (!MassLeadconvert.isEmpty()) {
            List<Database.LeadConvertResult> lcr = Database.convertLead(MassLeadconvert);
        }
    }
}

And Test Class:
@isTest 
      public class TestAutoConvertLeads{
      static void createnewlead(){
      User userToCreate = [SELECT id FROM user WHERE profile.name='System Administrator' Limit 1];
      
      Test.startTest();    
      Lead leadToCreate =new Lead();
      List<Lead> LeadIds= New List<Lead>();
      leadToCreate.ownerid= userToCreate.id;
      leadToCreate.LastName ='Gupta';
      leadToCreate.Company='Salesforce';
      insert leadToCreate; 
      LeadIds.add(leadToCreate);
      
      LeadStatus CLeadStatus = new LeadStatus();
      
      Account AccountToCreate = new Account();
      AccountToCreate.ownerid= userToCreate.id;
      AccountToCreate.Name = 'Salesforce';
      insert AccountToCreate; 
      
      AutoConvertLeads.LeadAssign(LeadIds);
      
      Test.stopTest();
   }
}

 
Best Answer chosen by Wesley H
Wesley HWesley H
@Abdul, Development Mode NOT checked (and wasn't before).

@Andrew, thanks, but already been down that road.

However...I found the issue: somehow my test class was missing a test method (line 3 of my test code above), so it was passing with 0/0 tests in sandbox (100%!) but bombing in the change set to Production. I fixed line 3 to read, "static testMethod void createnewlead(){" and I got 1/1 tests (also 100%) in sandbox and a flawless deployment to Production. Sorry that was so elementary, but thank you all for your help!
Sakthi KuppusamySakthi Kuppusamy 
Hello, I am playing with @future method with below code

public class AccountProcessor {
@future
  public static void countContacts(List<Id> recordIds) {
       string AcName = 'United Oil & Gas%';
       List<AggregateResult> ct_contacts = [Select AccountId, Count(Name) from Contact Where Account.Name Like :AcName group by AccountId ];
       List<Account> Upd_Account = new List<Account>();
       
       system.debug('Count - ' + ct_contacts.size());
      
        for (AggregateResult ar : ct_contacts)  {
            Account acc = new Account();
            acc.Id = ((Id)ar.get('AccountId'));
            acc.Number_of_Contacts__c = ((Integer)ar.get('expr0'));
            Upd_Account.add(acc);
            
        }
      update Upd_Account;
  }
}

and below test calss

@IsTest
public class AccountProcessorTest {
      @IsTest
      private static void testAccountProcessor() {
        Id myId1 = Id.valueOf('0016g000007qSglAAE');
        Id myId2 = Id.valueOf('0016g000007qSgmAAE');
        List<Id> MyList =new List<Id>();
        MyList.add(myId1);
        MyList.add(myId2);
                  
        Test.startTest();
          AccountProcessor.countContacts(MyList);
        Test.stopTest();
          
        // runs callout and check results
        List<AggregateResult> logs = [Select AccountId, Count(Name) from Contact Where AccountId IN :MyList group by AccountId];
        System.assertEquals(0, logs.size());
      }
}

My code is not gettign 100% coverage i treid removing @future as well but it is not executing the SOQL..

Select AccountId, Count(Name) from Contact Where Account.Name Like :AcName group by AccountId

I beleive it is not able to substitute the variable.

14:00:17:006 SOQL_EXECUTE_BEGIN [4]|Aggregations:0|SELECT AccountId, COUNT(Name) FROM Contact WHERE Account.Name LIKE :tmpVar1 GROUP BY AccountId

Is there any lilitation for using AggregateResult?

Thanks,
Sakthi
Best Answer chosen by Sakthi Kuppusamy
Abdul KhatriAbdul Khatri
No, First of all never hard code anything specially the 18 characters Id. Best practise is that you need to build you test data and then use that as I am showing you in this example. I have commented your code instead of deleting them so that you can see the difference. This should give you 100% code coverage.
 
    @IsTest
    private static void testAccountProcessor()
    {
        string AcName = 'United Oil & Gas%';
        List<Contact> contToInsertList = new List<Contact>();
        
        Account acct = new Account(Name = AcName);
        insert acct;
               
        Contact contact1 = new Contact(FirstName = 'FN', LastName = 'LN', AccountId = acct.Id);
        Contact contact2 = new Contact(FirstName = 'FN2', LastName = 'LN2', AccountId = acct.Id);
        contToInsertList.add(contact1);
        contToInsertList.add(contact2);
        
        Insert contToInsertList;
        
        //Id myId1 = Id.valueOf('0016g000007qSglAAE');
        //Id myId2 = Id.valueOf('0016g000007qSgmAAE');
        List<Id> MyList =new List<Id>{contact1.Id, contact2.Id};
        //MyList.add(myId1);
        //MyList.add(myId2);
                  
        Test.startTest();
          AccountProcessor.countContacts(MyList);
        Test.stopTest();
          
        // runs callout and check results
        List<AggregateResult> logs = [Select AccountId, Count(Name) from Contact Where AccountId IN :MyList group by AccountId];
        System.assertEquals(0, logs.size());
    }

 
Shilpa SrikantacharShilpa Srikantachar 
Hi All ,
I'm getting the Execute Anonymous Error

Line: 1, Column: 18
Constructor not defined: [Employee_Info].<Constructor>(String, Integer
public class Employee_Info {
    

when the following code is run :


    public String name;
        public Integer exp;
        public Decimal salary;
        public Decimal bonus;
        public Employee_Info(String empName,Integer empExp){
            name=empName;
            exp=empExp;
        }
        public void invoke(){
            if(exp > 5){
                salary=50000;
                bonus=5000;
            }else{
                salary=30000;
                bonus=3000;
            }
        }
        public void show(){
            System.debug('Name :'+name);
            System.debug('Exp :'+exp);
            System.debug('Salary:'+salary);
            System.debug('Bonus:'+bonus);
        }
    }

Pls let me know how to fix it .

Thanks
Shilpa
Best Answer chosen by Shilpa Srikantachar
Puru GangwarPuru Gangwar
It Works...make sure you are passing value in constructer as you have not defiened default constructor.

Employee_Info EI = new Employee_Info('Test', 10);
EI.Invoke();
EI.Show();
As a best practice, local varriable should be defined as Private.
StephenDicksonStephenDickson 
I created a trigger to update a custom field (Mailing County) before insert of a Contact.  The trigger takes the MailingPostalCode entered by the user and finds the County in which that zip code is found.  This is done via a custom object (Zip_Code__c) in which the Postal Codes are stored along with their respective Counties.

I would love any feedback on how to make this trigger better, but specifically I am confused because one of my test methods is not working (TestContactWithValidZip).  This particular test gets caught by my addError clause of my trigger.

Trigger:
trigger CountyLookupByZip on Contact (before insert) {
    for (Contact c : Trigger.New) {
        if(c.MailingPostalCode != null) {
        	List<Zip_Code__c> contactCounty = new List<Zip_Code__c>();
            contactCounty = [SELECT Id,
                                County__c,
                                Postal_Code__c
         				 FROM   Zip_Code__c 
        			     WHERE  Postal_Code__c = :c.MailingPostalCode];
            if(contactCounty.size() != 0){
            	c.Mailing_County__c = contactCounty[0].County__c;
            } else {
                c.MailingPostalCode.addError('Postal Code not found. Please ensure the postal code is a valid Virginia zip code.');
            }
        }
	}
}
Test Clas:
@isTest
public class TestCountyLookupByZip {

    @isTest
    public static void TestContactWithNullZip() {
        // Test data setup
        // Create a contact without a Mailing Postal Code
        // and check to ensure County is also null
        Contact contactNullZip = new Contact(LastName = 'Test');
        insert contactNullZip;
        
        // Perform Test
        System.assertEquals(contactNullZip.Mailing_County__c, null);
    }

    @isTest
    public static void TestContactWithValidZip() {

        // Test data setup
        // Create a contact with a valid VA Mailing Postal Code
        // and check to ensure County is updated correctly
        
    	Contact contactValidZip = new Contact(LastName = 'Test', MailingPostalCode = '20101');
        insert contactValidZip;
        
        // Perform Test
        System.assertEquals(contactValidZip.Mailing_County__c, 'Loudoun');
    }   
    
    @isTest
    public static void TestContactWithInvalidZip() {
        // Test data setup
        // Create a contact with an invalid Mailing Postal Code
        // and throw an error
        Test.startTest();
        try {
       		Contact contactInvalidZip = new Contact(LastName = 'Test', MailingPostalCode = '17602');
        	insert contactInvalidZip;
        // Perform Test
        } catch(Exception e) {
			System.Assert(e.getMessage().contains('FIELD_CUSTOM_VALIDATION_EXCEPTION'));
            System.Assert(e.getMessage().contains('Postal Code not found. Please ensure the postal code is a valid Virginia zip code.'));
        }
        Test.stopTest();
    }
}


 
Best Answer chosen by StephenDickson
Andrew GAndrew G
Hi Stephen
You still get the error as you have not re-queried the record that you have created.  
If you go to this thread  https://developer.salesforce.com/forums/ForumsMain?id=9062I000000IKZFQA4
and search for "why we grab the written record in our Apex Test Classes" you will see a post that will explain what is required and why.

But if you want the short version, update your method to:
@isTest
    public static void TestContactWithValidZip() {

        // Test data setup
        // Create a contact with a valid VA Mailing Postal Code
        // and check to ensure County is updated correctly
        Zip_Code__c zipCode = new Zip_Code__c(Postal_Code__c = '20101', County__c = 'Loudoun');
        insert zipCode;
        
    	Contact contactValidZip = new Contact(LastName = 'Test', MailingPostalCode = '20101');
        insert contactValidZip;
        Contact insertedContact = [SELECT Id, Mailing_County__c FROM Contact WHERE Id = :contactValidZip.Id  LIMIT 1];
        
        // Perform Test
        //general format for asserts is expected v actual so 
        System.assertEquals('Loudoun', insertedContact.Mailing_County__c, );
    }

Regards
Andrew
Md. Abdur Razzak.Md. Abdur Razzak. 

I am trying to pass the Einstein Analytics Data Preparation Specialist challenge#3 but got the following error -

 

Challenge Not yet complete... here's what's wrong:
We can't find the 'Create Seed Bank Agencies' node or required fields are missing. Check the challenge and confirm the node name, alias, and required fields.

can anyone please help me to overcome the issue. here are my files


User-added image
User-added image
{
  "Filter Agency Records": {
    "action": "filter",
    "parameters": {
      "filter": "IsAgency:EQ:TRUE",
      "source": "ID Agency Records"
    }
  },
  "Load Account": {
    "action": "sfdcDigest",
    "parameters": {
      "fields": [
        {
          "name": "AccountNumber"
        },
        {
          "name": "Name"
        },
        {
          "name": "Phone"
        },
        {
          "name": "ShippingCity"
        },
        {
          "name": "ShippingCountry"
        },
        {
          "name": "ShippingPostalCode"
        },
        {
          "name": "ShippingState"
        },
        {
          "name": "ShippingStreet"
        }
      ],
      "object": "Account"
    }
  },
  "Create Seed Bank Agencies": {
    "action": "sfdcRegister",
    "parameters": {
      "name": "Seed Bank Agencies",
      "alias": "seed_bank_agencies",
      "source": "Filter Agency Records"
    }
  },
  "Add Agency Fields": {
    "action": "augment",
    "parameters": {
      "right_key": [
        "AccountNumber"
      ],
      "left": "Load Account",
      "left_key": [
        "AccountNumber"
      ],
      "right_select": [
        "Acres",
        "Currency",
        "Latitude",
        "Longitude",
        "Region",
        "SubRegion"
      ],
      "right": "Load Agency Detail",
      "relationship": "AgencyDetails",
      "operation": "LookupSingleValue"
    }
  },
  "Load Agency Detail": {
    "action": "edgemart",
    "parameters": {
      "alias": "Agency_Detail"
    }
  },
  "ID Agency Records": {
    "action": "computeExpression",
    "parameters": {
      "source": "Add Agency Fields",
      "mergeWithSource": true,
      "computedFields": [
        {
          "name": "IsAgency",
          "saqlExpression": "case when Phone is not null then \"TRUE\" else \"FALSE\" end",
          "label": "IsAgency",
          "type": "Text"
        }
      ]
    }
  }
}

Best Answer chosen by Md. Abdur Razzak.
Md. Abdur Razzak.Md. Abdur Razzak.
The problem was in 'Latitude', 'Longitude' field in 'Agency Detail' dataset. 
Whiile I was uploading the 'Agency Detail' file, I was changing the 'Latitude', 'Longitude' fields from 'Measure' to 'Dimension' as it should be. But to pass this challeng they have to be 'Measure' as they were by default.
shailja ranjan 8shailja ranjan 8 
Hello, 

I am learning salesforce and quite new to it. can any one pls help me out in trigger design pattern  and frameworks. I am bit confused in this?
Best Answer chosen by shailja ranjan 8
Devi ChandrikaDevi Chandrika (Salesforce Developers) 
Hi shailja,
Here are some trigger best practices
1)Always there should be only one trigger for each object
2)Avoid SOQL Queries or DML statements inside FOR Loops
3)Execute DML statements using collections instead of individual records per DML statement.
4)Avoid complex logic in triggers.Use trigger Handler.
5)Trigers should be "bulkified" and be able to process up to 200 records for each call.

Please refer below links which might help you in this
https://developer.salesforce.com/page/Apex_Code_Best_Practices
http://amitsalesforce.blogspot.com/2015/06/trigger-best-practices-sample-trigger.html
https://developer.salesforce.com/page/Apex_Design_Patterns
https://developer.salesforce.com/forums/?id=906F0000000DBl8IAG

Hope this helps you
If this helps kindly mark it as solved so that it may help others in future.

Thanks and Regards
kavya mareedukavya mareedu 
global class OTFAutomationReport implements Database.Batchable<sObject> {
    global Database.QueryLocator start(Database.BatchableContext bc)
    {
        //String query = 'select Id,OTF_Total_Hours__c,OTFClient__c, OTF_Date__c, (select Date__c, Duration_Hours__c from Time_Logs__r) from account where Name='+80 Acres Farms+';
       
        
        system.debug('==query==>' +[select Id,OTF_Total_Hours__c,OTFClient__c, OTF_Date__c, (select Date__c, Duration_Hours__c from Time_Logs__r) from account where Name='80 Acres Farms']);
        return Database.getQueryLocator([select Id,OTF_Total_Hours__c,OTFClient__c, OTF_Date__c, (select Date__c, Duration_Hours__c from Time_Logs__r) from account where Name='80 Acres Farms']);
       
    }
    global void execute(Database.BatchableContext bc, List<account> scope)
    {
        system.debug('==scope==>' +scope);
        //decimal TotalHours=0.0;
        list<account> accUpdate = new list<account>();
        for(account a: scope)
           
        {
            a.OTF_Total_Hours__c=0.0;
            system.debug('a===>1st loop' +a);
            for(Time_Log__c tl : a.Time_Logs__r)
            { system.debug('a===>2nd loop' +tl);
            
                //system.debug('a==a.OTF_Total_Hours__c=>2nd loop' +a.OTF_Total_Hours__c);
             system.debug('a=tl.Duration_Hours__c==>2nd loop' +tl.Duration_Hours__c);
            
                if(tl.Duration_Hours__c!=NUll && a.OTF_Total_Hours__c!=Null){
                a.OTF_Total_Hours__c +=tl.Duration_Hours__c;
                system.debug('==TotalHours==>' +a.OTF_Total_Hours__c);
                if(a.OTF_Total_Hours__c>=20 && a.OTFClient__c==false)
                {
                    a.OTFClient__c=true;
                    system.debug('==a.OTFClient__c==>' +a.OTFClient__c);
                    a.OTF_Date__c=tl.Date__c;
                    accUpdate.add(a);
                }
                }
            }
           
            
        }
        system.debug('==accUpdate > ' +accUpdate);
        update accUpdate;
       
    }
    global void finish(Database.BatchableContext BC)
    {}   
    
}
 
Best Answer chosen by kavya mareedu
Raghu NaniRaghu Nani
Hi Below is the sample test class...
Please insert the data from test class and invoke the batch apex...

@isTest 
public class ExampleTestClass
{
    static testMethod void testMethod1() 
    {
      
      // create an account
        Account MyAccount = new Account(Name='Test');
        insert MyAccount;

     // Create a case on the test account
        date myDate = date.today();
        Account MyCase = new Account(Name='Test');
        MyCase.AccountId = MyAccount.Id;    
        insert MyCase;
        
        Test.startTest();
        BatchClassName batch = new BatchClassName();
        Database.executeBatch(batch );
        Test.stopTest();
      
    }
}
sagarrrrsagarrrr 
Create custom setting “ValidationSetting“. This custom setting should be used to activate/deactivate any Validation Rule from your org.
i have created validation rule but its not working.
User-added imageUser-added imagecan anyone help me thank you!!
Best Answer chosen by sagarrrr
Devi ChandrikaDevi Chandrika (Salesforce Developers) 
not in the field definition.
From setup--> custom settings --> click on manage next to validation setting -->new and create a record by giving checkbox as false 
John McAfeeJohn McAfee 
Test class below that was working perfectly is now failing with "Methods defined as TestMethod do not support Web service callouts" I have narrowed it down to the case insert line insert c; .  Is this a permissions issue on the case object ? all the other inserts work .

@isTest

public class DefaultEntitlementTest {
     static testmethod void ValidateDefaultEntitlementAction() {
        Account[] acc = new Account[] {
            new Account(Name='Test Account 1'),
            new Account(Name='Test Account 2')
        };
        insert acc;
       
        Contact[] contacts = new Contact[] {
            new Contact(FirstName='Test 1', LastName='McTesty', AccountId = acc[0].id),
            new Contact(FirstName='Test 2', LastName='McTesty', AccountId = acc[0].id)
        };
        insert contacts;
       
        Id entitlementProcessId = [SELECT Id FROM SlaProcess WHERE SObjectType = 'Case' LIMIT 1].Id;
       
        Entitlement[] ent = new Entitlement[] {
            new Entitlement (AccountId=acc[0].Id, SLAProcessId = entitlementProcessId, Name = 'Test Entitlement Account',
                                           StartDate = system.today(), EndDate = system.today()),
            new Entitlement (AccountId=acc[1].id, SLAProcessId = entitlementProcessId, Name = 'Test Entitlement Contact',
                                           StartDate = system.today().addDays(-1), EndDate = system.today().addDays(5))
        };
        insert ent;
       
        EntitlementContact ec = new EntitlementContact(ContactId = contacts[0].id, EntitlementId = ent[1].id);
        insert ec;
       
        Case c = new Case(AccountId = acc[0].id, ContactId = contacts[0].id, Subject='Test');
        insert c;
        
        List<Case> caseList = new List<Case>{c};
       
        DefaultEntitlementAction.updateDefaultEntitlements(caseList);
    }
}
 
Best Answer chosen by John McAfee
Abdul KhatriAbdul Khatri
Hi John,

Do you have a new code that is making http callout? That is impacting your existing test class, you need to update the Test class to make it work.

Here is the link for you reference

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_restful_http_testing_httpcalloutmock.htm