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


  • Chatter
    Feed
  • 315
    Best Answers
  • 2
    Likes Received
  • 4
    Likes Given
  • 14
    Questions
  • 1112
    Replies
I have a fairly simple controller that queries a record and references values from the record in order to render other VF pages.

How can I write a test class for this Controller?
public class MyController {
    
 public Account account  { get; set; }
        
        public MyController() {
        account = [SELECT Id, Name, Billing_Tier__c, Primary_Contact_Full_Name__C,Secondary_Contact_Full_Name__c,One_Line_Address__c FROM Account
                   WHERE Id = :ApexPages.currentPage().getParameters().get('id')];

	}
}

 

Hi Team,
Parent: Opportunity
Child: Opportunity Member
 I want to update an existing child of an opportunity if a field with the name primary is true on the existing child(Primary child) when a new child is inserted. We can only have one primary member(child record ) for the opportunity.  There is a field Amount on the Opportunity Member object and I want to update this field by subtracting the Amount of New Opportunity member(that we are inserting) from Primary Opportunity Member(an existing record).

My Code is working fine for a single record but not working as expected for bulk operation. Please help

Thank you

public class OppotunityMemberTriggerhandler{
 
   public static void afterInsert(List<Opportunity_Member__c> newoppMember){
          Set<Id> oppIdSet = new Set<Id>();
          List<Opportunity_Member__c> memberList = new List<Opportunity_Member__c>();
          Map<id,Opportunity_Member__c> oppMemberMap = new Map<id,Opportunity_Member__c>();
          List<Opportunity_Member__c> updatedMemberList = new List<Opportunity_Member__c>();
          
          
          for(Opportunity_Member__c newMember : newoppMember){
             oppIdSet.add(newMember.Opportunity__c);
          }
          if(oppIdSet.size()>0){
             memberList = [SELECT id,Amount__c,Opportunity__c,Primary__c FROM Opportunity_Member__c WHERE Opportunity__c IN :oppIdSet AND Primary__c = True ];
          }
          for(Opportunity_Member__c member : memberList){
            oppMemberMap.put(member.Opportunity__c,member);

          }
          for(Opportunity_Member__c oppMember : newoppMember){
              if(oppMember.Primary__c == False){
                for(Opportunity_Member__c primaryMember : memberList){
                    primaryMember.Amount__c = oppMemberMap.get(oppMember.Opportunity__c).Amount__c - oppMember.Amount__c;
                    updatedMemberList.add(primaryMember);
                 }
             }
          }
          update updatedMemberList;
   }    
}
public with sharing class OppSearch {
    
    public List<Opportunity> OppList { get; set; }
    
    public String searchText { get; set; }
    public static Id selectedRec {get;set;}
    public integer totalRecs = 0;
    public integer OffsetSize = 0;
    public integer LimitSize= 5;
    public OppSearch()
    {
        
        OppList = new List<Opportunity>();
        
    }
    
    public PageReference searchOpportunity()
        
    {
        OppList = new List<Opportunity>();
        
        if(String.isBlank(searchText))
        {
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Please enter some value'));
        }
        
        
        
        if(String.isNotBlank(searchText))
        {
            if(searchText.isNumeric())
            {
                Decimal searchstringDouble = decimal.valueOf(searchText);
                
                OppList = [select Id,Name,Account.Name,StageName,Type,Amount,CloseDate
                           
                           from Opportunity
                           
                           where Amount=:searchstringDouble LIMIT :LimitSize OFFSET :OffsetSize];
                totalRecs = OppList.size();
                
                if(OppList.size()==0)
                {
                    ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Search failed as criteria do not match'));
                }
                
            }
            else {
                String newSearchText = searchText+'%';
                
                OppList =[select Id,Name,Account.Name,StageName,Type,Amount,CloseDate
                          
                          from Opportunity
                          where Name like:newSearchText or Account.Name like:newSearchText
                          or StageName like:newSearchText or Type like:newSearchText LIMIT :LimitSize OFFSET :OffsetSize];
                totalRecs = OppList.size();
                
                if(OppList.size()==0)
                {
                    ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Search failed as criteria do not match'));
                }
                
            }
            
        }
        return null;
    }
    public pageReference FirstPage()
    {
        OffsetSize = 0;
        searchOpportunity();
        return null;
    }
    public pageReference previous()
    {
        OffsetSize = OffsetSize - LimitSize;
        searchOpportunity();
        return null;
    }
    public pageReference next()
    {
        OffsetSize = OffsetSize + LimitSize;
        
        searchOpportunity();
        return null;
    }
    public pageReference LastPage()
    {
        OffsetSize = totalrecs - math.mod(totalRecs,LimitSize);
        
        searchOpportunity();
        return null;
    }
    public boolean getprev()
    {
        if(OffsetSize == 0)
            return true;
        else
            return false;
    }
    public boolean getnxt()
    {
        if((OffsetSize + LimitSize) > totalRecs)
            
            return true;
        else
            return false;
    } 
    public static HttpResponse sendData()
    {
        Opportunity op=[select Id,Name,Account.Name,StageName,Type,Amount,CloseDate
                        
                        from Opportunity
                        
                        where Id = :selectedRec];
        
        JSONGenerator gen = JSON.createGenerator(true);   
        gen.writeStartObject();     
        gen.writeStringField('Name ', op.Name);
        
        gen.writeStringField('Account',op.Account.Name);
        gen.writeStringField('Stage',op.StageName);
        gen.writeStringField('Type',op.Type);
        gen.writeNumberField('Amount',op.Amount);
        gen.writeDateField('Close Date',op.CloseDate);
        gen.writeEndObject();   
        String jsonS = gen.getAsString();
        System.debug('jsonMaterials'+jsonS);
        
        // Sending the http body with JSON
        
        Http http = new Http();
        HttpRequest request = new HttpRequest();
        request.setEndpoint('https://th-apex-http-callout.herokuapp.com/animals');
        request.setMethod('POST');
        request.setHeader('Content-Type', 'application/json;charset=UTF-8');
        // Set the body as a JSON object
        request.setBody(jsonS);
        HttpResponse response = http.send(request);
        if (response.getStatusCode() != 201)
        {
            Opportunity o= [select Integration_Comments__c,Integration_Status__c from Opportunity
                            where Id =:selectedRec];  
            o.Integration_Status__c='Not Successful';
            o.Integration_Comments__c=response.getStatus();
            update o;
            System.debug(response.getStatusCode());
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Opps! your Callout was not successful'));
        }
        
        else {
            
            Opportunity o= [select Integration_Comments__c,Integration_Status__c from Opportunity
                            where Id =:selectedRec]; 
            
            o.Integration_Status__c='Success';
            o.Integration_Comments__c='Success';
            update o;
            System.debug(response.getStatusCode());
        }
      return response;
    }
    
}
 

Hi Coders, I am new to Coding and took a task to write a test class. I am working for a Leave management App and made my coverage for 65%. I am not understading why my for loop is not covered in coverage. your help is greatly appreciated !!


This my Class: (Bold code is NOT in coverage)
trigger OnLeaveApproval on Leaves__c (after update)
{
    
for(Leaves__c obj: Trigger.new)
{
    map<string, Object> leaveMap = new map<string, Object>();
    system.debug('coming here 1');   
    if (obj.Approval_Status__c != Null && obj.Approval_Status__c == 'Approved')
    {
            system.debug('coming here 1.2'+ obj.CreatedById); 
            system.debug('coming here 1.2'+ obj.Contact_ID__c); 
            system.debug('name'+ obj.Name);
            system.debug('coming here 1.2.1'+ obj); 
            leaveMap.put(obj.Contact_ID__c, obj.Req_Days_Off__c);
            system.debug('coming here 2'); 
    }
    system.debug('coming here 2.1' + leaveMap);
    if(leaveMap.size() > 0 ) {
  
            list<Contact> contact = [SELECT Id,Total_Available_Leaves__c,OwnerId FROM Contact WHERE  Id IN :leaveMap.KeySet()];
            system.debug('coming here 3' + contact); 
            list<Monthly_Take_Home__c> employeePayroll = [SELECT Id,Unpaid_Days__c, Paid_Days__c, Salary__c,Emp_Salary__c,Current_PayPeriod_Salary__c FROM Monthly_Take_Home__c WHERE Contact_ID__c IN :leaveMap.KeySet()];
            system.debug('coming here 3.1' + employeePayroll);
            list<Contact> contactUpdatelist = new list<Contact>();
            list<Monthly_Take_Home__c> employeePayrolllist = new list<Monthly_Take_Home__c>();
            for(Contact c: contact)
                {
                    system.debug('coming here 4'+ contact); 
                    //Integer totalApprovedLeaves = leaveMap.get(c.Name);
                    Integer totalApprovedLeaves = Integer.valueOf(leaveMap.get(c.Id));
                    if( c.Total_Available_Leaves__c - totalApprovedLeaves < 0 ) {
                        
                            system.debug('coming here 5'+c.Total_Available_Leaves__c); 
                             Integer lossOfPayDays = totalApprovedLeaves - c.Total_Available_Leaves__c.intValue();
                             system.debug('coming here 5.1'+ lossOfPayDays);
                            for(Monthly_Take_Home__c empPayroll: employeePayroll)
                            {
                                
                                  if(empPayroll.Unpaid_Days__c !=null)
                                      lossOfPayDays = lossOfPayDays + empPayroll.Unpaid_Days__c.intValue();
                                system.debug('coming here 5.1'+ lossOfPayDays);
                                system.debug('coming here 6.0'+empPayroll.Paid_Days__c); 
                                Integer totalPayDates = empPayroll.Paid_Days__c.intValue() - lossOfPayDays;
                                system.debug('totalPayDates 6'+totalPayDates); 
                                Double calculatedSalary =  Double.valueOf(empPayroll.Emp_Salary__c/empPayroll.Paid_Days__c.intValue());
                                system.debug('empPayroll.Salary__c 0'+ empPayroll.Emp_Salary__c);
                                system.debug('totalPayDates'+ totalPayDates);
                                system.debug('lossOfPayDays'+ lossOfPayDays);
                                empPayroll.Current_PayPeriod_Salary__c = (calculatedSalary * totalPayDates) ;
                                system.debug('totalSalary'+ calculatedSalary * totalPayDates);
                                empPayroll.Unpaid_Days__c = lossOfPayDays;
                                system.debug('empPayroll.Current_PayPeriod_Salary__c'+ empPayroll.Current_PayPeriod_Salary__c);
                                system.debug('calculatedSalary'+ calculatedSalary);     
                                employeePayrolllist.add(empPayroll);
                            }
                        c.Total_Available_Leaves__c = 0;
                    } else {
                        
                        c.Total_Available_Leaves__c =
c.Total_Available_Leaves__c - totalApprovedLeaves;
                    }
                    contactUpdatelist.add(c);
            }
            if(contactUpdatelist.size() > 0)
            {
                system.debug('coming here 7'+ contactUpdatelist); 
                update contactUpdatelist;
            }

            if(employeePayrolllist.size() > 0)
            {
                system.debug('coming here 8'+ employeePayrolllist); 
                update employeePayrolllist;
            }
        }
}
}


