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


  • Chatter
    Feed
  • 336
    Best Answers
  • 3
    Likes Received
  • 9
    Likes Given
  • 15
    Questions
  • 1168
    Replies
HTML TEMPLATE
<template>
    <lightning-card title="Custom Search Functionality in LWC" icon-name="standard:account">
        <div if:true={errorMsg} style="margin-left: 3%;">
            <p style="color: red;">{errorMsg}</p>
        </div>
        <lightning-layout multiple-rows="true" vertical-align="end">
            <lightning-layout-item size="12" small-device-size="10" medium-device-size="8" large-device-size="6" padding="around-small">
                    <div class="slds-form-element">
                            <div class="slds-form-element__control">
                                    <lightning-input type="text" 
                                                     label="Enter Customer Name" name ="cusName"
                                                     onchange={handleCustomerName} ></lightning-input>
                            </div>
                        </div> 
            </lightning-layout-item>
            <lightning-layout-item size="12" small-device-size="2" medium-device-size="2" large-device-size="2" padding="around-small">
                    <lightning-button label="Search" 
                                      variant="brand" 
                                      onclick={handleSearch}></lightning-button>
                </lightning-layout-item>
            </lightning-layout><br/>
            <template if:true={show}>
                <div class="acc-container">
                    {recordId}
                    <lightning-record-view-form record-id={recordId} object-api-name="Client__c">
                        <div class="slds-grid">
                            <div class="slds-col slds-size_1-of-2">
                                <lightning-output-field field-name="Name"></lightning-output-field>
                                <lightning-output-field field-name="Date_of_Birth__c"></lightning-output-field>
                            </div>
                            <div class="slds-col slds-size_1-of-2">
                                <lightning-output-field field-name="Photo__c"></lightning-output-field>
                                <lightning-output-field field-name="Booking_Date__c"></lightning-output-field>
                            </div>
                        </div>
                    </lightning-record-view-form>
                </div>
            </template>
           
      
    </lightning-card>
</template>

js

import { LightningElement, track } from 'lwc';
import getDetail from '@salesforce/apex/PriceFetch.getDetail';
export default class ClientDefinition extends LightningElement {
    cusName;
    @track show = false;
    @track recordId;
    handleCustomerName(event) {
        this.cusName =  event.target.value;
    }
    handleSearch() {
       /* if(this.cusName.equals('')) {
            this.errorMsg = 'Please enter customer name to search.';
          
            return;
        }*/
        alert(this.cusName);
     
        getDetail({ clientName: this.cusName})
          
        
           .then(result => {
            this.show = true;
            alert(result);
            this.recordId = result;
           })
        
           .catch(error => {
                this.error = error;
                alert("FAILURE" + error);
                 //this.error = error;
           });
            
    }
}

Apex controllr class

public with sharing class PriceFetch {
  
    @AuraEnabled
    public static String getDetail(String clientName) {
       
        String search = '%' + clientName + '%';
       
       List<Client__c> clients = new List<Client__c>();
         clients = [
            SELECT Id, Name, Unit__c, Total_cost__c, Remarks__c, Project__c,Profession__r.Name,Photo__c,PAN__c,Father_Spouse__c,Email_id__c,
            Date_of_Birth__c,Contact_Number__c,Communication_address__c,Booking_Date__c,Booking_Amount__c,Agreement_Date__c,Aadhar_Number__c
            FROM Client__c
            WHERE Name LIKE :search
            LIMIT 1];
            if(clients.size() == 0) {
                 throw new AuraHandledException('exceptionText');
            }
            
           return clients.get(0).Id;
        
    }


 
}

Is there any mistake in my code?
Im not getting the recordId.
Hi Gurus,

Plz help in Writing a Test class for below scheduled apex class Mon Tue wed thu 7am
 
global class CopyERTBatchDaily Implements Schedulable
    {
        global void execute(SchedulableContext sc)
        {
            setERTBatch();
        }

        public void setERTBatch()
        {
            //List<Executive_RT> exeList = new List<Executive_RT>();
            List<Executive_RT> exeList = [select Case__c, Level_1__c, Level_2__c,Level_3__c  FROM Executive_RT];
             // process each batch of records
            List<Case_Type__c> listCTD = new List<Case_Type__c>();
        
        for(Executive_RT exe : exeList)
        {        
           	listCTD.add(new Case_Type__c(Case__c=exe.Case__c,Level_1__c=exe.Level_1__c,Level_2__c=exe.Level_2__c,Level_3__c=exe.Level_3__c));
            //System.debug('ERT Case No is =====>' +Case__c);
        }
        try {
        	
            insert listCTD;
        
        } catch(Exception e) {
            System.debug(e);
        }
            
        }
    }

Regards
Fiona​​​​​​​
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
I have a custom object which has a list of products, country field and checkbox- inactive.

Use case: 
When I create an opportunity and add OpportunityLineItem, The line item should compare with the products field from the custom object.
Also, the Opportunity should look at Bill to country from the account attached and compare with the country field from the custom object.
And if the record matches and the "Inactive" checkbox from the custom object is true, then it should throw an error and not allow to save the opportunity.

For example,
Custom object:
Product: Pencil
Country: Mexico
Inavtive: True

Opportunity:
OpportunityLineItem: Pencil
Account - Bill to Country: Mexico
ERROR FLAG

Can this be achievable ? If so, can i receive some help on building the trigger ?

Thank you in advance.
Hello! I'm a bit new at writing Apex but I'm attempting to create an invocablemethod batch apex class to rollup multiple currency fields on an "Order Package" object to its parent object of "Order Location". Everything seems to be working as expected but I need to rollup multiple fields and I'm running into issues. Can someone show me how I might be able to include multiple fields in the rollup? I attempted to simply add another field but right now it looks like it's assigning the same amount to both fields I included. This seems to be because I am assigning the same "results" to both fields but I can't figure out how I can assign the aggregate query to multiple fields. Any help is greatly appreciated!
 
global class OrderLocationRollupSummary implements Database.Batchable<sObject>, Schedulable {
    
        //Invocable Method
        @InvocableMethod(label='Rollup All Order Packages to Locations')
        global static void rollupAllorderpackages(List<Order_Location_Package__c> orderpackages) {
            rollupOrderPackages(orderpackages);
        }
    
        //Batchable Methods
        global Database.QueryLocator start(Database.BatchableContext bc) {
            return Database.getQueryLocator([SELECT Id FROM Order_New_Location__c]);
        }
    
        global void execute(Database.BatchableContext context, List<sObject> batch){
            Set<Id> OrderLocationIds = new Set<Id>();
    
            for (sObject ordloc : batch) {
                OrderLocationIds.add(ordloc.Id);
            }
    
            summarizeOrderPackages(OrderLocationIds);
        }
    
        global void finish(Database.BatchableContext context) {}
    
        //Schedulable Methods
        global void execute(SchedulableContext context){
            OrderLocationRollupSummary batchJob = new OrderLocationRollupSummary();
            Database.executeBatch(batchJob);
        }
    
        //Static Methods
        public static void rollupOrderPackages(List<Order_Location_Package__c> orderpackages) {
            Set<Id> OrderLocationIds = new Set<Id>();
    
            //Get Order Location Ids from specified orderpackages
            for (Order_Location_Package__c ordpckg : orderpackages) {
                OrderLocationIds.add(ordpckg.New_Location_Name__c);
            }
    
            if (OrderLocationIds.isEmpty() == false) {
                /*Execute as a future call so that the user doesn't have to wait around for
                the rollup to finish. Unless, already in a future or batch call state then
                just perform the rollup.*/
                if (System.isFuture() == false && System.isBatch() == false) {
                    summarizeOrderPackagesAsync(OrderLocationIds);
                }
                else {
                    new OrderLocationRollupSummary().summarizeOrderPackages(OrderLocationIds);
                }
            }
        }
    
        @future
        public static void summarizeOrderPackagesAsync(Set<Id> OrderLocationIds) {
            new OrderLocationRollupSummary().summarizeOrderPackages(OrderLocationIds);
        }
    
        //Public Methods
        public void summarizeOrderPackages(Set<Id> OrderLocationIds) {
            //Get Order Locations to Update
            List<Order_New_Location__c> orderlocations = queryOrderLocationsById(OrderLocationIds);
    
            Map<Id, double> results = getOrderPackagesAmountsByLocationId(OrderLocationIds);
    
            //Loop Order Locations and set Amounts
            List<Order_New_Location__c> orderlocationsToUpdate = new List<Order_New_Location__c>();
            for (Order_New_Location__c ordloc : orderlocations) {
                double mrf = 0;
                double otf = 0;
    
                if (results.containsKey(ordloc.Id)) {
                    mrf = results.get(ordloc.Id);
                    otf = results.get(ordloc.Id);
                }
    
                //Determine if Amounts have Changed
                if (ordloc.Package_Monthly_Recurring_Fees__c != mrf || 
                    ordloc.Package_One_Time_Fees__c != otf) {
                    
                    ordloc.Package_Monthly_Recurring_Fees__c = mrf;
                    ordloc.Package_One_Time_Fees__c = otf;
                    orderlocationsToUpdate.add(ordloc); //Add location to collection to be updated
                }
            }
    
            if(orderlocationsToUpdate.isEmpty() == false) {
                Database.SaveResult[] saveResults = Database.update(orderlocationsToUpdate, false);
                System.debug(saveResults);
            }
        }
    
        //Private Methods
        public Map<Id, double> getOrderPackagesAmountsByLocationId(Set<Id> OrderLocationIds) {
            Map<Id, double> resultsByOrderLocationId = new Map<Id, double>();
    
            //Summarize Order Package Amounts by Order Location Id
            AggregateResult[] results = aggregateOrderPackageAmounts(OrderLocationIds);
            for (AggregateResult result : results) {
                Id orderlocationId = (Id) result.get('OrderLocation');
                double mrf = (double) result.get('MRFees');
                double otf = (double) result.get('OTFees');
    
                resultsByOrderLocationId.put(orderlocationId, mrf);
                resultsByOrderLocationId.put(orderlocationId, otf);
            }
            return resultsByOrderLocationId;
        }
    
        //Query Methods
        private List<Order_New_Location__c> queryOrderLocationsById(Set<Id> OrderLocationIds) {
            return [SELECT 
                    Id 
                    ,Package_Monthly_Recurring_Fees__c
                    ,Package_One_Time_Fees__c
                FROM 
                    Order_New_Location__c 
                WHERE 
                    Id IN :OrderLocationIds];
        }
    
        private AggregateResult[] aggregateOrderPackageAmounts(Set<Id> OrderLocationIds) {
            return [SELECT 
                     New_Location_Name__c OrderLocation
                    ,SUM(Monthly_Recurring_Fees__c) MRFees
                    ,SUM(One_Time_Fees__c) OTFees
                FROM 
                    Order_Location_Package__c
                WHERE
                    New_Location_Name__c IN :OrderLocationIds
                GROUP BY 
                    New_Location_Name__c];
        }
    
    }

 
Hi, 
I need help with my validation rule.  I need to allow only the 'Intake' profile to edit a record 'status' field when another field 'contact type' = 'Intake' .  So far I have below, but it's not working. 

 
AND
(ISCHANGED(enrtcr__Status__c),
NOT(mntrs_Contact_Type_derived__c = "Intake"),
 $Profile.Name = "Intake")

Hello,

I struggle to cover part of my code.
Could someone help?
Thanks
User-added image
here is my code:

 

trigger AircallTaskTrigger on Task (after insert, after update) {

        List<Case> lstCase = new List<Case>();
     
     	//Get 'Case Concern' RecordType Name
        Id caseConcernRecordTypeId = Schema.SObjectType.Case.getRecordTypeInfosByName().get(label.Param_Case_Concern).getRecordTypeId();

        Map<Id, Case> caseWithAircallTaskMap = new Map<Id, Case>([SELECT Id, First_Aircall_Logged__c FROM Case WHERE RecordTypeId =:caseConcernRecordTypeId]);                           
        for(Task t : Trigger.New) { 
           
            if(t.whatId != null &&  t.callDisposition!= null && t.callDisposition.containsIgnoreCase('aircall')) {
               System.debug('#### Aircall debug ' + t.whatId != null && t.callDisposition.containsIgnoreCase('aircall'));
                
                Case c = New Case();
                if(caseWithAircallTaskMap != null && caseWithAircallTaskMap.containsKey(t.whatId)){
                
                    c = caseWithAircallTaskMap.get(t.whatId);
                    if(c.first_Aircall_Logged__c == null){
                        c.first_Aircall_Logged__c = t.createdDate;
                        if(t.WhatId == c.Id) {
                            lstCase.add(c); 
                        }              
                    } 
                } 
            }     
        }
     
        if (lstCase.size() > 0) {
        	update lstCase;
     	}  
  }

here is the Test class
 
@isTest
public class AircallTaskTriggerTest {
    @isTest static void testAircallDateUpdate() {
        
        Contact con = new Contact (FirstName = 'First Name',LastName = 'Test');
        insert con;
        
        Case c = new Case(Status = 'New',ContactId = con.Id,Phone_Number__c = '123456789');
        insert c;
               
        Task t = new Task(Subject = 'Test', WhatId = c.Id, CreatedDate = System.today(), callDisposition = 'aircall');
        insert t;
        
        c.Id = t.WhatId;
        c.First_Aircall_Logged__c = null;
        //System.assertEquals(t.CreatedDate,  c.First_Aircall_Logged__c);
        update c;
       
    }
    
}

 
Hello,

I need help please, how do I prevent the case from being created in the first condition?
 
public Case generateLog(AccountHistory event) {

               if(OldValue_c.equals(NewValue_c)){ //Help                      
                    Case log = new Case();                        
        			return log;

    			}else{   
                     Case log = new Case();
                         log.RecordTypeId     = recordTypePrevention;
                         log.AccountId        = event.AccountId;           
                         log.Origin           = 'Phone';           
                     return log;
		}
}

 
Hi guys, I've stumbled another obstacle - this time providing code coverage for AggregateResult. The general idea is to "count" the number of Invoice Line records under Invoice then put them inside a Map. I've only included a snippet of my code which I believe are relevant.

Apex class:
public override void afterDelete() {

        for(InvoiceLine__c invLine : (List<InvoiceLine__c>) Trigger.old){

            if(invLine.InvoiceId__c != null){

                invLineIdSet.add(invLine.InvoiceId__c);
            }
        }

        List<AggregateResult> invoiceLineList = [SELECT COUNT(Id) counter, InvoiceId__c 
                                                 FROM InvoiceLine__c 
                                                 WHERE InvoiceId__c =: invLineIdSet
                                                 GROUP BY InvoiceId__c];

        List<Invoice__c> invoiceList = [SELECT Id, OpportunityId__c FROM Invoice__c
                                        WHERE Id IN: invLineIdSet];

        Map<Id, Boolean> invLineChecker = new Map<Id, Boolean>();

        Boolean noLineRecords;

        for(Invoice__c invL : invoiceList){

            noLineRecords = true;

            invLineChecker.put(invL.Id, noLineRecords);

            oppIdSet.add(invL.OpportunityId__c);
        }

        for(AggregateResult invoiceLine : invoiceLineList){

            Integer counter = (Integer) invoiceLine.get('counter');

            Id parentInvoiceId = (Id) invoiceLine.get('InvoiceId__c');
            
            if(counter > 0){

                noLineRecords = false;

                invLineChecker.put(parentInvoiceId, noLineRecords);
            }else{

                noLineRecords = true;

                invLineChecker.put(parentInvoiceId, noLineRecords);
            }
        }

        System.debug('NO RECORDS? :' + invLineChecker);
}

As provided in the snippet above, I've highlighted the block of code where I'm unable to get code coverage. If somehow I'll be able to resolve this, I may figure out the rest.

Finally, below is my test class.

Test Class:
private static Opportunity__c opportunityRecord = new Opportunity__c();
private static List<InvoiceLine__c> invoiceLineList = new List<InvoiceLine__c>();

@isTest
    private static void deleteInvoiceLinesNoRecords(){

        initializeData();

        insert invoiceLineList;

        System.assertNotEquals(0, invoiceLineList.size());

        Test.startTest();

        	try
			{
                delete invoiceLineList;
			}Catch(Exception e)
            {
                String errormessage = e.getMessage();
                system.debug(errormessage);
            }

        Test.stopTest();
    }