This my Test Class: Covered 65% of code
@isTest
private class OnLeaveApprovalTest {
 
@isTest
public static void CreateContactAndLeaveReq(){
test.startTest(); 

// Test data setup - Create a new Employee contact
Contact emp = new Contact ();
emp.FirstName = 'Jon';
emp.LastName = 'Snow';
emp.Emp_ID__c = 'Sp-343245';
emp.Total_Available_Leaves__c = 4;
emp.Emp_Salary__c = 10000;
    
insert emp;
system.debug(emp);

Contact EmpInfo = [Select Name,Id from Contact Where id =: Emp.Id]; 

//Enter record details on Leaves Object
Leaves__c leaveReq = new Leaves__c();
leaveReq.Employee_Name__c = EmpInfo.Id;
leaveReq.Request_Start_Date__c = date.newInstance(2020,06,10);
leaveReq.Request_End_Date__c = date.newInstance(2020,06,15);
leaveReq.Contact_ID__c = Emp.Id;

Insert leaveReq;
system.debug(leaveReq);


leaveReq.Approval_Status__c = 'Approved';
Update leaveReq;
    
Monthly_Take_Home__c TakeHome = new Monthly_Take_Home__c();
TakeHome.Employee_Name__c = EmpInfo.Id;
TakeHome.Salary_Start_Date__c = date.newInstance(2020,06,01);
TakeHome.Salary_End_Date__c = date.newInstance(2020,06,30);
TakeHome.Unpaid_Days__c = 6;
TakeHome.Contact_ID__c = Emp.Id;

Insert TakeHome;
test.stopTest();   
}
}

The initial value for a number field on a record is 1. A user updated the value of the number field to 10. This action invokes a workflow field update, which changes the value of the number field to 11. After the workflow field update, an update trigger fires.
What is the value of the number field of the object that is obtained from Trigger.old?

A. Null

B. 11 (Since 11 will be the immediate previous value before update, so i am considering it correct)

C. 1

D. 10

 Is it 11 or 1 ? And How ?
I want to sort String values from a custom field from custom settings. I had no issues with the code but I get the error "Method does not exist or incorrect signature: void ascending() from the type anon'

Here's my code:
public class SortNumbersFromCustomSetting {
	static Dev_Bootcamp__c value = Dev_Bootcamp__c.getInstance();
    
    static List<String> ListStringValue = new List<String>(value.Random__c.split('-'));
    
   		public static List<Integer> ascending(){
         List<Integer> ListIntValue = new List<Integer>();
            for(String str:ListStringValue){
                ListIntValue.add(Integer.valueOf(str));
            }
         ListIntValue.sort();
         Set<Integer> SetIntValue = new Set<Integer>(ListIntValue);
         List<Integer> FinalValue = new List<Integer>(SetIntValue);
         return FinalValue;
     }
    public static List<Integer> descending(){
        List<Integer> Temp = ascending();
        List<Integer> DescIntValue = new List<Integer>();
        for(Integer i = Temp.size()-1; i>=0; i--){
            DescIntValue.add(Temp.get(i));
        }
        return DescIntValue;
    }
}

 
I have a trigger that is effectively checking a custom list to match the Close Date with the Start/End dates for weeks so a custom field is populated with the text of the Start and End dates.