@isTest
    private static void initializeData(){
        
        opportunityRecord = new Opportunity__c();
        opportunityRecord.Account__c = '0012x000002kyl7AAA'; // required field
        insert opportunityRecord;

        invoiceRecord = new Invoice__c();
        invoiceRecord.OpportunityId__c = opportunityRecord.Id; // required field
        insert invoiceRecord;

        InvoiceLine__c invoiceLineRecord1 = new InvoiceLine__c();
        invoiceLineRecord1.InvoiceId__c = invoiceRecord.Id; // required field

        InvoiceLine__c invoiceLineRecord2 = new InvoiceLine__c();
        invoiceLineRecord2.InvoiceId__c = invoiceRecord.Id; // required field

        InvoiceLine__c invoiceLineRecord3 = new InvoiceLine__c();
        invoiceLineRecord3.InvoiceId__c = invoiceRecord.Id; // required field

        invoiceLineList = new List<InvoiceLine__c>();
        
        invoiceLineList.add(invoiceLineRecord1);
        invoiceLineList.add(invoiceLineRecord2);
        invoiceLineList.add(invoiceLineRecord3);
    }

I would appreciate it greatly if anyone can address this issue with me.

What could I be missing here?

Thank you!

- Sid
Hello everyone, I'm working on writing my first trigger and test class and am coming up short on the test class. My trigger is very simple, it takes all of the related Product names from an Opportunity and puts the names in a string on a field on the Opp separated by semicolons:
 
Trigger ProductList on Opportunity (before update, after delete) {

list<opportunity> sl = trigger.new;

list<opportunityLineItem> slnu = new list<opportunityLineItem>([select id ,product2.name, opportunityId from opportunitylineitem where opportunityId =: trigger.new[0].id]);

string productName='';

for(opportunityLineItem opp : slnu){

 productName += opp.product2.name +'; '; // + operator for concatenation.

}

for(Opportunity opp : trigger.new){

 opp.Product_Summary__c = productName;


}


}

Now, below is my test class. Can someone review and tell me what I'm missing here? Thank you.
@isTest
public class ProductListTestClass {
    
static testMethod void ProductListTestClass() {
        Account a = new Account(Name='testAccount');
        insert a; 
    
        Contact c = new Contact(LastName='testContact',
                               AccountId=a.Id,
                               Contact_Status__c='Prospect',
                               Email = 'xyz@me.com',
                               Function__c = 'Analytics (HCS)');
        insert c; 
    
        Product2 prod = new Product2(Name = 'Product');
        insert prod;
        
        Id pricebookId = Test.getStandardPricebookId();
        
        PricebookEntry standardPrice = new PricebookEntry(
            Pricebook2Id = pricebookId, Product2Id = prod.Id,
            UnitPrice = 10000, IsActive = true);
        insert standardPrice;
        
        
        Pricebook2 customPB = new Pricebook2(Name='Custom 2020', isActive=true);
        insert customPB;
        
        PricebookEntry customPrice = new PricebookEntry(
            Pricebook2Id = customPB.Id, Product2Id = prod.Id,
            UnitPrice = 12000, IsActive = true);
        insert customPrice;
        
        
        Opportunity opp = new Opportunity(Name='Test', 
                                          Account = a, 
                                          PriceBook2 = customPB,
                                          CloseDate = System.today(),
                                          Contract_Start_Date__c = System.today(),
                                          AccountId=a.Id, 
                                          Type = 'New Deal',
                                          Contact__c = c.Id,
                                          LeadSource = 'Client Referral',
                                          Function__c = 'Clinical',
                                          StageName = 'Active', 
                                          Probability = 5);
       
       insert opp; 
        
    }
}

 
Hello awesome Devs! 

I have hit a roadblock on an VF email template I am workign on, and would appreciate any help you all may be able to offer. 

I have the following code where I need to set up an email to an outside party when a contract is created from an Won Opportunity for an order summary.  Seems when I travel from the Contract to the Won Opportunity and then down to its child line items I get the following error: 

Error: Aggregate Relationship is used in an unsupported complex expression containing 'SBQQ__Opportunity__r.opportunitylineitems'

Can anyone look at my below code and tell me what I am doing wrong, and point me in the right direction by manipulating my code below to try?  

Thank you again, very much appreciate any help! 

Email Template Code:
<messaging:emailTemplate recipientType="Contact"
    relatedToType="Contract"
    subject="ORDER SUMMARY_Subscription Contract Number {!relatedTo.ContractNumber}_PO:{!relatedTo.SBQQ__Opportunity__r.Customer_PO__c}"
    replyTo="support@criticalstart.com" >
    
<messaging:htmlEmailBody >        
    <html>
        <body>
         <STYLE type="text/css">
               TH {font-size: 11px; font-face: arial;background: #CCCCCC; border-width: 1;  text-align: center} 
               TD  {font-size: 11px; font-face: verdana } 
               TABLE {border: solid #CCCCCC; border-width: 1}
               TR {border: solid #CCCCCC; border-width: 1}
         </STYLE>
        <div style="text-align:left;">
        <apex:image id="theImage" value="https://xxx.my.salesforce.com/servlet/servlet.ImageServer?id=0153j00000AlYgC&oid=00D3j00000024KB"  width="465" height="84" alt="Critical Start" />
        </div>
        <br/>
        <font face="arial" size="2">
        <b>6100 Tennyson Pkwy #200</b><br/>
        <b>Plano, TX 75024 </b>
        <b>USA</b><br/>
        <b>Phone: (877) 648-2077</b><br/>
        <b>Fax: (214) 919-4050</b><br/> </font>
        <br/>
        <br/>
        <font face="arial" size="5">
        <b>Order Summary</b><br/>
        <br/> </font>
        <font face="arial" size="2">
        <b><u>General Information</u></b><br/>
        Sales ID: {!relatedTo.SBQQ__Opportunity__r.Opp_Num_Only__c}<br/>
        Subscription Contract Number: {!relatedTo.ContractNumber}<br/>
        Subscription Contract Start Date: {!relatedTo.StartDate}<br/>
        Subscription Contract End Date: {relatedTo.EndDate}<br/>
        Subscription Contract Term Length: {!relatedTo.ContractTerm} months<br/>
        Document Date: {!month(relatedTo.Todays_Date__c)}/{!day(relatedTo.Todays_Date__c)}/{!year(relatedTo.Todays_Date__c)}<br/>
        PO #: {!relatedTo.SBQQ__Opportunity__r.Customer_PO__c}<br/>
        Account Manager: {!relatedTo.SBQQ__Opportunity__r.Owner_Full_Name__c}<br/>
        <br/>
        </font>
        <b><u>Sold-To-Party</u></b><br/>
        {!relatedTo.SBQQ__Opportunity__r.Bill_To_Account_Name__c}<br/>
        {!relatedTo.SBQQ__Opportunity__r.Bill_To_Account_Street__c}<br/>
        {!relatedTo.SBQQ__Opportunity__r.Bill_To_Account_City__c}, {!relatedTo.SBQQ__Opportunity__r.Bill_To_Account_State__c} {!relatedTo.SBQQ__Opportunity__r.Bill_To_Account_Zip__c}<br/>
        {!relatedTo.SBQQ__Opportunity__r.Bill_To_Account_Country__c}<br/> 
        E-Mail: {!relatedTo.SBQQ__Opportunity__r.Bill_To_Contact_Email__c}<br/>
        <br/>
        <b><u>End User</u></b><br/>
        {!relatedTo.SBQQ__Opportunity__r.Account_Name__c}<br/>
        {!relatedTo.SBQQ__Opportunity__r.Account_Street__c}<br/>
        {!relatedTo.SBQQ__Opportunity__r.Account_City__c}, {!relatedTo.SBQQ__Opportunity__r.Account_State__c} {!relatedTo.SBQQ__Opportunity__r.Account_Zip__c}<br/>
        {!relatedTo.SBQQ__Opportunity__r.Account_Country__c}<br/>
        <br/>
        <b><u>Bill-To-Party</u></b><br/>
        {!relatedTo.SBQQ__Opportunity__r.Bill_To_Account_Name__c}<br/>
        {!relatedTo.SBQQ__Opportunity__r.Bill_To_Account_Street__c}<br/>
        {!relatedTo.SBQQ__Opportunity__r.Bill_To_Account_City__c}, {!relatedTo.SBQQ__Opportunity__r.Bill_To_Account_State__c} {!relatedTo.SBQQ__Opportunity__r.Bill_To_Account_Zip__c}<br/>
        {!relatedTo.SBQQ__Opportunity__r.Bill_To_Account_Country__c}<br/> 
        <br/>
        <font face="arial" size="2">
        <p><b>Below contains a list of products ordered:</b></p>  
        <p/>                  
       <table border="5" >
                 <tr > 
                     <th>Product Name</th><th>Description</th><th>Quantity</th>
                  </tr>
    <apex:repeat var="opp" value="{!relatedTo.SBQQ__Opportunity__r.OpportunityLineItems}">
       <tr>
           <td>{!opp.PriceBookEntry.name}</td>
           <td>{!opp.Description__c}</td>
           <td>{!ROUND(opp.Quantity,0)}</td>
       </tr>
    </apex:repeat>                
       </table>
       <p/>
 </font>
       
        </body>
    </html>
</messaging:htmlEmailBody> 
    
<messaging:plainTextEmailBody >
Dear {!recipient.name},
 
Below contains a list of products ordered.

Account: {!relatedTo.SBQQ__Opportunity__r.Account.name}
Opportunity Close Date: {!relatedTo.SBQQ__Opportunity__r.CloseDate}


[ Product Name ] - [ Description ] - [ Quantity ]
-------------------------------------------------------------------------

<apex:repeat var="opp" value="{!relatedTo.SBQQ__Opportunity__r.OpportunityLineItems}">
[ {!opp.PriceBookEntry.name} ] - [{!opp.Description__c} ] - [ {!ROUND(opp.Quantity,0)} ]
</apex:repeat>

</messaging:plainTextEmailBody>       
        
</messaging:emailTemplate>

 
Hi Team,

I have a scenario that needs to through a validation using validation rules or flows. Please help me to achieve this.

I have an appointment object, where I have a start date and an end date. If any new appointment dates have already existed in the system. I have to throw an error saying already an appointment got booked on the same slot.
Hi, Team,

I'm trying to get this formula field finalized, however, it keeps populating the shipping value no matter what the picklist selection is. So, it always default to shipping city. The logic should go if type = hospital populate ShippingCity, else, populate BillingCity
 
IF(
OR(
ISPICKVAL(Type, "Hospital"),
ISBLANK(TEXT(Type))
),
ShippingCity,
BillingCity
)

 
Hi Everyone,

I am trying to make it so my html table has it so that it looks like this:

User-added image
However, currently it looks more like this:

User-added image

I know that the apex:repeat is causing the problem, would i be able to exclude the first column somehow?

Here's my table code:
<table id = "table" style="width:50%">
                <thead>
                    <tr>
                    <th title="Field #0"></th>
                    <apex:outputPanel rendered="{!anyHourlyRatePopulated}" layout="none">
                        <th title="Field #1">Services</th>
                    </apex:outputPanel>
                    <apex:outputPanel rendered="{!anyHourlyRatePopulated}" layout="none">
                        <th title="Field #1">Hourly Rate</th>
                    </apex:outputPanel>
                    <apex:outputPanel rendered="{!any2HourRatePopulated}" layout="none">
                        <th title="Field #2">2 Hour Rate</th>
                    </apex:outputPanel>
                    </tr>
                    </thead>
                <tbody>
                <apex:repeat value="{!qli}" var="opp">
                <tr>

                    <th scope ="row">Level 1</th>
                        <td>
                           L1 Hourly Rate Field
                        </td>
                    <td>
                        " L1 2 Hour Rate Field "
                    </td>
            
                </tr>
                </apex:repeat> 
                <apex:repeat value="{!qli}" var="opp">
                <tr>

                    <th scope ="row">Level 2</th>
                        <td>
                            "L2 Hourly Rate Field"
                        </td>
                    <td>
                       " L2 2 Hour Rate Field "
                    </td>
            
                </tr>
                </apex:repeat> 
            </tbody>

        </table>



 
Hi All,

Could you please look into the code and let me know where i am wrong.
I am trying the retrieve the list of accounts using imperative method. The data is not retrieving and it the going to the catch error block.
 
Apex Class
public with sharing class ContactListService {
@AuraEnabled
    public static List<Object> getAcountList(String name){
        String key = '%'+name+'%';
        String accQuery = 'select id, name, email, phone from Account where name like : key';
        System.debug('Query --- '+Database.query(accQuery));
        return Database.query(accQuery);
        
    }
}

JS File:
import { LightningElement, track } from 'lwc';
import getAcountList from '@salesforce/apex/ContactListService.getAcountList';
export default class ContactList extends LightningElement {
    
    @track accounts;
    @track errorAccount;
    @track searchAccount;

    handleChangeAccount(event){
        //event.preventDefault();
        console.log('Value '+event.target.value);
        this.searchAccount = event.target.value;
    }
    
    //Imperative method
    findaccounts(){
        getAcountList({
		name : this.searchAccount
	})
        .then(result =>{
            console.log('Result----'+result);
                this.accounts = result;
        })
        .catch(error=>{
                this.errorAccount = error;
                console.log('Error ----'+error);
        });
    }
}


HTML:
<template>
	<lightning-card>
	    <lightning-layout vertical-align="center">
                  <lightning-layout-item padding="around-small">
                      <lightning-input label="Find Account" value={searchAccount} onchange={handleChangeAccount}></lightning-input>
            	</lightning-layout-item>
            
		<lightning-layout-item padding="around-small">
                	<lightning-button label="Find Accounts" varient="brand" onclick={findaccounts}></lightning-button>
           	</lightning-layout-item>
    
            	<lightning-layout-item padding="around-small">
                	<template for:each={accounts} for:item="acc">
                    		<p key={acc.id}>{acc.Name}</p>
        		</template>
            	</lightning-layout-item>
            </lightning-layout>
	</lightning-card>
</template>

User-added image

Thanks
Saurav
 
i have a quest : 
- create a list view contact
- list have edit + view button

this is my code : 

listview.cmp
<aura:component controller="ContactController" implements="force:appHostable,
                                                           flexipage:availableForAllPageTypes,
                                                           force:hasRecordId">
    
    <aura:attribute type="Contact[]" name="contList"/>
    <aura:attribute name="mycolumns" type="List"/>
    
    <aura:handler name="init" value="{!this}" action="{!c.fetchCt}"/>
    
    <lightning:datatable data="{! v.contList }"
                         columns="{! v.mycolumns }"
                         keyField="id"
                         hideCheckboxColumn="true"
                         onrowaction="{!c.handleRowAction}" />"
</aura:component>

listviewController.js
({
    fetchCt : function(component, event, helper) {
        var actions = [
            {label:'Edit',name:'edit'},
            {label:'View',name:'view'}
        ];
        component.set('v.mycolumns', [
            {label: 'ContactName', fieldName: 'Name', type: 'text'},
            {label: 'Email', fieldName: 'Email', type: 'text'},
            {label: 'Phone', fieldName: 'Phone', type: 'Phone'},
            {label: 'Title', fieldName: 'Title', type: 'Text'},
            {label:'Status',fieldName:'Status',type:'picklist'},
            {type:'action',typeAttributes:{rowActions:actions}}
        ]);
        var action = component.get("c.fetchContacts");
        action.setCallback(this, function(response){
            var state = response.getState();
            if (state === "SUCCESS") {
                component.set("v.contList", response.getReturnValue());
            }
        });
        $A.enqueueAction(action);
    },
    handleRowAction: function ( cmp, event, helper ) {
        
        var action = event.getParam( 'action' );
        var row = event.getParam( 'row' );
        var recId = row.Id;
        console.log('RecordId',recId);
        switch ( action.name ) {
            case 'edit':
                var editRecordEvent = $A.get("e.force:editRecord");
                editRecordEvent.setParams({
                    "recordId": recId
                });
                editRecordEvent.fire();
                break;
            case 'view':
                var viewRecordEvent = $A.get("e.force:navigateToURL");
                viewRecordEvent.setParams({
                    "url": "/" + recId
                });
                viewRecordEvent.fire();
                break;
        }
    }
})

contactController.apxc
public class ContactController {
    @AuraEnabled
    public static List <Contact> fetchContacts() {
        //Qyery 10 accounts
        List<Contact> contList = [Select Id, Name, Email, Title, Phone From Contact];
        //return list of accounts
        return contList;
    }
}


i used this doc : 
https://developer.salesforce.com/docs/component-library/bundle/force:editRecord/documentation

Error : 
This page has an error. You might just need to refresh it. Action failed: c:listView$controller$handleRowAction [Cannot read property 'setParams' of undefined] Failing descriptor: {c:listView$controller$handleRowAction}
User-added image

please someone have me, thanks.
Hi,

I am trying to iterate through a list of users using a For loop, but am receiving duplicate values when pushed to json.

The ID for Username 7 in my example is copied to all values, even though the username shows up correctly in the JSON.

Why is it pushing idForUser7 to all of them here?

{
  "username 1" : {
    "id" : "idForUser7"
  },
  "username 2" : {
    "id" : "idForUser7"
  },
  "username 3" : {
    "id" : "idForUser7"
  },
  "username 4" : {
    "id" : "idForUser7"
  },
  "username 5" : {
    "id" : "idForUser7"
  },
  "username 6" : {
    "id" : "idForUser7"
  },
  "username 7" : {
    "id" : "idForUser7"
  }
}

As a side note, the reason I am going with this approach is to avoid the attributes/type/url when pushing an SObject Map to json.

"attributes" : {
"type" : "User",
"url" : "/services/data/v49.0/sobjects/User/0053t000007t21nAAA"
},
public static string getActiveUsers() {
 		
        Map<string, Map<String, String>> userActiveMap = new Map<string, Map<String, String>>();
        Map<String, String> userActiveMapValue = new Map<String, String>();
        
        try{
            
			for(List<User> activeUsersList : [ select id,username,LastLoginDate,ProfileId from User where IsActive = True]) {
                
                for (User u : activeUsersList) {
                    
                    userActiveMapValue.clear();
                    
                    userActiveMapValue.put('id', string.valueof(u.id));
                    
                    userActiveMap.put(  string.valueof(u.Username) , userActiveMapValue);
                     
                }
                
            }
        
        	
            
         } catch(DmlException e) {
            	System.debug('An unexpected error has occurred: ' + e.getMessage());
         }
            
        return json.serialize(userActiveMap);
        
    }

 
Hi All,

I have field with data type date:

How to query based on that field.

select id, Week_Start_Date__c from QAAM_Weekly_Planner__c where Week_Start_Date__c  := 6/07/2020

I get unknown parse error.

Kindly help.
Hi, Guys!

Is there a way of adding a record in a list record directly? The user doesn't want to call a record form by clicking on "New" button. The data should be entered directly in a new row in the list itself without any screen refresh or navigation.

Thanks
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.
HTML TEMPLATE
<template>
    <lightning-card title="Custom Search Functionality in LWC" icon-name="standard:account">
        <div if:true={errorMsg} style="margin-left: 3%;">
            <p style="color: red;">{errorMsg}</p>
        </div>
        <lightning-layout multiple-rows="true" vertical-align="end">
            <lightning-layout-item size="12" small-device-size="10" medium-device-size="8" large-device-size="6" padding="around-small">
                    <div class="slds-form-element">
                            <div class="slds-form-element__control">
                                    <lightning-input type="text" 
                                                     label="Enter Customer Name" name ="cusName"
                                                     onchange={handleCustomerName} ></lightning-input>
                            </div>
                        </div> 
            </lightning-layout-item>
            <lightning-layout-item size="12" small-device-size="2" medium-device-size="2" large-device-size="2" padding="around-small">
                    <lightning-button label="Search" 
                                      variant="brand" 
                                      onclick={handleSearch}></lightning-button>
                </lightning-layout-item>
            </lightning-layout><br/>
            <template if:true={show}>
                <div class="acc-container">
                    {recordId}
                    <lightning-record-view-form record-id={recordId} object-api-name="Client__c">
                        <div class="slds-grid">
                            <div class="slds-col slds-size_1-of-2">
                                <lightning-output-field field-name="Name"></lightning-output-field>
                                <lightning-output-field field-name="Date_of_Birth__c"></lightning-output-field>
                            </div>
                            <div class="slds-col slds-size_1-of-2">
                                <lightning-output-field field-name="Photo__c"></lightning-output-field>
                                <lightning-output-field field-name="Booking_Date__c"></lightning-output-field>
                            </div>
                        </div>
                    </lightning-record-view-form>
                </div>
            </template>
           
      
    </lightning-card>
</template>

js

import { LightningElement, track } from 'lwc';
import getDetail from '@salesforce/apex/PriceFetch.getDetail';
export default class ClientDefinition extends LightningElement {
    cusName;
    @track show = false;
    @track recordId;
    handleCustomerName(event) {
        this.cusName =  event.target.value;
    }
    handleSearch() {
       /* if(this.cusName.equals('')) {
            this.errorMsg = 'Please enter customer name to search.';
          
            return;
        }*/
        alert(this.cusName);
     
        getDetail({ clientName: this.cusName})
          
        
           .then(result => {
            this.show = true;
            alert(result);
            this.recordId = result;
           })
        
           .catch(error => {
                this.error = error;
                alert("FAILURE" + error);
                 //this.error = error;
           });
            
    }
}

Apex controllr class

public with sharing class PriceFetch {
  
    @AuraEnabled
    public static String getDetail(String clientName) {
       
        String search = '%' + clientName + '%';
       
       List<Client__c> clients = new List<Client__c>();
         clients = [
            SELECT Id, Name, Unit__c, Total_cost__c, Remarks__c, Project__c,Profession__r.Name,Photo__c,PAN__c,Father_Spouse__c,Email_id__c,
            Date_of_Birth__c,Contact_Number__c,Communication_address__c,Booking_Date__c,Booking_Amount__c,Agreement_Date__c,Aadhar_Number__c
            FROM Client__c
            WHERE Name LIKE :search
            LIMIT 1];
            if(clients.size() == 0) {
                 throw new AuraHandledException('exceptionText');
            }
            
           return clients.get(0).Id;
        
    }


 
}

Is there any mistake in my code?
Im not getting the recordId.
Hi Team,
I have a requirement to auto-create an account and contact through web-to-case. I am able to create contact through trigger if the email id doesn't exists.As the contact is created it becomes private conatct because it not associated to any account. So I need to create the account from 'Suppliedcompany' field and map this account to the contact.

APEX CODE

trigger CreateContact on Case (before insert) {
    
        List<String> emailAddresses = new List<String>();
    for (Case caseObj:Trigger.new) {
        if (caseObj.ContactId==null && caseObj.SuppliedEmail!='')
        {
            emailAddresses.add(caseObj.SuppliedEmail);             
        }
    }
    List<Contact> listContacts = [Select Id, Email From Contact Where Email in :emailAddresses];
    Set<String> takenEmails = new Set<String>();
    for (Contact c:listContacts) {
        takenEmails.add(c.Email);
    }
    Map<String,Contact> emailToContactMap = new Map<String,Contact>();
    List<Case> casesToUpdate = new List<Case>();
    for (Case caseObj:Trigger.new) {
        if (caseObj.ContactId==null && caseObj.SuppliedName!=null && caseObj.SuppliedName!='' && caseObj.SuppliedEmail!=null &&
            caseObj.SuppliedEmail!='' && caseObj.SuppliedPhone!=null && caseObj.SuppliedPhone!='' && !takenEmails.contains(caseObj.SuppliedEmail))
         {
            String[] nameParts = caseObj.SuppliedName.split(' ',2);
            if (nameParts.size() == 2)
            {
             Contact cont = new Contact(FirstName=nameParts[0], LastName=nameParts[1], Email=caseObj.SuppliedEmail, Phone=caseObj.SuppliedPhone);
                emailToContactMap.put(caseObj.SuppliedEmail,cont);
                casesToUpdate.add(caseObj);
            }
        }
    }
    List<Contact> newContacts = emailToContactMap.values();
    insert newContacts;
    for (Case caseObj:casesToUpdate) {
        Contact newContact = emailToContactMap.get(caseObj.SuppliedEmail);
        caseObj.ContactId = newContact.Id;
    }
}

Thanks,
Mahesh
Hi,
I have written a trigger which considers value of the checkbox as true.
can you help me in the code to take Approved__c values as false so that the error message works when Approved__c= False

trigger OpportunityProductCheck on OpportunityLineItem (before insert) {
    set<Id> oppIds = new set<id>();
    set<Id> prodIds = new set<Id>();
    map<String,Boolean> prodcheckMap = new map<String,Boolean>();
    for(OpportunityLineItem oli : Trigger.New){
        oppIds.add(oli.OpportunityId);
        prodIds.add(oli.Product2Id);
    }
    Map<Id,Opportunity> oppMap = new Map<Id,Opportunity>([Select Id,Account.BillingCountry from Opportunity where ID IN: oppIds]);
    Map<Id,Product2> prodMap = new Map<Id,Product2>([Select Id,Name from Product2 where Id IN: prodIds]);
    for(Country_Registration__c prod : [Select Id,Approved__c,Part_number__c,Country__c from Country_Registration__c]){
        String key = '';
        if(!String.isEmpty(prod.Part_number__c) && !String.isEmpty(prod.Country__c)){
            key = prod.Part_number__c + prod.Country__c;
            prodcheckMap.put(key, prod.Approved__c );
        }
    }
    
    for(OpportunityLineItem oli : Trigger.New){
        string prodName = prodMap.containsKey(oli.Product2Id) ? prodMap.get(oli.Product2Id).Name : '';
        string acccountry = oppMap.containsKey(oli.OpportunityId) ? oppMap.get(oli.OpportunityId).Account.BillingCountry : '';
        //string olikey = prodMap.get(oli.Product2Id).Name + oppMap.get(oli.OpportunityId).Account.BillingCountry;
        string olikey = prodName + acccountry;
        if(prodcheckMap.containsKey(olikey)  ){
            boolean bool = prodcheckMap.get(olikey);
           
            if(bool){
                String errormsg = prodName + ' is NOT registered for ' + acccountry;
                oli.addError(errormsg);
            }
        }
    }
}
Hi Gurus,

Plz help in Writing a Test class for below scheduled apex class Mon Tue wed thu 7am
 
global class CopyERTBatchDaily Implements Schedulable
    {
        global void execute(SchedulableContext sc)
        {
            setERTBatch();
        }

        public void setERTBatch()
        {
            //List<Executive_RT> exeList = new List<Executive_RT>();
            List<Executive_RT> exeList = [select Case__c, Level_1__c, Level_2__c,Level_3__c  FROM Executive_RT];
             // process each batch of records
            List<Case_Type__c> listCTD = new List<Case_Type__c>();
        
        for(Executive_RT exe : exeList)
        {        
           	listCTD.add(new Case_Type__c(Case__c=exe.Case__c,Level_1__c=exe.Level_1__c,Level_2__c=exe.Level_2__c,Level_3__c=exe.Level_3__c));
            //System.debug('ERT Case No is =====>' +Case__c);
        }
        try {
        	
            insert listCTD;
        
        } catch(Exception e) {
            System.debug(e);
        }
            
        }
    }

Regards
Fiona​​​​​​​
Hi,
Requirement is to show Account name with Account Industry and Account no. when user is searching the Account in the custom searchable dropdown. Doing this in Aura.
Any help on this?
Rgds,
Vai.
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;
}
I have a custom object which has a list of products, country field and checkbox- inactive.

Use case: 
When I create an opportunity and add OpportunityLineItem, The line item should compare with the products field from the custom object.
Also, the Opportunity should look at Bill to country from the account attached and compare with the country field from the custom object.
And if the record matches and the "Inactive" checkbox from the custom object is true, then it should throw an error and not allow to save the opportunity.

For example,
Custom object:
Product: Pencil
Country: Mexico
Inavtive: True

Opportunity:
OpportunityLineItem: Pencil
Account - Bill to Country: Mexico
ERROR FLAG

Can this be achievable ? If so, can i receive some help on building the trigger ?

Thank you in advance.
Hello! I'm a bit new at writing Apex but I'm attempting to create an invocablemethod batch apex class to rollup multiple currency fields on an "Order Package" object to its parent object of "Order Location". Everything seems to be working as expected but I need to rollup multiple fields and I'm running into issues. Can someone show me how I might be able to include multiple fields in the rollup? I attempted to simply add another field but right now it looks like it's assigning the same amount to both fields I included. This seems to be because I am assigning the same "results" to both fields but I can't figure out how I can assign the aggregate query to multiple fields. Any help is greatly appreciated!
 
global class OrderLocationRollupSummary implements Database.Batchable<sObject>, Schedulable {
    
        //Invocable Method
        @InvocableMethod(label='Rollup All Order Packages to Locations')
        global static void rollupAllorderpackages(List<Order_Location_Package__c> orderpackages) {
            rollupOrderPackages(orderpackages);
        }
    
        //Batchable Methods
        global Database.QueryLocator start(Database.BatchableContext bc) {
            return Database.getQueryLocator([SELECT Id FROM Order_New_Location__c]);
        }
    
        global void execute(Database.BatchableContext context, List<sObject> batch){
            Set<Id> OrderLocationIds = new Set<Id>();
    
            for (sObject ordloc : batch) {
                OrderLocationIds.add(ordloc.Id);
            }
    
            summarizeOrderPackages(OrderLocationIds);
        }
    
        global void finish(Database.BatchableContext context) {}
    
        //Schedulable Methods
        global void execute(SchedulableContext context){
            OrderLocationRollupSummary batchJob = new OrderLocationRollupSummary();
            Database.executeBatch(batchJob);
        }
    
        //Static Methods
        public static void rollupOrderPackages(List<Order_Location_Package__c> orderpackages) {
            Set<Id> OrderLocationIds = new Set<Id>();
    
            //Get Order Location Ids from specified orderpackages
            for (Order_Location_Package__c ordpckg : orderpackages) {
                OrderLocationIds.add(ordpckg.New_Location_Name__c);
            }
    
            if (OrderLocationIds.isEmpty() == false) {
                /*Execute as a future call so that the user doesn't have to wait around for
                the rollup to finish. Unless, already in a future or batch call state then
                just perform the rollup.*/
                if (System.isFuture() == false && System.isBatch() == false) {
                    summarizeOrderPackagesAsync(OrderLocationIds);
                }
                else {
                    new OrderLocationRollupSummary().summarizeOrderPackages(OrderLocationIds);
                }
            }
        }
    
        @future
        public static void summarizeOrderPackagesAsync(Set<Id> OrderLocationIds) {
            new OrderLocationRollupSummary().summarizeOrderPackages(OrderLocationIds);
        }
    
        //Public Methods
        public void summarizeOrderPackages(Set<Id> OrderLocationIds) {
            //Get Order Locations to Update
            List<Order_New_Location__c> orderlocations = queryOrderLocationsById(OrderLocationIds);
    
            Map<Id, double> results = getOrderPackagesAmountsByLocationId(OrderLocationIds);
    
            //Loop Order Locations and set Amounts
            List<Order_New_Location__c> orderlocationsToUpdate = new List<Order_New_Location__c>();
            for (Order_New_Location__c ordloc : orderlocations) {
                double mrf = 0;
                double otf = 0;
    
                if (results.containsKey(ordloc.Id)) {
                    mrf = results.get(ordloc.Id);
                    otf = results.get(ordloc.Id);
                }
    
                //Determine if Amounts have Changed
                if (ordloc.Package_Monthly_Recurring_Fees__c != mrf || 
                    ordloc.Package_One_Time_Fees__c != otf) {
                    
                    ordloc.Package_Monthly_Recurring_Fees__c = mrf;
                    ordloc.Package_One_Time_Fees__c = otf;
                    orderlocationsToUpdate.add(ordloc); //Add location to collection to be updated
                }
            }
    
            if(orderlocationsToUpdate.isEmpty() == false) {
                Database.SaveResult[] saveResults = Database.update(orderlocationsToUpdate, false);
                System.debug(saveResults);
            }
        }
    
        //Private Methods
        public Map<Id, double> getOrderPackagesAmountsByLocationId(Set<Id> OrderLocationIds) {
            Map<Id, double> resultsByOrderLocationId = new Map<Id, double>();
    
            //Summarize Order Package Amounts by Order Location Id
            AggregateResult[] results = aggregateOrderPackageAmounts(OrderLocationIds);
            for (AggregateResult result : results) {
                Id orderlocationId = (Id) result.get('OrderLocation');
                double mrf = (double) result.get('MRFees');
                double otf = (double) result.get('OTFees');
    
                resultsByOrderLocationId.put(orderlocationId, mrf);
                resultsByOrderLocationId.put(orderlocationId, otf);
            }
            return resultsByOrderLocationId;
        }
    
        //Query Methods
        private List<Order_New_Location__c> queryOrderLocationsById(Set<Id> OrderLocationIds) {
            return [SELECT 
                    Id 
                    ,Package_Monthly_Recurring_Fees__c
                    ,Package_One_Time_Fees__c
                FROM 
                    Order_New_Location__c 
                WHERE 
                    Id IN :OrderLocationIds];
        }
    
        private AggregateResult[] aggregateOrderPackageAmounts(Set<Id> OrderLocationIds) {
            return [SELECT 
                     New_Location_Name__c OrderLocation
                    ,SUM(Monthly_Recurring_Fees__c) MRFees
                    ,SUM(One_Time_Fees__c) OTFees
                FROM 
                    Order_Location_Package__c
                WHERE
                    New_Location_Name__c IN :OrderLocationIds
                GROUP BY 
                    New_Location_Name__c];
        }
    
    }

 
I have written below code for in Manipulate Records with DML trailhead CHALLENGE, it not accepting but the output is coming correctly. Can you please guide me what is wrong in it.

Create a method for inserting accounts.
To pass this challenge, create an Apex class that inserts a new account named after an incoming parameter. If the account is successfully inserted, the method should return the account record. If a DML exception occurs, the method should return null.

The Apex class must be called AccountHandler and be in the public scope
The Apex class must have a public static method called insertNewAccount
The method must accept an incoming string as a parameter, which will be used to create the Account name
The method must insert the account into the system and then return the record
The method must also accept an empty string, catch the failed DML and then return null

https://trailhead.salesforce.com/content/learn/modules/apex_database/apex_database_dml

public class AccountHandler {

    public static id insertNewAccount(String AccountName){
        Account acc = new Account(Name = AccountName);
        Database.SaveResult srList = Database.insert(acc, false);
        System.debug('srList :'+srList.getId());
        return srList.getId();
    }
}
We are trying to pull a list of all the Salesforce Objects (tables names) from Salesforce. The name of the Object is already known. I want to see the entire list of Objects prior to that. Is this possible?
I have a radio group with picklist values, I am able to get values in console but Radio group is not displaying.
<lightning-radio-group name="Status"
                        label="Work Order Type"
                        options={pickListvalues}
                        value={StatusValue}
                        type="radio" ></lightning-radio-group> 
my JavaScript Code: 
import { LightningElement, wire, track} from 'lwc';
import { getPicklistValues } from 'lightning/uiObjectInfoApi';
import STATUS_FIELD from '@salesforce/schema/WorkOrder.Status';
export default class Workbench extends LightningElement {
@track pickListValues;
 @wire(getPicklistValues, {
        recordTypeId : '0126g000000Oag2AAC',
        fieldApiName : STATUS_FIELD
    })wiredPickListValue({ data, error }){
        if(data){
            console.log('Status Picklist>>', data.values);
            this.pickListvalues = data.values;
            this.error = undefined;
}
if(error){
            console.log('Error  ${error}');
            this.error = error; 
            this.pickListvalues = undefined;
        }
}
Hi, 
I need help with my validation rule.  I need to allow only the 'Intake' profile to edit a record 'status' field when another field 'contact type' = 'Intake' .  So far I have below, but it's not working. 

 
AND
(ISCHANGED(enrtcr__Status__c),
NOT(mntrs_Contact_Type_derived__c = "Intake"),
 $Profile.Name = "Intake")

Hello,

I struggle to cover part of my code.
Could someone help?
Thanks
User-added image
here is my code:

 

trigger AircallTaskTrigger on Task (after insert, after update) {

        List<Case> lstCase = new List<Case>();
     
     	//Get 'Case Concern' RecordType Name
        Id caseConcernRecordTypeId = Schema.SObjectType.Case.getRecordTypeInfosByName().get(label.Param_Case_Concern).getRecordTypeId();

        Map<Id, Case> caseWithAircallTaskMap = new Map<Id, Case>([SELECT Id, First_Aircall_Logged__c FROM Case WHERE RecordTypeId =:caseConcernRecordTypeId]);                           
        for(Task t : Trigger.New) { 
           
            if(t.whatId != null &&  t.callDisposition!= null && t.callDisposition.containsIgnoreCase('aircall')) {
               System.debug('#### Aircall debug ' + t.whatId != null && t.callDisposition.containsIgnoreCase('aircall'));
                
                Case c = New Case();
                if(caseWithAircallTaskMap != null && caseWithAircallTaskMap.containsKey(t.whatId)){
                
                    c = caseWithAircallTaskMap.get(t.whatId);
                    if(c.first_Aircall_Logged__c == null){
                        c.first_Aircall_Logged__c = t.createdDate;
                        if(t.WhatId == c.Id) {
                            lstCase.add(c); 
                        }              
                    } 
                } 
            }     
        }
     
        if (lstCase.size() > 0) {
        	update lstCase;
     	}  
  }

here is the Test class
 
@isTest
public class AircallTaskTriggerTest {
    @isTest static void testAircallDateUpdate() {
        
        Contact con = new Contact (FirstName = 'First Name',LastName = 'Test');
        insert con;
        
        Case c = new Case(Status = 'New',ContactId = con.Id,Phone_Number__c = '123456789');
        insert c;
               
        Task t = new Task(Subject = 'Test', WhatId = c.Id, CreatedDate = System.today(), callDisposition = 'aircall');
        insert t;
        
        c.Id = t.WhatId;
        c.First_Aircall_Logged__c = null;
        //System.assertEquals(t.CreatedDate,  c.First_Aircall_Logged__c);
        update c;
       
    }
    
}

 
Hello,

I need help please, how do I prevent the case from being created in the first condition?
 
public Case generateLog(AccountHistory event) {

               if(OldValue_c.equals(NewValue_c)){ //Help                      
                    Case log = new Case();                        
        			return log;

    			}else{   
                     Case log = new Case();
                         log.RecordTypeId     = recordTypePrevention;
                         log.AccountId        = event.AccountId;           
                         log.Origin           = 'Phone';           
                     return log;
		}
}

 
Hi guys, I've stumbled another obstacle - this time providing code coverage for AggregateResult. The general idea is to "count" the number of Invoice Line records under Invoice then put them inside a Map. I've only included a snippet of my code which I believe are relevant.

Apex class:
public override void afterDelete() {

        for(InvoiceLine__c invLine : (List<InvoiceLine__c>) Trigger.old){

            if(invLine.InvoiceId__c != null){

                invLineIdSet.add(invLine.InvoiceId__c);
            }
        }

        List<AggregateResult> invoiceLineList = [SELECT COUNT(Id) counter, InvoiceId__c 
                                                 FROM InvoiceLine__c 
                                                 WHERE InvoiceId__c =: invLineIdSet
                                                 GROUP BY InvoiceId__c];

        List<Invoice__c> invoiceList = [SELECT Id, OpportunityId__c FROM Invoice__c
                                        WHERE Id IN: invLineIdSet];

        Map<Id, Boolean> invLineChecker = new Map<Id, Boolean>();

        Boolean noLineRecords;

        for(Invoice__c invL : invoiceList){

            noLineRecords = true;

            invLineChecker.put(invL.Id, noLineRecords);

            oppIdSet.add(invL.OpportunityId__c);
        }

        for(AggregateResult invoiceLine : invoiceLineList){

            Integer counter = (Integer) invoiceLine.get('counter');

            Id parentInvoiceId = (Id) invoiceLine.get('InvoiceId__c');
            
            if(counter > 0){

                noLineRecords = false;

                invLineChecker.put(parentInvoiceId, noLineRecords);
            }else{

                noLineRecords = true;

                invLineChecker.put(parentInvoiceId, noLineRecords);
            }
        }

        System.debug('NO RECORDS? :' + invLineChecker);
}

As provided in the snippet above, I've highlighted the block of code where I'm unable to get code coverage. If somehow I'll be able to resolve this, I may figure out the rest.

Finally, below is my test class.

Test Class:
private static Opportunity__c opportunityRecord = new Opportunity__c();
private static List<InvoiceLine__c> invoiceLineList = new List<InvoiceLine__c>();

@isTest
    private static void deleteInvoiceLinesNoRecords(){

        initializeData();

        insert invoiceLineList;

        System.assertNotEquals(0, invoiceLineList.size());

        Test.startTest();

        	try
			{
                delete invoiceLineList;
			}Catch(Exception e)
            {
                String errormessage = e.getMessage();
                system.debug(errormessage);
            }

        Test.stopTest();
    }

@isTest
    private static void initializeData(){
        
        opportunityRecord = new Opportunity__c();
        opportunityRecord.Account__c = '0012x000002kyl7AAA'; // required field
        insert opportunityRecord;

        invoiceRecord = new Invoice__c();
        invoiceRecord.OpportunityId__c = opportunityRecord.Id; // required field
        insert invoiceRecord;

        InvoiceLine__c invoiceLineRecord1 = new InvoiceLine__c();
        invoiceLineRecord1.InvoiceId__c = invoiceRecord.Id; // required field

        InvoiceLine__c invoiceLineRecord2 = new InvoiceLine__c();
        invoiceLineRecord2.InvoiceId__c = invoiceRecord.Id; // required field

        InvoiceLine__c invoiceLineRecord3 = new InvoiceLine__c();
        invoiceLineRecord3.InvoiceId__c = invoiceRecord.Id; // required field

        invoiceLineList = new List<InvoiceLine__c>();
        
        invoiceLineList.add(invoiceLineRecord1);
        invoiceLineList.add(invoiceLineRecord2);
        invoiceLineList.add(invoiceLineRecord3);
    }

I would appreciate it greatly if anyone can address this issue with me.

What could I be missing here?

Thank you!

- Sid
Hello everyone, I'm working on writing my first trigger and test class and am coming up short on the test class. My trigger is very simple, it takes all of the related Product names from an Opportunity and puts the names in a string on a field on the Opp separated by semicolons:
 
Trigger ProductList on Opportunity (before update, after delete) {

list<opportunity> sl = trigger.new;

list<opportunityLineItem> slnu = new list<opportunityLineItem>([select id ,product2.name, opportunityId from opportunitylineitem where opportunityId =: trigger.new[0].id]);

string productName='';

for(opportunityLineItem opp : slnu){

 productName += opp.product2.name +'; '; // + operator for concatenation.

}

for(Opportunity opp : trigger.new){

 opp.Product_Summary__c = productName;


}


}

Now, below is my test class. Can someone review and tell me what I'm missing here? Thank you.
@isTest
public class ProductListTestClass {
    
static testMethod void ProductListTestClass() {
        Account a = new Account(Name='testAccount');
        insert a; 
    
        Contact c = new Contact(LastName='testContact',
                               AccountId=a.Id,
                               Contact_Status__c='Prospect',
                               Email = 'xyz@me.com',
                               Function__c = 'Analytics (HCS)');
        insert c; 
    
        Product2 prod = new Product2(Name = 'Product');
        insert prod;
        
        Id pricebookId = Test.getStandardPricebookId();
        
        PricebookEntry standardPrice = new PricebookEntry(
            Pricebook2Id = pricebookId, Product2Id = prod.Id,
            UnitPrice = 10000, IsActive = true);
        insert standardPrice;
        
        
        Pricebook2 customPB = new Pricebook2(Name='Custom 2020', isActive=true);
        insert customPB;
        
        PricebookEntry customPrice = new PricebookEntry(
            Pricebook2Id = customPB.Id, Product2Id = prod.Id,
            UnitPrice = 12000, IsActive = true);
        insert customPrice;
        
        
        Opportunity opp = new Opportunity(Name='Test', 
                                          Account = a, 
                                          PriceBook2 = customPB,
                                          CloseDate = System.today(),
                                          Contract_Start_Date__c = System.today(),
                                          AccountId=a.Id, 
                                          Type = 'New Deal',
                                          Contact__c = c.Id,
                                          LeadSource = 'Client Referral',
                                          Function__c = 'Clinical',
                                          StageName = 'Active', 
                                          Probability = 5);
       
       insert opp; 
        
    }
}

 
Hi,

I have a trigger than creates and edits an event when a custom object record name Calendar Event is created/edited.

I need help with writing a test class please. Any help will be appreciated.
 
trigger CreateEvent on Calender_Event__c (after insert,before update) {

    if(trigger.isInsert)
    {
        List<Event> eventList = new List<Event>();

        for(Calender_Event__c fac : Trigger.new)
        {
            if(fac.Name != null)
            {
                Event e = new Event();
                e.StartDateTime = fac.Start_Date_Time__c;
                e.EndDateTime = fac.End_Date_Time__c;
                e.Subject = fac.Subject__c;
                e.WhatId = fac.Id;

                eventList.add(e);
            }
        }

        insert eventList;
    }

    if(trigger.isUpdate)
    {
        List<Id> facIds = new List<Id>();

        Map<Id, Event> eventMap = new Map<Id, Event>();

        List<Event> eventList = new List<Event>();

        for(Integer i = 0; i < Trigger.new.size(); i++)
        {
            if(Trigger.new[i].Start_Date_Time__c <> Trigger.Old[i].Start_Date_Time__c)
            {
                facIds.add(Trigger.new[i].Id);
            }
        }
        
        for(Event ev : [SELECT Id, WhatId, StartDateTime, EndDateTime FROM Event WHERE WhatId IN :facIds])
        {
            eventMap.put(ev.WhatId, ev);
        }
        
        for(Calender_Event__c dfc : Trigger.new)
        {
            Event evnt = eventMap.get(dfc.Id);
            if(evnt <> null)
            {
                evnt.StartDateTime = dfc.Start_Date_Time__c;
                evnt.EndDateTime =dfc.End_Date_Time__c;

                eventList.add(evnt);
            }
        }

        update eventList;
    }
}

 
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;
}
I have a custom object which has a list of products, country field and checkbox- inactive.

Use case: 
When I create an opportunity and add OpportunityLineItem, The line item should compare with the products field from the custom object.
Also, the Opportunity should look at Bill to country from the account attached and compare with the country field from the custom object.
And if the record matches and the "Inactive" checkbox from the custom object is true, then it should throw an error and not allow to save the opportunity.

For example,
Custom object:
Product: Pencil
Country: Mexico
Inavtive: True

Opportunity:
OpportunityLineItem: Pencil
Account - Bill to Country: Mexico
ERROR FLAG

Can this be achievable ? If so, can i receive some help on building the trigger ?

Thank you in advance.
I'm getting the following error when attempting to created this custom formula field on the Opportunity object:

LMS Opportunity Owner Auto-Poulate = 
IF(
INCLUDES(Products_of_interest__c, "Learning Management System (LMS)"),
INCLUDES(Products_of_interest__c, "Schoology LMS"), 
Account.LMS_Account_Owner__c)

Conditions are to set the LMS Opportunity Owner to the LMS Account Owner if Opprotunity Products of Interest = Learning Management System (LMS) or Schoology LMS.

The formula above is giving me the following error:  Incorrect parameter type for function 'IF()'. Expected Boolean, received Lookup(User)

What am I doing wrong?

Hi, folks!

Could you please help me with the following scenario?

I have created a <lightning-datatable> tag in my <template> and I need to hidden the dropdown list with the options Wrap Text and Clip Text.

Screenshot:

As far as I know, there isn't any OOTB class that could help me with that.

When trying to apply a custom style, nothing happens:

.THIS slds-button slds-button_icon-baree{
    display: none ;
}

Has anyone any idea of how to solve that?

Thanks in advance.

 

Hello,

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