Trigger:
trigger CloseWeekUpdate on Opportunity (before insert, before update) {
    Try{
        for(Opportunity opp : trigger.new){
            if(opp.CloseDate != NULL){
                system.debug('opp.CloseDate = ' + opp.CloseDate);
                for(CloseDateWeek__c rec : CloseDateWeek__c.getAll().values()){
                    if (opp.CloseDate >= rec.WeekStartDate__c && opp.CloseDate <= rec.WeekEndDate__c){
                        system.debug('rec.WeekStartDate__c = ' + rec.WeekStartDate__c);
                        system.debug('rec.WeeEndDate__c = ' + rec.WeekEndDate__c);
                        opp.Close_Week__c = rec.WeekStartDate__c.format() + ' - ' + rec.WeekEndDate__c.format();
                        system.debug('rec.Close_Week__c = ' + opp.Close_Week__c);
                        break;
                    }
                }
            }
        }
    }
    Catch(Exception Ex){
        system.debug('Exception Details = ' + Ex);
    }


I have built a test class to insert a test Opportunity and I am getting to 50% but unable to get higher, how do I get the class to test the following lines from the Trigger?

Lines that are not testing:

- for(CloseDateWeek__c rec : CloseDateWeek__c.getAll().values()){
- if (opp.CloseDate >= rec.WeekStartDate__c && opp.CloseDate <= rec.WeekEndDate__c){
- opp.Close_Week__c = rec.WeekStartDate__c.format() + ' - ' + rec.WeekEndDate__c.format();

Here is the Test class I have:
@isTest
    public class TestCloseWeekUpdate {
        static testMethod void testCloseWeek(){
            Opportunity to = new Opportunity();
            to.Name = 'Test Name';
            to.CloseDate = Date.newInstance(2020,06,06);
            to.StageName = 'Closed Won';
            to.Start_Date__c = Date.newInstance(2020,06,01);
            to.Type = 'New Business';
            to.Market__c = 'Large';
            to.Premium__c = TRUE;
            to.Startup_Needed__c = 'Yes';
            insert to;
            test.startTest();
            try{
                to.Close_Week__c = '5/31/2020 - 6/6/2020';
            }
            Catch (Exception ee){}
            test.stopTest();
        }
    }


Any help with getting that last 3 lines covered is greatly appreciated! 
I need help writing a test class for my apex code. I really don't know much about apex. But I was able to create a visualforce page and an apex class that extends the standard controller. Everything works perfectly in my sandbox. But I have no idea how to write the test class so that I can push my code into production.

Here is my code for the visualforce page:

<apex:page standardController="WorkOrder" extensions="WorkOrderLineItemsOnWorkOrderClass">     

    <apex:sectionHeader title="Equipment on quote number {! WorkOrder.Workorder_Name__c } for {! WorkOrder.Account.Name }"/>
  
    <p></p>
    
    <apex:pageblock id="WorkOrderLineItemList"> 

         <br/> 

            <apex:pageBlockTable value="{!WorkOrderLineItems}" var="item">                          

                <apex:column value="{!item.Product_Code_Display__c}"/>
                
                <apex:column value="{!item.Description}"/> 
                
                <apex:column value="{!item.Quote_Line_Quantity_Display__c}"/>
                
                <apex:column value="{!item.Quote_Line_Net_Total_Display__c}"/> 
                
                <apex:column value="{!item.Group_Name__c}"/>
               
            </apex:pageBlockTable>     
            
     </apex:pageblock> 

</apex:page>

And here my code for my apex class that extends the standard controller:

public class WorkOrderLineItemsOnWorkOrderClass {

    public List<WorkOrderLineItem> WorkOrderLineItems{get;set;}

    public WorkOrder WorkOrders {get;set;} 

    public WorkOrder wo {get;set;} 

     //Constructor 

    public WorkOrderLineItemsOnWorkOrderClass(ApexPages.StandardController controller) { 

        wo = (WorkOrder)controller.getRecord();      

        WorkOrders = [SELECT id FROM WorkOrder WHERE id=: wo.id LIMIT 1]; 

        WorkOrderLineItems = [SELECT id,Group_Name__c,Product_Code_Display__c,Quote_Line_Quantity_Display__c, Description, Quote_Line_Net_Total_Display__c FROM WorkOrderLineItem WHERE WorkOrderid = :WorkOrders.id ORDER BY Quote_Line__c];     


   
}
 
trigger contactTrigger on Contact (after insert,after update) {
List<Id> ids = new List<Id>();
    for(Contact con: trigger.new){
        ids.add(con.AccountId);
    }
    List<Account> aList= [select id,name, Task__c, (select id,Task__c from contacts) from account where id IN: ids];
        
    
    for(Account acc: aList){
        for(Contact con: acc.contacts){
            system.debug('task'+con.Task__C+acc.Task__C);
        if(con.Task__C=='Submitted'){
            acc.Task__C='Achieved';
            } system.debug('task'+con.Task__C+acc.Task__C+acc.Name);
        }
    }
}
    
    
    
    
    
    
    
    
 
I found this How To Show HTML Email Right On Your Case Page (http://success.salesforce.com/ideaView?id=087300000007TOe) that really works great for what we want but cannot understand how to test it.
 
public with sharing class CaseHTMLEmailController {
    private final Case caseObj;

    public String firstHTMLEmail { get
        {return getFirstHTMLEmail(); }
    }
    
    public CaseHTMLEmailController(ApexPages.StandardController stdController) {
        this.caseObj = (Case)stdController.getRecord();
    }

    public String getFirstHTMLEmail() {
        EmailMessage firstEmail = [Select HtmlBody From EmailMessage where ParentId=:caseObj.Id order by LastModifiedDate asc limit 1];
        if (firstEmail!=null) {
            return firstEmail.HtmlBody;
        }
        
        return '';
    }
}

I need the email-to-case context where the case was generated by an email and test  it pulling the data from emailMessage for this visualforce page.
Hello,

I have a map with Name(String) and Ranks(Integer),
Name is the Pricebook name and Rank is Order by.
map<String,Integer> mapOfNameAndRank = new map<String,Integer>();

Name1, 1
Name2, 2
Name3, 3
I am populating SelectOption in below manner: 
public list<SelectOption> listOfOpt {get;set;}
for(priceBook2 prc : [select id,Name from priceBook2 ){
            listOfOpt.add(new SelectOption(prc.Id,prc.Name));
        }

My usecase is that, the SelectOption should display the Name is the order defined in map.

How can i reiterate the SelectOption inorder to order it.

thank you for suggestion
Params1:
public class params1 {
    @AuraEnabled
    public static List<Account> accountthod(){
        List<Account> accounts=[select id,name,industry,rating,phone from Account limit 4];
        return accounts;
    }
}

pasasm.cmp
<aura:component controller="params1">
    <aura:attribute name="acclist" type="List"/>
    <aura:handler name="init" value="{!this}" action="{!c.invoke}"/>
    <aura:iteration items="{!v.acclist}" var="a">
        <p>{!a.name} &nbsp;&nbsp;&nbsp;{!a.industry} &nbsp;&nbsp;&nbsp;{!a.rating} &nbsp;&nbsp;&nbsp;{!a.phone}</p>
    </aura:iteration>
</aura:component>

parasmController.js
({
    invoke : function(component, event, helper) {
        var action=component.get("v.accountthod");
        action.setCallback(this,function(response){
            console.log("invoked");
            var state=response.getState();
            if(state==='SUCCESS'){
                console.log('Operation successfull');
                component.set("v.acclist",response.getReturnValue());
            }else{
                console.log('Operation failed');
            }            
        });
        $A.enqueueAction(action);
    }
})

parasmap.app
<aura:application extends="force:slds">
    <c:parasm />
</aura:application>
I am trying to get the Contact Name and Email of the Primary Opportunity Contact. I am having difficulty as what is being returned is the Id of the contact and no email. 

Could someone let me know what key piece I'm missing here? 
 
List<OpportunityContactRole> primaryContactInfo = [SELECT OpportunityId, Contact.Name, Contact.Email
                    FROM OpportunityContactRole
                    WHERE OpportunityId ='0063h00000551YKAAY' AND isPrimary = TRUE];

System.debug(primaryContactInfo[0].get((string)'OpportunityId'));
System.debug(primaryContactInfo[0].get((String)'ContactId'));

How would I expose Contact.Name and Contact.Email? 
Can't do with Workflow or Process Builder...can I do this with a Trigger? New to Triggers

Trying to update a custom field (Call_Copy_Last_Reported_Date__c) on User object with a date (Week_Ending__c) from custom object (Call_Copy_Reporting__c) when a new Call Copy Report is created. 

Custom Object - Call Copy Reporting
Owner (Lookup)
Week_Ending__c (Date)

User Object
Call_Copy_Last_Reported_Date__c (Date)

Any help would be appreciated!
Hi, i write a code about datatable and apex, but  the result is null.
I have a custome object called Warehouse.It have a relationship field, related to Product object. And a number filed called Amount.
 want to show they in datatable. Now page show null but amount of records is right. And i try to show Name,Type__c , they will show. Just Product__r.Name and Amount__c is null.
Im sure that my SOQL is right.because i run it in develope consle query editor.

This is my code.
cmp:
<aura:handler name="init" value="{!this}" action="{!c.doInit}" />
	<aura:attribute name="columns" type="List"/>
	<aura:attribute name="data" type="Object"/>
	<aura:attribute name="errors" type="Object" default="[]"/>

	<lightning:card title="Pending QA">
		<lightning:datatable
			columns="{! v.columns }"
			data="{! v.data }"
			keyField="Id"
			errors="{! v.errors}"
			hideCheckboxColumn="true"/>
	</lightning:card>
controller:
doInit : function(component, event, helper) {
    	component.set('v.columns', [
            { label: 'Product', fieldName: 'Product__r.Name', type: 'text',editable:false},
            { label: 'Amount', fieldName: 'Amount__c', type: 'text',editable:false}]);
    	helper.getPendingRecord(component,event,helper);
    }
Helper:
getPendingRecord : function(component, event, helper) {
		var action = component.get("c.query");
        // call back
        action.setCallback(this, function(response){
            var state = response.getState();
            // call back success
            if (state == "SUCCESS"){
                var result = response.getReturnValue();
                component.set('v.data', result);
            }
            // call back failed
            else {
                var toastEvent=$A.get("e.force:showToast");
                toastEvent.setParams({
                    "title":'Error!',
                    "message":'Get Record Failed!',
                    "duration":5000,
                    "type":ERROR
                });
                toastEvent.fire();
            }
        });
        $A.enqueueAction(action);
	}
class:
public static List<Warehouse__c> query() {
    	List<Warehouse__c> pending = new List<Warehouse__c>();
        pending = [SELECT Product__r.Name,Amount__c FROM Warehouse__c WHERE Type__c = 'pendingArea'];
        return pending;
    }
Pls help me. Thanks!


 
CMPT:
<aura:component controller="DTController">
    <aura:attribute name="parentId" type="Id"/>
    <aura:attribute name="nameFilter" type="string"/>
    <aura:attribute type="FIN_RCSAQ__c[]" name="acctList"/>
    <aura:attribute name="showSaveCancelBtn" type="boolean" default="false" />
    <aura:attribute name="isAsc" type="boolean" default="true" description="boolean flag for pass sorting condition to apex class"/> 
    <aura:attribute name="arrowDirection" type="string" default="arrowup" description="Use for change arrow sign direction on header based on click"/>
    <aura:attribute name="selectedTabsoft" type="string" default="firstName" description="Use for show/hide arraow sign on header based on conditions"/>
     
    <aura:handler name="init" value="{!this}" action="{!c.fetchAcc}"/>
    
    <table class="slds-table slds-table_bordered slds-table_col-bordered slds-table_cell-buffer slds-table_edit slds-table_resizable-cols" style="table-layout: fixed; width: 100% !important;">
        <thead>
            <tr class="slds-line-height_reset">
                <th class="slds-is-sortable" scope="col" onclick="{!c.sortName}">
                    <a href="javascript:void(0);" class="slds-th__action slds-text-link--reset">
                        <span class="slds-assistive-text">Sort</span>
                        <span class="slds-truncate" title="Name">Fin-RSCAQ</span>  
                        <aura:if isTrue="{! and(v.arrowDirection == 'arrowdown', v.selectedTabsoft == 'Name') }">
                            <lightning:icon iconName="utility:arrowdown" alternativeText="Descending" size="xx-small" />
                        </aura:if>  
                        <aura:if isTrue="{! and(v.arrowDirection != 'arrowdown', v.selectedTabsoft == 'Name') }">
                            <lightning:icon iconName="utility:arrowup" alternativeText="Descending" size="xx-small" /> 
                        </aura:if>                        
                    </a>
                </th>
                <th class="slds-is-sortable" scope="col" onclick="{!c.sortControlNumber}">
                    <a href="javascript:void(0);" class="slds-th__action slds-text-link--reset">
                        <span class="slds-assistive-text">Sort</span>
                        <span class="slds-truncate" title="ControlNumber">Control Number</span>  
                        <aura:if isTrue="{! and(v.arrowDirection == 'arrowdown', v.selectedTabsoft == 'ControlNumber') }">
                            <lightning:icon iconName="utility:arrowdown" alternativeText="Ascending" size="xx-small" />
                        </aura:if>  
                        <aura:if isTrue="{! and(v.arrowDirection != 'arrowdown', v.selectedTabsoft == 'ControlNumber') }"> 
                            <lightning:icon iconName="utility:arrowup" alternativeText="Descending" size="xx-small" />
                        </aura:if>                        
                    </a>
                </th>
                <th scope="col">
                    <div class="slds-truncate slds-text-align_center" title="ControlObjective">Control Objective</div>
                </th>
                <th scope="col">
                    <div class="slds-truncate slds-text-align_center" title="ControlledElsewhere">Controlled Elsewhere</div>
                </th>
                <th scope="col">
                    <div class="slds-truncate slds-text-align_center" title="ControlledElsewhereHFMCode">Controlled Elsewhere HFM Code</div>
                </th>
                <th scope="col">
                    <div class="slds-truncate slds-text-align_center" title="Frequency">Frequency</div>
                </th>
                <th scope="col">
                    <div class="slds-truncate slds-text-align_center" title="FrequencySelection">Frequency Selection</div>
                </th>
                <th scope="col">
                    <div class="slds-truncate slds-text-align_center" title="Preparer">Preparer</div>
                </th>
                <th scope="col">
                    <div class="slds-truncate slds-text-align_center" title="CreatedBy">Created By</div>
                </th>
                <th scope="col">
                    <div class="slds-truncate slds-text-align_center" title="FirstApprover">First Approver</div>
                </th>
                <th scope="col">
                    <div class="slds-truncate slds-text-align_center" title="SecondApprover">Second Approver</div>
                </th>
            </tr>
        </thead>
        <!--table body start, Iterate contact list as a <tr> -->
        <tbody>
            <aura:iteration items="{!v.acctList}" var="acc">  
                <c:InlineEditRow singleRec="{!acc}" 
                                 rcsaqFrequencyVal="{!acc.RCSAQ_Frequency__c}" 
                                 frequencySelectionVal = "{!acc.Frequency_Selection__c}"
                                 firstOwnerNameVal="{!acc.First_Approver__r.Name}" 
                                 secondOwnerNameVal="{!acc.Second_Approver__r.Name}" 
                                 prepareNameVal="{!acc.Preparer__r.Name}" 
                                 showSaveCancelBtn="{!v.showSaveCancelBtn}"/>
            </aura:iteration>
        </tbody>
    </table> 
    
    <aura:if isTrue="{!v.showSaveCancelBtn}">
        <lightning:buttonGroup class="slds-m-around_medium">
            <lightning:button label="Cancel" />
            <lightning:button label="Save" onclick="{!c.handleSaveEdition}" variant="success"/>
        </lightning:buttonGroup>
    </aura:if> 
</aura:component>

Controller:
({
    fetchAcc : function(component, event, helper) {
        helper.fetchAccHelper(component, event, "Name");
    },
    sortName : function(component, event, helper) {
        component.set("v.selectedTabsoft", "Name"); 
        helper.sortHelper(component, event, "Name");
    },
    sortControlNumber : function(component, event, helper) {
        component.set("v.selectedTabsoft", "ControlNumber"); 
        helper.sortHelper(component, event, "Control_Number__c");
    },
    handleSaveEdition: function (cmp, event, helper) {
        var draftValues = cmp.get("v.acctList");
        console.log(draftValues);
        var action = cmp.get("c.updateAccount");
        action.setParams({"acc" : draftValues});
        action.setCallback(this, function(response) {
            console.log(response);
            helper.fetchAccHelper(cmp, event, "Name");
            cmp.set("v.showSaveCancelBtn", false); 
        });
        $A.enqueueAction(action);
    },
})

Helper:
({
    fetchAccHelper : function(component, event, sortFieldName) {
        var action = component.get("c.fetchAccount");
        action.setParams({
            "parentId" : component.get("v.parentId"),
            "sortField": sortFieldName,
            "isAsc": component.get("v.isAsc"),
            "nameLike":component.get("v.nameFilter")
        });
        action.setCallback(this, function(response){
            var state = response.getState();
            if (state === "SUCCESS") {
                var records =response.getReturnValue();
                console.log(records);
                records.forEach(function(record){
                    record.linkName = '/'+record.Id;
                });
                component.set("v.acctList", records);
            }
        });
        $A.enqueueAction(action);
    },
    sortHelper: function (component, event, sortFieldName) {
        var currentDir = component.get("v.arrowDirection");
        if (currentDir == 'arrowdown') {
            component.set("v.arrowDirection", 'arrowup'); 
            component.set("v.isAsc", true);
        } else {
            component.set("v.arrowDirection", 'arrowdown');
            component.set("v.isAsc", false);
        }
        this.fetchAccHelper(component, event, sortFieldName);
    }
})
Style:
.THIS .slds-table td th {
    white-space:normal; /* wraps larger stuff like textarea and long text*/
}
.THIS .widthVal {
    max-width:100% !important;
}

Apex Class:
public class DTController{
    @AuraEnabled
    public static List<FIN_RCSAQ__c> fetchAccounts(String parentId) {
        String query = 'SELECT Id, Name, Control_Number__c, Question_Number__c, Risk_Reference__c, Control_Objective__c,';
        query += 'Group_Control_Description__c,Assertions__c,Controlled_Elsewhere__c,Controlled_Elsewhere_HFM_Code__c,';
        query += 'First_Approver__c,First_Approver__r.Name,Second_Approver__c,Second_Approver__r.Name,';
        query += 'Frequency_Selection__c,RCSAQ_Frequency__c,Preparer__r.Name,';
        query += 'Control_Clarification__c,Frequency__c,Control_Type__c,System_Report_SAP__c,System_Report_OTC__c,System_Name__c,';
        query += 'Excel_File_Name__c,Evidence_of_the_Control__c,Notes_Guidance__c,Preparer__c,Supported_By__c FROM ';
        query += 'FIN_RCSAQ__c WHERE Control_Number__c LIKE \'RR%\'';
        if(String.isNotBlank(parentId)) query += ' AND FIN_RCSA__c = \'' + parentId + '\'';
        List<FIN_RCSAQ__c> accList = Database.query(query);
        System.debug(accList);
        return accList;
    }
    
    @AuraEnabled
    public static List<FIN_RCSAQ__c> fetchAccount(String parentId, String sortField, boolean isAsc, String nameLike) {
        String query = 'SELECT Id, Name, Control_Number__c, Question_Number__c, Risk_Reference__c, Control_Objective__c,';
        query += 'Group_Control_Description__c,Assertions__c,Controlled_Elsewhere__c,Controlled_Elsewhere_HFM_Code__c,';
        query += 'Control_Clarification__c,Frequency__c,Control_Type__c,System_Report_SAP__c,System_Report_OTC__c,System_Name__c,';
        query += 'Preparer__r.Name,First_Approver__c,First_Approver__r.Name,Second_Approver__c,Second_Approver__r.Name,';
        query += 'Frequency_Selection__c,RCSAQ_Frequency__c,';
        query += 'Excel_File_Name__c,Evidence_of_the_Control__c,Notes_Guidance__c,Preparer__c,Supported_By__c FROM ';
        query += 'FIN_RCSAQ__c WHERE Control_Number__c LIKE \'' + nameLike + '%\'';
        if(String.isNotBlank(parentId)) query += ' AND FIN_RCSA__c = \'' + parentId + '\'';
        if (sortField != '') {
            query += ' order by ' + sortField;
            query += isAsc ? ' asc' : ' desc';
        }
        
        system.debug('The query is ' + query);
        return Database.query(query);
    }
    
    @AuraEnabled
    public static String getContactName(String conId) {
        String conName;
        List<Contact> conList = [Select Id,FirstName,LastName from Contact Where Id =: conId];
        if(conList.size() > 0)
            conName = String.isNotBlank(conList[0].FirstName) ? conList[0].FirstName + ' ' + conList[0].LastName : conList[0].LastName;
        System.debug(conName);
        return conName;
    }
    
    @AuraEnabled
    public static String getUserName(String conId) {
        String conName;
        List<User> conList = [Select Id,FirstName,LastName from User Where Id =: conId];
        if(conList.size() > 0)
            conName = String.isNotBlank(conList[0].FirstName) ? conList[0].FirstName + ' ' + conList[0].LastName : conList[0].LastName;
        System.debug(conName);
        return conName;
    }
    
    @AuraEnabled
    public static void updateAccount(List<FIN_RCSAQ__c> acc ){
        update acc;
    }
}

 
For some reason, my Contact object still shows existing contacts inside my unit tests even though I am not using seeAllData=true...
 
@isTest
public class TravelDetailGateway_Tests {
    @isTest
    public static void loadData_Tests() {
        Test.loadData(Account.sobjectType, 'test_data_accounts'); //file contains 10 rows.
        //contact in file is associated to account 9 in the file above.
        Test.loadData(Contact.sobjectType, 'test_data_contacts'); //file coontains 1 row.
        
        integer acctCount = [SELECT count() FROM Account];
        integer ctcCount = [SELECT count() FROM Contact];
        
        system.assertEquals(10, acctCount);
        system.assertEquals(1, ctcCount); //assertion fails and returns 11 records.
    }
}

 
Importing from this CSV file:
"OWNERID","STATUS","ORIGIN","SUBJECT","PRIORITY","DESCRIPTION"
"3D00G1U000002xbcg","New","EMAIL","New order.","HIGH","Seven TwentyOne Main"

Gives me this success message showing new ID :
"ID","OWNERID","STATUS","ORIGIN","SUBJECT","PRIORITY","DESCRIPTION","STATUS"
"5002900000BrQN4AAN","3D00G1U000002xbcg","Item Created","EMAIL","New subscription renewal order.","HIGH","Seven TwentyOne Main","Item Created"
A Case is created but the detail is missing, Origin is blank, owner is me, not the OwnerId, subject blank, descriptrion blank, Just ... Nothing but the defaults for Status and Priority

I disabled the trigger.
Hi I am somewhat of a novice when it comes to apex and can't seem to work out what the problem is with line 7 of my code. I am building a practice trigger that creates 10 identical opportunities whenever an account has more than 99 employees.

I think I have set up the for loop correctly but in the developer console 'Problem' there are a number of messages on line 7
- Expecting ';' but was a '<'
- Expecting ';' but was a ','
- Expecting ';' but was a ')'

Any suggestions?
trigger CreateTenOpps on Account (before insert) {
    
    List<Opportunity> TenOpps = New List<Opportunity>();
    
    for (Account acc : Trigger.new) {
        if (acc.NumberOfEmployees > 100) {
            for (Integer i = 0, i < 10, i++) {
                Opportunity opp = New Opportunity(CloseDate = date.today(), 
                                                  StageName = 'Prospecting', Name = 'Trigger Opp');
                TenOpps.add(opp);
            }
            insert TenOpps;
        }
    }

}

 
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.
I have a Master aura component containing 2 buttons to open another aura component - 1 for each button in the master component. I'm transferring the control using the Application Events from master component to the child component using the below code:

**MasterComponent.cmp:**
```
<aura:component implements = "flexipage:availableForAllPageTypes, flexipage:availableForRecordHome, force:hasRecordId" access = "global">
    <aura:attribute name = "recordId" type = "Id"/>
    <aura:registerEvent name = "SubmitCandidateEvent" type = "c:SubmitCandidateEvent"/>
    <aura:registerEvent name = "SubmissionConfirmationEvent" type = "c:SubmissionConfirmationEvent"/>
    <div>
        <lightning:button type = "button" iconName = "utility:text_template" variant = "brand" label = "Submission Confirmation Email" title = "Submission Confirmation Email" onclick = "{!c.submissionConfirmation}"/>
        <lightning:button type = "button" iconName = "utility:text_template" variant = "brand" label = "Submit Candidate" title = "Submission Confirmation Email" onclick = "{!c.submitCandidate}"/>
    </div>
</aura:component>
```
**MasterComponent.js**
```
({
    submissionConfirmation : function(component, event, helper) {
        console.log("Inside Submission Confirmation Master Component Controller");
        var submissionConfirmationEvent = $A.get("e.c:SubmissionConfirmationEvent");
        submissionConfirmationEvent.setParams({"submissionStatus":"SubmissionComponent"});
        console.log("SubmissionConfirmationEvent: "+submissionConfirmationEvent);
        submissionConfirmationEvent.fire();
        console.log("SubmissionConfirmationEvent fired");
    },
    
    submitCandidate : function(component, event, helper) {
        console.log("Inside Submit Candidate Master Submit Controller");
        var submitCandidateEvent = $A.get("e.c:SubmitCandidateEvent");
        submitCandidateEvent.setParams({"submitStatus" : "SubmitComponent"});
        console.log("SubmitCandidateEvent: "+submitCandidateEvent);
        submitCandidateEvent.fire();
        console.log("SubmitCandidateEvent fired");
    },
})
```
**SubmitCandidateEvent.evt**
```
<aura:event type="APPLICATION" description="Event template" >
    <aura:attribute name = "submitStatus" type = "String" />
</aura:event>
```
**SubmissionConfirmationEvent.evt**
```
<aura:event type="APPLICATION" description="Event template" >
    <aura:attribute name = "submissionStatus" type = "String" />
</aura:event>
```
**SubmitCandidateComponent.cmp**
```
<aura:component controller = "SubmitCandidateController" implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome" access="global">
    <aura:attribute name="recordId" type="String"/>
    <aura:attribute name="open" type="Boolean" default="false"/>
    <aura:attribute name = "isOpen" type = "Boolean" default = "false"/>
    <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
    <aura:handler event = "c:SubmitCandidateEvent" action = "{!c.openSubmitCandidate}"/>
    
    <aura:if isTrue = "{!v.isOpen}" >
        //doSomething
    </aura:if>
</aura:component>
```
**SubmitCandidateComponent.js**
```
({ openSubmitCandidate : function(component, event, helper) {
        console.log("In Submit Candidate Controller: Setting the open attribute");
        component.set("v.isOpen", true);
        var source = event.getSource();
        console.log("Source: "+source);
        var evt = $A.get("e.c:SubmitCandidateEvent");
        console.log("Submit Candidate Event: "+evt);
        var evtParam = evt.getParam("submitStatus");
        console.log("Event Param: "+evtParam);  
        alert(evtParam);
        var init = component.get("c.doInit");
        $A.enqueueAction(init);     
    },
})
```
**SubmissionConfirmationComponent.cmp**
```
<aura:component controller="SubmissionConfirmationEmailJobApplicant" implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId" access="global" >
    <aura:attribute name="recordId" type="Id"/>
    <aura:attribute name="open" type="Boolean" default="false"/>
    <aura:attribute name = "isOpen" type = "Boolean" default = "false"/>

    <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
    <aura:handler event = "c:SubmissionConfirmationEvent" action = "{!c.openSubmissionConfirmation}"/>
    
    <aura:if isTrue = "{!v.isOpen}" >
    //doSomething
    </aura:if>
</aura:component>
```
**SubmissionConfirmationComponent.js**
```

 ({ openSubmissionConfirmation : function(component, event, helper) {
        console.log("In Submission Confirmation Controller: Setting up the open attribute");
        component.set("v.isOpen", true);
        var source = event.getSource();
        console.log("Source: "+source);
        var evt = $A.get("e.c:SubmissionConfirmationEvent");
        console.log("Submission Confirmation Event: "+evt);
        var evtParam = evt.getParam("submissionStatus");
        console.log("Event Param: "+evtParam);
        alert(evtParam);
        var init = component.get("c.doInit");
        $A.enqueueAction(init);
    },
})
```

I can see the events being fired when the buttons are clicked. But I can't see the flow moving to the handler component. Handler code in the SubmitCandidateComponent and SubmissionConfirmationComponent not getting invoked, hence the application event handler not working as it should do. Kindly suggest what can be wrong in this code, its been hours I'm stuck on this piece of code. 
Thanks!
Hey there! 

I copied @Todd Kadas Trigger code from this forum: 
https://developer.salesforce.com/forums/?id=906F00000005G3yIAE

and tweaked it so it would work on SBQQ__Quote__c object in my org. But I have no idea how to build a test class so I can deploy it to prod. Can someone please help? 
 
trigger TriggerApprover on SBQQ__Quote__c (before update) {
    
       if(trigger.isUpdate){
             List<SBQQ__Quote__c> quoteList =  [Select id,
                                                   (Select Id, 
                                                         IsPending, 
                                                         ProcessInstanceId, 
                                                         TargetObjectId, 
                                                         StepStatus, 
                                                         OriginalActorId, 
                                                         ActorId, 
                                                         RemindersSent, 
                                                         Comments, 
                                                         IsDeleted, 
                                                         CreatedDate, 
                                                         CreatedById, 
                                                         SystemModstamp 
                                                    FROM ProcessSteps
                                                ORDER BY CreatedDate DESC) 
                                                    From SBQQ__Quote__c
                                                WHERE Id IN : Trigger.new];

             if(quoteList.size() > 0){

               for(SBQQ__Quote__c qt : quoteList){
              
                for(SBQQ__Quote__c qt1 : Trigger.new) {
                  
                         //check copy comment is true
                         if(qt.id == qt1.id && qt1.copy_comment__c) {
 
                           if (qt.ProcessSteps.size() > 0) {
                            
                         qt1.Approver_Comment__c = qt.ProcessSteps[0].Comments;
                         qt1.copy_comment__c = false;
                
                           }

                        }
                 
                    }
               }
             }   
        }  
    }

 
Hey Folks, I need to create an accessory visualforce page for Campaign, which lets a user quickly associate multiple leads to a campaign.
This is my Apex class and VFP: 
apex controller : -
public class CampaignLeads
{
public List<AddLeads> addFewLeads{get; set;}
public List<CampaignMember> campMems ;
public List<Id> ids;
public Campaign camp;
public CampaignLeads(ApexPages.StandardController sc)
{
ids = new List<Id>();
camp = new Campaign();
addFewLeads = new List<AddLeads>();
for(Lead lead: [SELECT Id, LastName FROM Lead WHERE Id NOT IN (SELECT LeadId FROM CampaignMember WHERE CampaignId =: ApexPages.currentPage().getParameters().get('id')) LIMIT 50 ])
{
AddLeads objAddLeads = new AddLeads(lead);
addFewLeads.add(objAddLeads);
}
campMems = new List<CampaignMember>();
}
public void insertLead()
{
camp = [SELECT Id FROM Campaign WHERE Id =: ApexPages.currentPage().getParameters().get('id')];
for(AddLeads addLead : addFewLeads)
{
if(addLead.selected == true)
{
CampaignMember campMem = new CampaignMember();
campMem.CampaignId = camp.Id;
campMem.LeadId = addLead.lead1.Id;
campMems.add(campMem);
}
}
insert campMems;
}
public class AddLeads
{
public Lead lead1{get; set;}
public Boolean selected{get; set;}
public AddLeads(Lead wrpLead)
{
lead1 = wrpLead;
selected = false;
}
}
}
Visualforce Page :-
<apex:page standardController="Campaign" extensions="CampaignLeads" >
<apex:form id="formID">
<apex:pageBlock >
<apex:pageBlockButtons >
<apex:commandButton value="Insert Lead" reRender="formID" action="{!insertLead}" oncomplete="CampaignPage()" />
</apex:pageBlockButtons>
<apex:pageBlockTable value="{!addFewLeads}" var="le" columns="4">
<apex:column headerValue="Select">
<apex:inputCheckbox value="{!le.selected}"/>
</apex:column>
<apex:column value="{!le.lead1.LastName}">
</apex:column>
</apex:pageBlockTable>
</apex:pageBlock>
</apex:form>
<script>
function CampaignPage()
{
window.top.location='/{!Campaign.Id}';
}
</script>
</apex:page>

but this is not working. Can someone help in figuring out the possible error
Hi,

I need help in writting test class for below written batch class.

Can anyone help please?

global class UpdateCurrentMonth implements Database.Batchable<sObject>,Schedulable, Database.stateful
{

  global void execute(SchedulableContext sc)
    {
        
    }


   global Database.queryLocator start(Database.BatchableContext BC )
   {
        String str = 'SELECT Id, Start_Date__c,End_Date__c,Current_Month__c FROM Business_Re_development_Target__c';
        return Database.getQueryLocator(str);
        
   }
    
    global void execute(Database.BatchableContext BC, List<Business_Re_development_Target__c> BRTToProcess)
     {
     List<Business_Re_development_Target__c> BRTList = new List<Business_Re_development_Target__c>();
       for(Business_Re_development_Target__c BRTObj : BRTToProcess){
       
       If(Date.Today().Year()  == BRTObj.End_Date__c.Year()){
      
       If(Date.Today().Month()  > BRTObj.End_Date__c.month())
       {
       
               BRTObj.Current_Month__c = False;
            BRTList.add(BRTObj);
            }            
            }
        
        else
         
       If(Date.Today().Year() > BRTObj.End_Date__c.Year()){
      
       If(Date.Today().Month()  < BRTObj.End_Date__c.month())
       {
       
               BRTObj.Current_Month__c = False;
            BRTList.add(BRTObj);
            }            
            }
               
            
          }
        update BRTList;
        }
   global void finish(Database.BatchableContext BC)
    {
   system.debug('finish');     
    }    
}
    
     

    
I have a fairly simple controller that queries a record and references values from the record in order to render other VF pages.

How can I write a test class for this Controller?
public class MyController {
    
 public Account account  { get; set; }
        
        public MyController() {
        account = [SELECT Id, Name, Billing_Tier__c, Primary_Contact_Full_Name__C,Secondary_Contact_Full_Name__c,One_Line_Address__c FROM Account
                   WHERE Id = :ApexPages.currentPage().getParameters().get('id')];

	}
}

 
Hi All

 


 <apex:pageBlock rendered="{!lstud.size>0}">
            <apex:pageBlocksection>
           <apex:pageBlockTable value ="{!lstud}" var="act">
                <apex:column value="{!act.acc.Name}"/>
                <apex:column value="{!act.acc.Phone}"/>
                <apex:column value="{!act.acc.Industry}"/>
                <apex:column value="{!act.con.LastName}"/>
                <apex:column value="{!act.con.FirstName}"/>
           </apex:pageBlockTable>
              </apex:pageBlocksection>
        </apex:pageBlock>


I am getting this below error on the tab.

The value 'null' is not valid for operator '>'
Error is in expression '{!lstud.size>0}' in component <apex:pageBlock> in page list_accountinfo_vfp

Hi Team,
Parent: Opportunity
Child: Opportunity Member
 I want to update an existing child of an opportunity if a field with the name primary is true on the existing child(Primary child) when a new child is inserted. We can only have one primary member(child record ) for the opportunity.  There is a field Amount on the Opportunity Member object and I want to update this field by subtracting the Amount of New Opportunity member(that we are inserting) from Primary Opportunity Member(an existing record).

My Code is working fine for a single record but not working as expected for bulk operation. Please help

Thank you

public class OppotunityMemberTriggerhandler{
 
   public static void afterInsert(List<Opportunity_Member__c> newoppMember){
          Set<Id> oppIdSet = new Set<Id>();
          List<Opportunity_Member__c> memberList = new List<Opportunity_Member__c>();
          Map<id,Opportunity_Member__c> oppMemberMap = new Map<id,Opportunity_Member__c>();
          List<Opportunity_Member__c> updatedMemberList = new List<Opportunity_Member__c>();
          
          
          for(Opportunity_Member__c newMember : newoppMember){
             oppIdSet.add(newMember.Opportunity__c);
          }
          if(oppIdSet.size()>0){
             memberList = [SELECT id,Amount__c,Opportunity__c,Primary__c FROM Opportunity_Member__c WHERE Opportunity__c IN :oppIdSet AND Primary__c = True ];
          }
          for(Opportunity_Member__c member : memberList){
            oppMemberMap.put(member.Opportunity__c,member);

          }
          for(Opportunity_Member__c oppMember : newoppMember){
              if(oppMember.Primary__c == False){
                for(Opportunity_Member__c primaryMember : memberList){
                    primaryMember.Amount__c = oppMemberMap.get(oppMember.Opportunity__c).Amount__c - oppMember.Amount__c;
                    updatedMemberList.add(primaryMember);
                 }
             }
          }
          update updatedMemberList;
   }    
}

Hello, I'm trying to convert my trigger to a batch class. Can anyone help me with this one, I would much appreciate:

 

trigger SetTitleToAttachment on Attachment (before insert) { 
//store the id of the WO related to the attachment
 List<String> woIDs= new List<String>();
    for (Attachment  orderRec : Trigger.new) {
        woIDs.add(orderRec.ParentID);
    }
System.Debug('>>>>'+woIDs);

//store the work order(s) where the ID in woIDs
Map<String, SVMXC__Service_Order__c > woByIds= new Map<String, SVMXC__Service_Order__c >([
        SELECT Id, Name, SVMX_PS_Ship_To_Name__c, SVMXC__Order_Type__c, SerialNumberIP__c
        FROM SVMXC__Service_Order__c 
        WHERE Id =: woIDs
    ]);
  
//change the name of the attachment
 System.debug('woByIds'+ woByIds);
        for(Attachment a: Trigger.new){
           SVMXC__Service_Order__c workorder = woByIds.get(a.ParentId);
            System.debug('workorder '+ workorder );
                if(workorder != null){
                    if(a.Name.startsWith('SIG_Work_Order_Service__Reports')){
                        a.Name =  'SR'+ '_'+  date.today().format()+ '_'+workorder.SVMX_PS_Ship_To_Name__c+ '_' + workorder.Name+ '_'+ workorder.SVMXC__Order_Type__c+'_'+ workorder.SerialNumberIP__c +'.pdf';
                    }
                    else if (a.Name.startsWith('SIG_HandoverCheckList_Customer_To_SIG_Report')){
                        a.Name = 'Handover Customer To SIG' +'.pdf';
                    } 
                    else if (a.Name.startsWith('SIG_HandoverCheckList_SIG_To_Customer')){ 
                        a.Name = 'Handover SIG_To_Customer'+'.pdf';
                    }
                    else if (a.Name.startsWith('SIG_Work_Order_Service')){ 
                        a.Name = 'SR'+ '_'+  date.today().format()+ '_'+workorder.SVMX_PS_Ship_To_Name__c+ '_' + workorder.Name+ '_'+ workorder.SVMXC__Order_Type__c+'_'+ workorder.SerialNumberIP__c+'.pdf' ;
                    }
                }
             
         } 

}
public with sharing class OppSearch {
    
    public List<Opportunity> OppList { get; set; }
    
    public String searchText { get; set; }
    public static Id selectedRec {get;set;}
    public integer totalRecs = 0;
    public integer OffsetSize = 0;
    public integer LimitSize= 5;
    public OppSearch()
    {
        
        OppList = new List<Opportunity>();
        
    }
    
    public PageReference searchOpportunity()
        
    {
        OppList = new List<Opportunity>();
        
        if(String.isBlank(searchText))
        {
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Please enter some value'));
        }
        
        
        
        if(String.isNotBlank(searchText))
        {
            if(searchText.isNumeric())
            {
                Decimal searchstringDouble = decimal.valueOf(searchText);
                
                OppList = [select Id,Name,Account.Name,StageName,Type,Amount,CloseDate
                           
                           from Opportunity
                           
                           where Amount=:searchstringDouble LIMIT :LimitSize OFFSET :OffsetSize];
                totalRecs = OppList.size();
                
                if(OppList.size()==0)
                {
                    ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Search failed as criteria do not match'));
                }
                
            }
            else {
                String newSearchText = searchText+'%';
                
                OppList =[select Id,Name,Account.Name,StageName,Type,Amount,CloseDate
                          
                          from Opportunity
                          where Name like:newSearchText or Account.Name like:newSearchText
                          or StageName like:newSearchText or Type like:newSearchText LIMIT :LimitSize OFFSET :OffsetSize];
                totalRecs = OppList.size();
                
                if(OppList.size()==0)
                {
                    ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Search failed as criteria do not match'));
                }
                
            }
            
        }
        return null;
    }
    public pageReference FirstPage()
    {
        OffsetSize = 0;
        searchOpportunity();
        return null;
    }
    public pageReference previous()
    {
        OffsetSize = OffsetSize - LimitSize;
        searchOpportunity();
        return null;
    }
    public pageReference next()
    {
        OffsetSize = OffsetSize + LimitSize;
        
        searchOpportunity();
        return null;
    }
    public pageReference LastPage()
    {
        OffsetSize = totalrecs - math.mod(totalRecs,LimitSize);
        
        searchOpportunity();
        return null;
    }
    public boolean getprev()
    {
        if(OffsetSize == 0)
            return true;
        else
            return false;
    }
    public boolean getnxt()
    {
        if((OffsetSize + LimitSize) > totalRecs)
            
            return true;
        else
            return false;
    } 
    public static HttpResponse sendData()
    {
        Opportunity op=[select Id,Name,Account.Name,StageName,Type,Amount,CloseDate
                        
                        from Opportunity
                        
                        where Id = :selectedRec];
        
        JSONGenerator gen = JSON.createGenerator(true);   
        gen.writeStartObject();     
        gen.writeStringField('Name ', op.Name);
        
        gen.writeStringField('Account',op.Account.Name);
        gen.writeStringField('Stage',op.StageName);
        gen.writeStringField('Type',op.Type);
        gen.writeNumberField('Amount',op.Amount);
        gen.writeDateField('Close Date',op.CloseDate);
        gen.writeEndObject();   
        String jsonS = gen.getAsString();
        System.debug('jsonMaterials'+jsonS);
        
        // Sending the http body with JSON
        
        Http http = new Http();
        HttpRequest request = new HttpRequest();
        request.setEndpoint('https://th-apex-http-callout.herokuapp.com/animals');
        request.setMethod('POST');
        request.setHeader('Content-Type', 'application/json;charset=UTF-8');
        // Set the body as a JSON object
        request.setBody(jsonS);
        HttpResponse response = http.send(request);
        if (response.getStatusCode() != 201)
        {
            Opportunity o= [select Integration_Comments__c,Integration_Status__c from Opportunity
                            where Id =:selectedRec];  
            o.Integration_Status__c='Not Successful';
            o.Integration_Comments__c=response.getStatus();
            update o;
            System.debug(response.getStatusCode());
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Opps! your Callout was not successful'));
        }
        
        else {
            
            Opportunity o= [select Integration_Comments__c,Integration_Status__c from Opportunity
                            where Id =:selectedRec]; 
            
            o.Integration_Status__c='Success';
            o.Integration_Comments__c='Success';
            update o;
            System.debug(response.getStatusCode());
        }
      return response;
    }
    
}
 

Hi Coders, I am new to Coding and took a task to write a test class. I am working for a Leave management App and made my coverage for 65%. I am not understading why my for loop is not covered in coverage. your help is greatly appreciated !!


This my Class: (Bold code is NOT in coverage)
trigger OnLeaveApproval on Leaves__c (after update)
{
    
for(Leaves__c obj: Trigger.new)
{
    map<string, Object> leaveMap = new map<string, Object>();
    system.debug('coming here 1');   
    if (obj.Approval_Status__c != Null && obj.Approval_Status__c == 'Approved')
    {
            system.debug('coming here 1.2'+ obj.CreatedById); 
            system.debug('coming here 1.2'+ obj.Contact_ID__c); 
            system.debug('name'+ obj.Name);
            system.debug('coming here 1.2.1'+ obj); 
            leaveMap.put(obj.Contact_ID__c, obj.Req_Days_Off__c);
            system.debug('coming here 2'); 
    }
    system.debug('coming here 2.1' + leaveMap);
    if(leaveMap.size() > 0 ) {
  
            list<Contact> contact = [SELECT Id,Total_Available_Leaves__c,OwnerId FROM Contact WHERE  Id IN :leaveMap.KeySet()];
            system.debug('coming here 3' + contact); 
            list<Monthly_Take_Home__c> employeePayroll = [SELECT Id,Unpaid_Days__c, Paid_Days__c, Salary__c,Emp_Salary__c,Current_PayPeriod_Salary__c FROM Monthly_Take_Home__c WHERE Contact_ID__c IN :leaveMap.KeySet()];
            system.debug('coming here 3.1' + employeePayroll);
            list<Contact> contactUpdatelist = new list<Contact>();
            list<Monthly_Take_Home__c> employeePayrolllist = new list<Monthly_Take_Home__c>();
            for(Contact c: contact)
                {
                    system.debug('coming here 4'+ contact); 
                    //Integer totalApprovedLeaves = leaveMap.get(c.Name);
                    Integer totalApprovedLeaves = Integer.valueOf(leaveMap.get(c.Id));
                    if( c.Total_Available_Leaves__c - totalApprovedLeaves < 0 ) {
                        
                            system.debug('coming here 5'+c.Total_Available_Leaves__c); 
                             Integer lossOfPayDays = totalApprovedLeaves - c.Total_Available_Leaves__c.intValue();
                             system.debug('coming here 5.1'+ lossOfPayDays);
                            for(Monthly_Take_Home__c empPayroll: employeePayroll)
                            {
                                
                                  if(empPayroll.Unpaid_Days__c !=null)
                                      lossOfPayDays = lossOfPayDays + empPayroll.Unpaid_Days__c.intValue();
                                system.debug('coming here 5.1'+ lossOfPayDays);
                                system.debug('coming here 6.0'+empPayroll.Paid_Days__c); 
                                Integer totalPayDates = empPayroll.Paid_Days__c.intValue() - lossOfPayDays;
                                system.debug('totalPayDates 6'+totalPayDates); 
                                Double calculatedSalary =  Double.valueOf(empPayroll.Emp_Salary__c/empPayroll.Paid_Days__c.intValue());
                                system.debug('empPayroll.Salary__c 0'+ empPayroll.Emp_Salary__c);
                                system.debug('totalPayDates'+ totalPayDates);
                                system.debug('lossOfPayDays'+ lossOfPayDays);
                                empPayroll.Current_PayPeriod_Salary__c = (calculatedSalary * totalPayDates) ;
                                system.debug('totalSalary'+ calculatedSalary * totalPayDates);
                                empPayroll.Unpaid_Days__c = lossOfPayDays;
                                system.debug('empPayroll.Current_PayPeriod_Salary__c'+ empPayroll.Current_PayPeriod_Salary__c);
                                system.debug('calculatedSalary'+ calculatedSalary);     
                                employeePayrolllist.add(empPayroll);
                            }
                        c.Total_Available_Leaves__c = 0;
                    } else {
                        
                        c.Total_Available_Leaves__c =
c.Total_Available_Leaves__c - totalApprovedLeaves;
                    }
                    contactUpdatelist.add(c);
            }
            if(contactUpdatelist.size() > 0)
            {
                system.debug('coming here 7'+ contactUpdatelist); 
                update contactUpdatelist;
            }

            if(employeePayrolllist.size() > 0)
            {
                system.debug('coming here 8'+ employeePayrolllist); 
                update employeePayrolllist;
            }
        }
}
}


This my Test Class: Covered 65% of code
@isTest
private class OnLeaveApprovalTest {
 
@isTest
public static void CreateContactAndLeaveReq(){
test.startTest(); 

// Test data setup - Create a new Employee contact
Contact emp = new Contact ();
emp.FirstName = 'Jon';
emp.LastName = 'Snow';
emp.Emp_ID__c = 'Sp-343245';
emp.Total_Available_Leaves__c = 4;
emp.Emp_Salary__c = 10000;
    
insert emp;
system.debug(emp);

Contact EmpInfo = [Select Name,Id from Contact Where id =: Emp.Id]; 

//Enter record details on Leaves Object
Leaves__c leaveReq = new Leaves__c();
leaveReq.Employee_Name__c = EmpInfo.Id;
leaveReq.Request_Start_Date__c = date.newInstance(2020,06,10);
leaveReq.Request_End_Date__c = date.newInstance(2020,06,15);
leaveReq.Contact_ID__c = Emp.Id;

Insert leaveReq;
system.debug(leaveReq);


leaveReq.Approval_Status__c = 'Approved';
Update leaveReq;
    
Monthly_Take_Home__c TakeHome = new Monthly_Take_Home__c();
TakeHome.Employee_Name__c = EmpInfo.Id;
TakeHome.Salary_Start_Date__c = date.newInstance(2020,06,01);
TakeHome.Salary_End_Date__c = date.newInstance(2020,06,30);
TakeHome.Unpaid_Days__c = 6;
TakeHome.Contact_ID__c = Emp.Id;

Insert TakeHome;
test.stopTest();   
}
}

The initial value for a number field on a record is 1. A user updated the value of the number field to 10. This action invokes a workflow field update, which changes the value of the number field to 11. After the workflow field update, an update trigger fires.
What is the value of the number field of the object that is obtained from Trigger.old?

A. Null

B. 11 (Since 11 will be the immediate previous value before update, so i am considering it correct)

C. 1

D. 10

 Is it 11 or 1 ? And How ?
I want to sort String values from a custom field from custom settings. I had no issues with the code but I get the error "Method does not exist or incorrect signature: void ascending() from the type anon'

Here's my code:
public class SortNumbersFromCustomSetting {
	static Dev_Bootcamp__c value = Dev_Bootcamp__c.getInstance();
    
    static List<String> ListStringValue = new List<String>(value.Random__c.split('-'));
    
   		public static List<Integer> ascending(){
         List<Integer> ListIntValue = new List<Integer>();
            for(String str:ListStringValue){
                ListIntValue.add(Integer.valueOf(str));
            }
         ListIntValue.sort();
         Set<Integer> SetIntValue = new Set<Integer>(ListIntValue);
         List<Integer> FinalValue = new List<Integer>(SetIntValue);
         return FinalValue;
     }
    public static List<Integer> descending(){
        List<Integer> Temp = ascending();
        List<Integer> DescIntValue = new List<Integer>();
        for(Integer i = Temp.size()-1; i>=0; i--){
            DescIntValue.add(Temp.get(i));
        }
        return DescIntValue;
    }
}

 
public with sharing class OppSearch {
    
    public List<Opportunity> OppList { get; set; }
    
    public String searchText { get; set; }
    public Id selectedRec {get;set;}
    
    public OppSearch()
    {
        
        OppList = new List<Opportunity>();
        
    }
    
    public PageReference searchOpportunity()
        
    {
        OppList = new List<Opportunity>();
        
        if(String.isBlank(searchText))
        {
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Please enter some value'));
        }
        
        
        
        if(String.isNotBlank(searchText))
        {
            if(searchText.isNumeric())
            {
                Decimal searchstringDouble = decimal.valueOf(searchText);
                
                OppList = [select Id,Name,Account.Name,StageName,Type,Amount,CloseDate
                           
                           from Opportunity
                           
                           where Amount=:searchstringDouble ]; 
                
                if(OppList.size()==0)
                {
                    ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Search failed as criteria do not match'));
                }
                
            }
            else {
                String newSearchText = searchText+'%';
                
                OppList =[select Id,Name,Account.Name,StageName,Type,Amount,CloseDate
                          
                          from Opportunity
                          where Name like:newSearchText or Account.Name like:newSearchText
                          or StageName like:newSearchText or Type like:newSearchText];
                
                if(OppList.size()==0)
                {
                    ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Search failed as criteria do not match'));
                }
                
            }
            
        }
        return null;
    }
}
I have a trigger that is effectively checking a custom list to match the Close Date with the Start/End dates for weeks so a custom field is populated with the text of the Start and End dates.

Trigger:
trigger CloseWeekUpdate on Opportunity (before insert, before update) {
    Try{
        for(Opportunity opp : trigger.new){
            if(opp.CloseDate != NULL){
                system.debug('opp.CloseDate = ' + opp.CloseDate);
                for(CloseDateWeek__c rec : CloseDateWeek__c.getAll().values()){
                    if (opp.CloseDate >= rec.WeekStartDate__c && opp.CloseDate <= rec.WeekEndDate__c){
                        system.debug('rec.WeekStartDate__c = ' + rec.WeekStartDate__c);
                        system.debug('rec.WeeEndDate__c = ' + rec.WeekEndDate__c);
                        opp.Close_Week__c = rec.WeekStartDate__c.format() + ' - ' + rec.WeekEndDate__c.format();
                        system.debug('rec.Close_Week__c = ' + opp.Close_Week__c);
                        break;
                    }
                }
            }
        }
    }
    Catch(Exception Ex){
        system.debug('Exception Details = ' + Ex);
    }


I have built a test class to insert a test Opportunity and I am getting to 50% but unable to get higher, how do I get the class to test the following lines from the Trigger?

Lines that are not testing:

- for(CloseDateWeek__c rec : CloseDateWeek__c.getAll().values()){
- if (opp.CloseDate >= rec.WeekStartDate__c && opp.CloseDate <= rec.WeekEndDate__c){
- opp.Close_Week__c = rec.WeekStartDate__c.format() + ' - ' + rec.WeekEndDate__c.format();

Here is the Test class I have:
@isTest
    public class TestCloseWeekUpdate {
        static testMethod void testCloseWeek(){
            Opportunity to = new Opportunity();
            to.Name = 'Test Name';
            to.CloseDate = Date.newInstance(2020,06,06);
            to.StageName = 'Closed Won';
            to.Start_Date__c = Date.newInstance(2020,06,01);
            to.Type = 'New Business';
            to.Market__c = 'Large';
            to.Premium__c = TRUE;
            to.Startup_Needed__c = 'Yes';
            insert to;
            test.startTest();
            try{
                to.Close_Week__c = '5/31/2020 - 6/6/2020';
            }
            Catch (Exception ee){}
            test.stopTest();
        }
    }


Any help with getting that last 3 lines covered is greatly appreciated! 
Hi, I am new to LWC ​​​​​​, trying dynamically add/remove rows for a table scenario. I can able to add the row by click on the + button. After added that rows I want to enter some values in text boxes and save into account object by click on save buttton. Also do the delete action as well to delete the specific row by click on delete button. 

I am facing issue with save & delete records. How I can solve this? Can anyone give me some guidence to solve.

AddDeleteRow
dynamicAddRow.html

<template>
                  
    <div class="slds-m-around--xx-large">
        <div class="slds-float_right slds-p-bottom_small">
            <h1 class="slds-page-header__title">Add Row
                <lightning-button-icon icon-name="utility:add"  size="large" variant="bare" alternative-text="Add" onclick={addRow}> </lightning-button-icon>
            </h1>
        </div>
        <div class="container-fluid">        
            <table class="slds-table slds-table_bordered slds-table_cell-buffer"> 
                <thead>
                    <tr class="slds-text-title_caps">
                        <th scope="col">
                            <div class="slds-truncate">#</div>
                        </th>
                        <th scope="col">
                            <div class="slds-truncate" title="Account Name">Account Name</div>
                        </th>
                        <th scope="col">
                            <div class="slds-truncate" title="Account Number">Account Number</div>
                        </th>
                        <th scope="col">
                            <div class="slds-truncate" title="Phone">Phone</div>
                        </th>
                        <th scope="col">
                            <div class="slds-truncate" title="Action">Action</div>
                        </th>
                    </tr>
                </thead>   
                <tbody>      
                    
                    <template for:each={accountList} for:item="acc" for:index="index">
                        <tr key={acc.Id}> 
                            <td>{index}</td>                                                  
                            <td>
                                <lightning-input label="Name" value={acc.Name} onchange={handleNameChange}></lightning-input>                               
                            </td>
                            <td>
                                <lightning-input label="Account Number" value={acc.AccountNumber} onchange={handleAccountNumberChange}></lightning-input>                        
                            </td>
                            <td>
                                <lightning-input label="Phone" value={acc.Phone} onchange={handlePhoneChange}></lightning-input>
                            </td>
                            <td>
                                <a onclick={removeRow}> 
                                    <lightning-icon icon-name="utility:delete" size="small" style="margin-top: -4px; margin-right: 0px;" ></lightning-icon>
                                    <span class="slds-assistive-text">Delete</span>
                                </a>
                            </td> 
                        </tr>
                    </template>
                     
                </tbody>
            </table>
            <div class="slds-align_absolute-center slds-p-top_small">                
                <lightning-button name="Save" label="Save" onclick={saveRecord} ></lightning-button>
            </div>
        </div>
    </div>

</template>
 
dynamicAddRow.js

import { LightningElement, track,api } from 'lwc';
import ACCOUNT_OBJECT from '@salesforce/schema/Account';
import NAME_FIELD from '@salesforce/schema/Account.Name';
import ACCOUNTNUMBER_FIELD from '@salesforce/schema/Account.AccountNumber';
import PHONE_FIELD from '@salesforce/schema/Account.Phone';
import saveAccounts from '@salesforce/apex/AccountController.saveAccounts';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
export default class CreateDynamicRecord extends LightningElement {
    @track accountList = []; 
    @track index = 0;
    @api recordId;
    @track name = NAME_FIELD;
    @track industry = ACCOUNTNUMBER_FIELD;
    @track phone = PHONE_FIELD;

    @api record = {
        firstName : '',
        lastName : '',
        Email : '',
        Phone : '',
        Title : ''
    }

    addRow(){

        this.index++;
   
        this.accountList.push ({
            sobjectType: 'Account',
            Name: '',
            AccountNumber : '',
            Phone: ''
        });

        console.log('Enter ',this.accountList);
        
       // this.accountList.push(this.record);
        //console.log(' After adding Record List ', this.accountList);
    }
    
    removeRow(){

        var index = this.index;
      
        if(this.accountList.length>1)
           this.accountList.splice(index, 1);

        //this.dispatchEvent(new CustomEvent('deleterow', {detail: this.index}));
        //console.log(' After adding Record List ', this.dispatchEvent);
    } 

    acc = {
        Name : this.name,
        AccountNumber : this.accNumber,
        Phone : this.phone
    }

    handleNameChange(event) {
        this.acc.Name = event.target.value;
        console.log("name", this.acc.Name);
    }
    
    handleAccountNumberChange(event) {
        this.acc.AccountNumber = event.target.value;
        console.log("AccountNumber", this.acc.AccountNumber);
    }
    
    handlePhoneChange(event) {
        this.acc.Phone = event.target.value;
        console.log("Phone", this.acc.Phone);
    }
    
    saveRecord(){        
        saveAccounts(this.acc.accountList)
            .then(result => {
                this.message = result;
                this.error = undefined;
                if(this.message !== undefined) {
                    this.acc.Name = '';
                    this.acc.AccountNumber = '';
                    this.acc.Phone = '';
                    this.dispatchEvent(
                        new ShowToastEvent({
                            title: 'Success',
                            message: 'Account created successfully',
                            variant: 'success',
                        }),
                    );
                }
                
                console.log(JSON.stringify(result));
                console.log("result", this.message);
                /*console.log(' After adding Record List ', result);
                this.accountList = result;
                console.log(' After adding Record List ', this.accountList);*/
            })
            .catch(error => {
                this.message = undefined;
                this.error = error;
                this.dispatchEvent(
                    new ShowToastEvent({
                        title: 'Error creating record',
                        message: error.body.message,
                        variant: 'error',
                    }),
                );
                console.log("error", JSON.stringify(this.error));
            });
    }
      
}
 
AccountController.apex  

public with sharing class AccountController { 
 
    @AuraEnabled( cacheable = true ) 
    public static List< Account > getAccounts() { 
      
        return [ SELECT Id, Name, Industry FROM Account LIMIT 10 ]; 
         
    } 
     
    @AuraEnabled( cacheable = true )
    public static void saveAccounts(List<Account> accList){
        Insert accList;
        /*if(accList.size()>0 && accList != null){
            insert accList;
        }*/
    } 
}
Thanks 
Siva
 
Hi All,
I need to create a table to take input from the user. The table should have dynamic row addition/deletion capability as well. Any help will be really appreciated. I have just started using LWC in my project and i am little flustered to accomplish this requiremnt
TIA
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