• sumit suwalka
  • SMARTIE
  • 525 Points
  • Member since 2018

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 265
    Questions
  • 248
    Replies
HI All,
        I have a trigger in which i am deleting asset when its related opportunity line item is deleted but its giving me error that list  System.QueryException: List has more than 1 row for assignment to SObject
        How to solve this error? 
         My trigger helper is given below:-
         public  without sharing class OpportunityLineItemTriggerHelper {
    
    public static List<OpportunityLineItem> newOpportunityLineItem = new List<OpportunityLineItem>();
    public static List<OpportunityLineItem> oldOpportunityLineItem = new List<OpportunityLineItem>();
    public static Map<Id, OpportunityLineItem> newMapOpportunityLineItem = new Map<Id, OpportunityLineItem>();
    public static Map<Id, OpportunityLineItem> oldMapOpportunityLineItem = new Map<Id, OpportunityLineItem>(); 
    
    Public static void deleteAssets( ){
        
        Set<Id> applicableOppIds = new Set<Id>();
        for( OpportunityLineItem oli : oldOpportunityLineItem ){
            
            applicableOppIds.add( oli.OpportunityId );
        }
        
        
        
        Map<String, Asset> mapOfProCodeToAsset = new Map<String, Asset>();
        List<Asset>  ListAsset = [Select Id, Product2.ProductCode, AccountId From Asset ];
        
        for( Asset ast : ListAsset ){
            String uniqueId = ast.Product2.ProductCode + '-' + ast.AccountId;
            mapOfProCodeToAsset.put( uniqueId,ast );
        }
        System.debug('mapOfProCodeToAsset'+mapOfProCodeToAsset);
        
        List<Asset> deleteListAsset = new List<Asset>();
        //Collecting all child records related to Parent records
        for( Opportunity oppObj : [ SELECT Id, Name, StageName, AccountId, Account.Name,
                                   ( SELECT Id, Name, OpportunityId, Current_Year__c, 
                                    Product2Id, Product2.Name,Product2.ProductCode, Product2.Family, 
                                    Product2.AcctSeedERP__Inventory_Asset__c, Quantity, Description
                                    FROM OpportunityLineItems 
                                    Where Id In : oldMapOpportunityLineItem.keySet() )
                                   FROM Opportunity
                                   WHERE  Id IN :applicableOppIds
                                   
                                  ] ){
                                      
                                      for( OpportunityLineItem oppLine : oldOpportunityLineItem ){
                                          Id prod = oppLine.Product2Id;
                                          //Opportunity opp = oppLine.Opportunity;
                                          System.debug('product'+prod);
                                          String uniqueId = oppLine.ProductCode + '-' + oppObj.AccountId;
                                          System.debug('UniqueListAsset'+uniqueId);
                                          if(mapOfProCodeToAsset.containsKey(uniqueId)){
                                              System.debug('#####' );
                                              deleteListAsset.add(mapOfProCodeToAsset.values());
                                              System.debug('deleteListAsset'+deleteListAsset.Size());
                                          }
                                          
                                      }
                                  }
        System.debug('deleteListAsset'+deleteListAsset);
        if( deleteListAsset.Size() > 0 ){
            delete deleteListAsset;
        }
    }
}
Hi All,
I want to delete assets when its related opportunity line item is deleted.
i have a trigger helper given below:-
public  without sharing class OpportunityLineItemTriggerHelper {
    
    public static List<OpportunityLineItem> newOpportunityLineItem = new List<OpportunityLineItem>();
    public static List<OpportunityLineItem> oldOpportunityLineItem = new List<OpportunityLineItem>();
    public static Map<Id, OpportunityLineItem> newMapOpportunityLineItem = new Map<Id, OpportunityLineItem>();
    public static Map<Id, OpportunityLineItem> oldMapOpportunityLineItem = new Map<Id, OpportunityLineItem>(); 
    
    Public static void deleteAssets(){
        
        list<id> ProductIds=new list<id>();
        for(Product2 prod :  [SELECT id,Name
                              FROM Product2 
                              ] )
        {
            ProductIds.add(Prod.id);
        }  
        List<Asset> deleteListAsset = new List<Asset>();
        //Collecting all child records related to Parent records
        list<Asset> listOfAssets = [ select id, Product2Id 
                                     from Asset 
                                     where Product2Id in :ProductIds ];
        for(OpportunityLineItem oli : oldOpportunityLineItem){
            for(Asset ast : listOfAssets){
                if (ast.Product2Id == oli.Product2Id){
                    deleteListAsset.add(ast);
                    
                }
             }
            System.debug('deleteListAsset'+deleteListAsset);
        }
        
        system.debug('listOfAssets'+listOfAssets);
        //deleting Asset records
        if( deleteListAsset.Size() > 0 ){
             delete deleteListAsset;
        }
     }
 }
Can anyone help me with this requirement if i am doing it wrong?
Any suggestions?
Hi All,
         I have a requirement in which i want to delete assets when related opportunity Line item is deleted.
Can anyone help me with this trigger as i dont know the relationship between assets and Opportunity Lineitem?
Any suggestions?
 Hi All,
       i have a Batch in which I want that the total of (Case_Age_Days__c) for all Cases related to account should populate in a field of account.
       Can anyone help me out with this ?
public without sharing class BatchServiceScore implements Database.Batchable<sObject>,Database.Stateful{
    
    public static Date backDate = System.Today().addDays(-365); 
    public static void run( Set<Id> AccIds ) {
        List<Account> accountRecords =  [ SELECT Id, Service_Score__c,NPS_Score__c,Customer_Satisfaction_Score__c,
                                         Customer_Effort_Score__c
                                          FROM Account WHERE ID IN : AccIds
                                        ];
        executeHelper( accountRecords );                  
    }
    
    public Database.querylocator start(Database.BatchableContext BC){
        return Database.getQueryLocator([ SELECT Id, Service_Score__c,NPS_Score__c,Customer_Satisfaction_Score__c,
                                         Customer_Effort_Score__c
                                          FROM Account
                                        ]);
    }
    
    public void execute(Database.BatchableContext BC, List<Account> scope){
        
        executeHelper( scope );
    }
    
    public static void executeHelper( List<Account> scope ) {
        
        List<Account> accsToUpdate = new List<Account>();
        Map<Id, Account> mapAccountsWithCases = new Map<Id, Account>([ Select Id,
                                                                     ( SELECT Id, AccountId, Case_Age_Days__c, 
                                                                      Is_Negative_Case__c,Total_Case_Minutes_Per_Month__c 
                                                                       FROM Cases
                                                                       WHERE CreatedDate >=: System.today().addDays(-365) 
                                                                     )
                                                                      From Account
                                                                      Where Id in :scope 
                                                                     ]);
        
        for( Account acct : scope ){
            
             Decimal avgCaseAgeScore = 0;
             Decimal caseHoursCountScore = 0;
             Decimal caseRecordCountScore = 0;
             Decimal service_Score = 0;
            
             List<Case> accountCases = mapAccountsWithCases.get( acct.Id ).Cases;
             accountCases = accountCases == null ? new List<Case>() : accountCases;
             Decimal totalCases = accountCases.size();
             System.debug('Total cases:-'+totalCases);
             
             if( totalCases == 0 ){
                caseRecordCountScore = 0;
            }
            else if( totalCases <= 5  ){
                caseRecordCountScore = 25;
            }
            else if( totalCases <= 15  ){
                caseRecordCountScore = 20;
            }
            else if( totalCases <= 30  ){
                caseRecordCountScore = 10;
            }
            else if( totalCases > 30  ){
                caseRecordCountScore = 5;
            }
            System.debug('caseRecordCountScore:-'+caseRecordCountScore);
           
             Decimal AccountCaseAge = 0;
             Decimal AvgAccCaseAge = 0;
             Decimal CaseHoursCount = 0;
             for (Case c : accountCases){ 
                if(c.AccountId == acct.id){
                    AccountCaseAge = c.Case_Age_Days__c;
                    CaseHoursCount = c.Total_Case_Minutes_Per_Month__c;
                    
                }
            }
            System.debug('Case Age'+AccountCaseAge);
             System.debug('Case Minutes:- '+CaseHoursCount);
                AvgAccCaseAge = AccountCaseAge / totalCases;
            System.debug('Case  avreageAge:-'+AvgAccCaseAge);
            
            if( AvgAccCaseAge <= 7 ){
                avgCaseAgeScore = 25;
            }
            else if( AvgAccCaseAge <= 14  ){
                avgCaseAgeScore = 20;
            }
            else if( AvgAccCaseAge <= 31  ){
                avgCaseAgeScore = 10;
            }
            else if( AvgAccCaseAge <= 45  ){
                avgCaseAgeScore = 5;
            }
            else if( AvgAccCaseAge > 45  ){
                avgCaseAgeScore = 0;
            }
            
             System.debug('Case  avreageAge Score :-'+avgCaseAgeScore);  
            
             if( CaseHoursCount == 0 ){
                caseHoursCountScore = 0;
            }
            else if( CaseHoursCount <= 60  ){
                caseHoursCountScore = 25;
            }
            else if( CaseHoursCount <= 300  ){
                caseHoursCountScore = 20;
            }
            else if( CaseHoursCount <= 900  ){
                caseHoursCountScore = 10;
            }
            else if( CaseHoursCount > 900  ){
                caseHoursCountScore = 5;
            }

             System.debug('Case  Hours Score :- '+caseHoursCountScore);  
          
            System.debug('service_Score after case review : '+service_Score);
            
            if( acct.Service_Score__c != null
               || acct.Service_Score__c != service_Score ){
                   
                   Decimal npsScoreContribution = 0;
                   
                   if(acct.NPS_Score__c != null){
                       npsScoreContribution = acct.NPS_Score__c * 1.5;
                   }
                   
                   Decimal CustomerEffortScore = 0;
                   if(acct.Customer_Effort_Score__c == 1){
                       CustomerEffortScore =  5;
                   }
                   else if(acct.Customer_Effort_Score__c == 2){
                       CustomerEffortScore = 4;
                   }
                   else if(acct.Customer_Effort_Score__c == 3){
                       CustomerEffortScore = 3;
                   }
                   else if(acct.Customer_Effort_Score__c == 4){
                       CustomerEffortScore = 2;
                   }
                   else if(acct.Customer_Effort_Score__c == 5){
                       CustomerEffortScore = 1;
                   } 
                   
                   System.debug('CustomerEffortScore after case review : '+CustomerEffortScore);
                   Decimal customerSatisfactionScore = 0;
                   if(acct.Customer_Satisfaction_Score__c != null){
                       customerSatisfactionScore = acct.Customer_Satisfaction_Score__c / 2.0;
                       System.debug('CustomerSatScore after case review : '+ customerSatisfactionScore);
                   }
                   acct.Service_Score__c = avgCaseAgeScore + caseHoursCountScore + caseRecordCountScore 
                                           + npsScoreContribution + customerSatisfactionScore + customerEffortScore;    
                   accsToUpdate.add(acct);
               }
             System.debug(' Service Score after   : '+ acct.Service_Score__c);
        }
        if( accsToUpdate.size() > 0 ){
            
            update accsToUpdate; 
        }
    }
    
    public void finish(Database.BatchableContext BC){
        if( !Test.isRunningTest() ){
            BatchOnAccountForMarketingActivityScore bch = new BatchOnAccountForMarketingActivityScore();
            Database.executeBatch( bch, 1 );    
        }
    }
}
hI all,
         I have a batch in which i am getting invalid query locator error for few records.
Can anyone help me with this error?
My batch is given below:-

public without sharing class BatchServiceScore implements Database.Batchable<sObject>,Database.Stateful{
    
    public static Date backDate = System.Today().addDays(-365); 
    public static void run( Set<Id> AccIds ) {
        List<Account> accountRecords =  [ SELECT Id, Service_Score__c,NPS_Score__c,Customer_Satisfaction_Score__c,
                                         Customer_Effort_Score__c,
                                         ( SELECT Id, Is_Negative_Case__c FROM Cases
                                          WHERE CreatedDate >=: System.today().addDays(-365)
                                         )
                                         FROM Account WHERE ID IN : AccIds
                                        ];
        executeHelper( accountRecords );                  
    }
    
    public Database.querylocator start(Database.BatchableContext BC){
        return Database.getQueryLocator([ SELECT Id, Service_Score__c,NPS_Score__c,Customer_Satisfaction_Score__c,
                                         Customer_Effort_Score__c,
                                         ( SELECT Id, Is_Negative_Case__c FROM Cases
                                          WHERE CreatedDate >=: System.today().addDays(-365)
                                         )
                                         FROM Account
                                        ]);
    }
    
    public void execute(Database.BatchableContext BC, List<Account> scope){
        
        executeHelper( scope );
    }
    
    public static void executeHelper( List<Account> scope ) {
        List<Account> accsToUpdate = new List<Account>();
         List<Case> casesToUpdate = new List<Case>();
        
        for( Account acct : scope ){
            Decimal totalNegativeCases = 0, totalPostiveCases = 0, service_Score = 0;
            //for( Case c : acct.Cases){
            casesToUpdate.addAll(acct.Cases);
            
            if (casesToUpdate != null) {  
                for (Case c : casesToUpdate){ 
                    if( c.Is_Negative_Case__c  ){
                        totalNegativeCases++;
                    }
                    else{
                        totalPostiveCases++;
                    }
                }
            }
            System.debug('Case Size: '+ acct.Cases.Size()+' '+acct.Cases);
            if( acct.Cases != null && acct.Cases.Size() > 0 ){
                Decimal totalCases = acct.Cases.Size();
                if( totalPostiveCases > 0 ) {
                    service_Score = (totalPostiveCases/totalCases)*75;
                }
                else if( totalNegativeCases > 0 ) {
                    service_Score = -(totalNegativeCases/totalCases)*75;
                }
            }
            System.debug('service_Score after case review : '+service_Score);
            if( acct.Service_Score__c != null
               || acct.Service_Score__c != service_Score ){
                   
                   Decimal npsScoreContribution = 0;
                   
                   if(acct.NPS_Score__c != null){
                       npsScoreContribution = acct.NPS_Score__c * 1.5;
                        System.debug('npsScoreContribution after case review : '+npsScoreContribution);
                   }
                
                   Decimal CustomerEffectScore = 0;
                   if(acct.Customer_Effort_Score__c == 1){
                       CustomerEffectScore =  5;
                   }else if(acct.Customer_Effort_Score__c == 2){
                       CustomerEffectScore = 4;
                   }else if(acct.Customer_Effort_Score__c == 3){
                       CustomerEffectScore = 3;
                   }else if(acct.Customer_Effort_Score__c == 4){
                       CustomerEffectScore = 2;
                   }else if(acct.Customer_Effort_Score__c == 5){
                       CustomerEffectScore = 1;
                   } 
                   System.debug('CustomerEffectScore after case review : '+CustomerEffectScore);
                   Decimal CustomerSatisfaction = 0;
                   if(acct.Customer_Satisfaction_Score__c != null){
                       CustomerSatisfaction = acct.Customer_Satisfaction_Score__c/2.0;
                       System.debug('CustomerSatScore after case review : '+CustomerSatisfaction);
                   }
              
                   acct.Service_Score__c = service_Score + npsScoreContribution + CustomerSatisfaction + CustomerEffectScore;    
                   accsToUpdate.add(acct);
                   
               }
            
        }
        if( accsToUpdate.size() > 0 ){
            
            update accsToUpdate; 
        }
        
    }
    
    public void finish(Database.BatchableContext BC){
        if( !Test.isRunningTest() ){
            BatchOnAccountForMarketingActivityScore bch = new BatchOnAccountForMarketingActivityScore();
            Database.executeBatch( bch, 1 );    
        }
        
    }
}
Can anyone help me out with this error?
Hi All,
       i have a trigger on Account which is giving me error:-Trigger_Account: execution of BeforeUpdate caused by: System.DmlException: Update failed. First exception on row 1 with id 0010o00002cFEGpAAO; first error: SELF_REFERENCE_FROM_TRIGGER, Object (id = 0010o00002cFEGp) is currently in trigger Trigger_Account, therefore it cannot recursively update itself: [] Class.AccountTriggerHelper.getCredebilityOfParentAcc: line 73, column 1 Trigger.Trigger_Account: line 24, column 1
       *******
       trigger Trigger_Account on Account (before insert, before update, 
                                    before delete, after insert, 
                                    after update, after delete) {
                                         
    AccountTriggerHelper.newAccount = trigger.new;
    AccountTriggerHelper.oldAccount = trigger.old;
    AccountTriggerHelper.newMapAccount = trigger.newMap;
    AccountTriggerHelper.oldMapAccount = trigger.oldMap;         
                                        
                                        if(!AccountTriggerHelper.runTrigger) {
                                            return;
                                        }

                                        if(Trigger.IsBefore){
                                            if(Trigger.IsInsert){
                                                AccountTriggerHelper.updateOppAmountOnAccount();
                                                AccountTriggerHelper.getCredebilityOfParentAcc();
                                            }
                                        } 
                                        
                                        if(Trigger.IsBefore){
                                            if(Trigger.IsUpdate){
                                                AccountTriggerHelper.updateOppAmountOnAccount();
                                                AccountTriggerHelper.getCredebilityOfParentAcc();
                                            }
                                        } 
        
}
Account trigger helper:-
public class AccountTriggerHelper {
    
    public static List<Account> newAccount = new List<Account>();
    public static List<Account> oldAccount = new List<Account>();
    public static Map<Id, Account> newMapAccount = new Map<Id, Account>();
    public static Map<Id, Account> oldMapAccount = new Map<Id, Account>();
    
    public static boolean runTrigger = True;
    
    public static Map<ID,List<Opportunity>> MapAccIdToOpp = New Map<ID,List<Opportunity>>();
    
    public static void  updateOppAmountOnAccount(){
        
        Set<id> accids = new Set<id>();
        for(Account acc : newAccount){
            accids.add(acc.id);
        }
        
        for(Id accid : accids){
            List<Opportunity> Listopp = MapAccIdToOpp.get(accid);
            System.debug('List'+ MapAccIdToOpp.get(accid));
            MapAccIdToOpp.put(accid, Listopp);
            System.debug('MapAccidtoOpp'+MapAccIdToOpp);
        }
        
        List<Account> AccountListToUpdate = new List<Account>();
        
        for(Account acc : newAccount){
            Decimal Amount = 0;
            
            for(Opportunity opp :  [SELECT id ,Name,StageName,Amount FROM Opportunity WHERE AccountId =: acc.id] ){
                if(opp.StageName == 'Closed Won' || opp.StageName == 'Closed Lost'){
                    Amount = Amount + opp.Amount;
                    System.debug('AmountIfupdate'+Amount);
                }
                
                if(opp.StageName != 'Closed Won' && opp.StageName != 'Closed Lost'){
                    Amount  = Amount + (opp.Amount)*0.25;
                     System.debug('Amountelseupdate'+Amount);
                }
                
                acc.Opportunity_Amount__c = Amount;
                System.debug('Amountupdate'+acc.Opportunity_Amount__c);
                AccountListToUpdate.add(acc);
            }
            
            System.debug('acctoupdate'+AccountListToUpdate);
        }        
        
    }
    public static void getCredebilityOfParentAcc(){
        List<Account> accListToUpdate = new List<Account>();
        Integer Point = 0;
        Map<Account,Decimal> MapAccToAmount = new Map<Account,Decimal>();
        for(Account acc : [SELECT id ,Name,Opportunity_Amount__c  
                          FROM Account 
                          WHERE Parentid = null 
                          AND Opportunity_Amount__c <> null 
                          ORDER BY Opportunity_Amount__c desc]){
            MapAccToAmount.put(acc,acc.Opportunity_Amount__c);
            system.debug('mapAmount'+MapAccToAmount);
                              
        }
        for(Account acc : MapAccToAmount.keyset()){
            Point = Point+1;
             System.debug('point'+Point);
            acc.RankOfAccount__c = Point;
            accListToUpdate.add(acc);
        }
        System.debug('point'+  accListToUpdate);
        
            runTrigger = false;
            Update accListToUpdate;
            runTrigger = true;
         
         
    }
    
}
How to solve this issue? Any suggestions?
Hi All,
I am creating a batch for the requirement in which if lead has duplicates based on name than a checkbox field named ToBeDeleted__c should set to true on the duplicate of a lead records.
Can anyone guide me with this requirement?
Thanks in advance
Hi All,
         i have a requirement in which i have a field on lead object called ToBeDeleted__c, which should be true when one of the following condition is true :-
1.lead name contains 'test'   
2.The owner of the lead is inactive.
3.lead has duplicate records than last created record need to be checked.
4.lead is created 1 year or more than one year ago.
I want to create a batch which set the checkbox field true when above condition met.
How to do it ?Can someone guide me with it?
Thanks
Hi All,
         i am creating a batch to get all the ticket audits fields in task fields. i have created a batch below:-

global class BatchZendeskActivityToTask implements Database.Batchable<sObject>, Database.AllowsCallouts, Database.Stateful {

    global Database.QueryLocator start(Database.BatchableContext BC) {
        String query = ' SELECT Id, Zd_Zendesk_Id__c, Status ' +
                       ' FROM Case ' +
                       ' WHERE Zd_Zendesk_Id__c != Null '+
                       ' AND Id = \'500S000000AEXIEIA5\'';
        return Database.getQueryLocator(query);
    }

    global void execute( Database.BatchableContext BC, List<Case> caseRecords ){         
        
        for ( Case caseObj : caseRecords ){
            try {                  
                HttpRequest req = new HttpRequest();
                HttpResponse res = new HttpResponse();
                Http http = new Http();
                
                // Set values to Params
                String username = Label.Zendesk_UserName;
                String password = Label.Zendesk_Password;
                Blob headerValue = Blob.valueOf( username + ':' + password );
                String authorizationHeader = 'BASIC ' + EncodingUtil.base64Encode( headerValue );
                
                req.setHeader( 'Authorization', authorizationHeader );
                req.setHeader('Content-Type', 'application/json');
                req.setEndpoint( 'https://timerack.zendesk.com/api/v2/tickets/'+caseObj.Zd_Zendesk_Id__c+'/audits.json' );
                req.setMethod('GET');
                
        
                if( !Test.isRunningTest() ) {      
                    res = http.send( req );
                    String sJson = res.getBody();
                     TaskJSON2Apex obj = parseTaskData( sJson );
                    System.assert( false, obj );
                }             
                               
            }
            catch (Exception e) {         
                System.debug( 'Error:' + e.getMessage() + 'LN:' + e.getLineNumber() );           
            }
        }
    }   

    global void finish( Database.BatchableContext BC ){    
    
    }
    
    //method to return Activity in Task. 
    public static TaskJSON2Apex parseTaskData( String json ){
        System.assert( false, ( TaskJSON2Apex ) System.JSON.deserialize( json, TaskJSON2Apex.class ) );
        return ( TaskJSON2Apex ) System.JSON.deserialize( json, TaskJSON2Apex.class );
    }
    
    //Wrapper Class
    //wrapper class to fetch users data in salesforce contact
    public class TaskJSON2Apex {
        public List<Audits> audits {get;set;} 
        public Object next_page {get;set;} 
        public Object previous_page {get;set;} 
        public Integer count {get;set;} 
        
        TaskJSON2Apex(){
            System.assert( false, count );
        }
    }
    
    public class Audits {
        public Integer id {get;set;} 
        public Integer ticket_id {get;set;} 
        public String created_at {get;set;} 
        public Integer author_id {get;set;} 
        public List<Events> events {get;set;} 
    }
    
    public class Events {
        public Integer id {get;set;} 
        public String type {get;set;} // in json: type
        public Integer author_id {get;set;} 
        public String body {get;set;} 
        public String html_body {get;set;} 
        public String plain_body {get;set;} 
        public Integer audit_id {get;set;} 
        public Object value {get;set;} 
        public String field_name {get;set;} 
        public String subject {get;set;} 
        public List<Integer> recipients {get;set;} 
    }
 }
Can anyone guide me how to move ahead and get the ticket audits fields in salesforce task fields?let me know if i am missing something?
HI All,
      i have installed (Mass Edit + Mass Update + Mass Delete) app from app exchange.its working on Account,Contact and leads.
but its not working on case.
how can i make it to work on case?
or how can i mass update and edit on case?
Any suggestions?
Hi All,
i am trying to automate a lightning component . i write a script for it .
but i have a lookup field on it i dont know how to test it?
my script is given below:-
package myPackage;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

public class FamilyRecords {
    public static void main(String[] args) {
         // declaration and instantiation of objects/variables
        System.setProperty("webdriver.chrome.driver","C:\\Users\\user\\Downloads\\Chromedriver_win32\\chromedriver.exe");
        WebDriver driver = new ChromeDriver();
        String baseUrl = "https://login.salesforce.com";
        driver.get(baseUrl);
        driver.findElement(By.id("username")).sendKeys("kmalek@fbgholdings.com.sfdcadmin");                        
        driver.findElement(By.id("password")).sendKeys("2&*ZMRrGFSx&");                        
        WebElement login = driver.findElement(By.id("Login"));
        login.submit();
        driver.navigate().to("https://fbg--sfdcadmin.lightning.force.com/lightning/r/Account/001S000000zb9KyIAI/view?0.source=alohaHeader");
        WebElement newpage = driver.findElement(By.cssSelector(".slds-button, .slds-button_neutral, .buttonStyle"));
        newpage.click(); 
        //driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);
        driver.navigate().to("https://fbg--sfdcadmin.lightning.force.com/lightning/o/FBG_Family__c/new?nooverride=1&backgroundContext=%2Flightning%2Fr%2FAccount%2F001S000000zb9KyIAI%2Fview%3F0.source%3DalohaHeader&0.source=alohaHeader");
        System.out.println("click submit");
        WebDriverWait wait=new WebDriverWait(driver, 20);
        WebElement namefield = wait.until(
                ExpectedConditions.visibilityOfElementLocated(By.id("5998:0")));
        namefield.sendKeys("June12");
        WebElement namefield2 = wait.until(
                ExpectedConditions.visibilityOfElementLocated(By.id("6103:0")));
        namefield2.sendKeys("June12");
        WebElement Accsubmit = driver.findElement(By.cssSelector(".slds-button, .slds-button--neutral, .uiButton--brand, .uiButton, .forceActionButton"));

        Accsubmit.click();
        System.out.println("record submit");
        WebElement option1 =  driver.findElement(By.cssSelector(".slds-checkbox_faux"));                            
        //This will Toggle the Check box         
        option1.click();    
        driver.close();
        
    }
}User-added image
 
Hi All,
i am trying to create test class for following batch:-
public without sharing class BatchDeleteAndMergeDuplicateCases implements Database.Batchable<sObject> {
    
    public string subjectToFind ;
    public Set<Id> duplicateCaseIds;
    public Case parentCase;
 
    public BatchDeleteAndMergeDuplicateCases(Set<Id> duplicateCaseIds, Case parentCase){
        this.duplicateCaseIds = duplicateCaseIds;
        this.parentCase = parentCase;
    }
     public BatchDeleteAndMergeDuplicateCases(String subjectToFind, Set<Id> duplicateCaseIds, Case parentCase){
        this.subjectToFind = subjectToFind;
        this.duplicateCaseIds = duplicateCaseIds;
        this.parentCase = parentCase;
    }
     public static void run( Set<Id> CaseIds ) {
        Set<String> duplicateSubjectMetaData = new Set<String>();
        Set<String> duplicateEmailMetaData = new Set<String>();
        for(Duplicate_Merge_Rule_Exception__mdt duplicateMetaData : [SELECT Active__c, Subject__c 
                                                                     FROM Duplicate_Merge_Rule_Exception__mdt
                                                                     where Active__c =: True]){
            if(duplicateMetaData.Type__c == 'Email'){
               duplicateEmailMetaData.add(duplicateMetaData.Email__c);
            }else if(duplicateMetaData.Type__c == 'Subject'){                                                        
               duplicateSubjectMetaData.add(duplicateMetaData.Subject__c);
            }                                                                
        }
        List<Case> CaseRecords =  [Select id, Subject, 
                                   Origin, DuplicateOf__c,
                                   SuppliedEmail, Status,
                                   Duplicate_Count__c, CaseNumber,
                                   Description
                                   from case 
                                   where Id IN: CaseIds 
                                   AND origin != Null AND 
                                   origin =: 'Email' AND
                                   SuppliedEmail != Null AND 
                                   Subject != Null
                                   AND SuppliedEmail NOT IN: duplicateEmailMetaData 
                                   AND DuplicateOf__c =: Null
                                   ORDER By LastModifiedDate DESC];
        //executeHelper( CaseRecords , parentCase);                  
    }
     public Database.QueryLocator start(Database.BatchableContext BC){
        Set<String> duplicateSubjectMetaData = new Set<String>();
        Set<String> duplicateEmailMetaData = new Set<String>();
        for(Duplicate_Merge_Rule_Exception__mdt duplicateMetaData : [SELECT Active__c, Subject__c, Type__c, Email__c 
                                                                     FROM Duplicate_Merge_Rule_Exception__mdt
                                                                     where Active__c =: True]){
        
        
            if(duplicateMetaData.Type__c == 'Email'){
               duplicateEmailMetaData.add(duplicateMetaData.Email__c);
            }else if(duplicateMetaData.Type__c == 'Subject'){                                                        
                duplicateSubjectMetaData.add(duplicateMetaData.Subject__c);
            }                                                                
        }
         if(subjectToFind != Null && subjectToFind != ''){
            return Database.getQueryLocator([SELECT id, Subject, Origin,SuppliedEmail,
                                             Status, DuplicateOf__c, Description,
                                             Duplicate_Count__c, CaseNumber
                                             FROM Case
                                             WHERE Subject != null
                                             AND Subject LIKE: '%'+ subjectToFind + '%'
                                             AND Origin != Null
                                             And Origin = 'Email'
                                             AND SuppliedEmail != Null
                                             AND Subject NOT IN: duplicateSubjectMetaData
                                             AND SuppliedEmail NOT IN: duplicateEmailMetaData 
                                             AND DuplicateOf__c =: Null
                                             ORDER By CreatedDate DESC 
                                            ]);
            
            
        }
        else if(duplicateCaseIds != null && parentCase.Id != null ) {
            return Database.getQueryLocator([SELECT id, Subject, Origin,SuppliedEmail,
                                             Status, DuplicateOf__c, Description,
                                             Duplicate_Count__c, CaseNumber
                                             FROM Case
                                             WHERE Subject != null
                                             AND Origin != Null
                                             And Origin = 'Email'
                                             AND SuppliedEmail != Null
                                             AND Subject NOT IN: duplicateSubjectMetaData
                                             AND SuppliedEmail NOT IN: duplicateEmailMetaData 
                                             AND DuplicateOf__c =: Null
                                             AND Id in :duplicateCaseIds 
                                             ORDER By CreatedDate DESC 
                                            ]);
        }
        else {
             return Database.getQueryLocator([SELECT id, Subject, Origin,SuppliedEmail,
                                             Status, DuplicateOf__c, Description,
                                             Duplicate_Count__c, CaseNumber
                                             FROM Case
                                             WHERE Subject != null
                                             AND Origin != Null
                                             And Origin = 'Email'
                                             AND SuppliedEmail != Null
                                             AND Subject NOT IN: duplicateSubjectMetaData
                                             AND SuppliedEmail NOT IN: duplicateEmailMetaData 
                                             AND DuplicateOf__c =: Null
                                             ORDER By CreatedDate DESC 
                                            ]);
        } 
    }
     public void execute(Database.BatchableContext BC, List<Case> cases){
        executeHelper(cases, parentCase);
    }
    
    public void finish(Database.BatchableContext BC){
        
    }
     public static void executeHelper(List<Case> caseRecords, Case parentCase){
        
        EmailMessageTriggerHelper.runTrigger = False;
        CaseTriggerHelper.runTrigger = False;
        
        List<EmailMessage> emList = new List<EmailMessage>();
        
        String objectName = 'EmailMessage';  // modify as needed
        String soql = getCreatableFieldsSOQL('EmailMessage', 'ParentId IN :caseRecords');
        emList = database.query(soql);
        
        List<EmailMessage> emListToInsert = new List<EmailMessage>();
        if(emList.size() > 0){
           for(EmailMessage em : emList){
              EmailMessage emToInsert = em.clone(False); 
              emToInsert.ParentId = parentCase.Id; 
               emToInsert.CreatedDate = em.CreatedDate;
               emToInsert.LastModifiedDate = em.LastModifiedDate;
               emToInsert.CreatedById = em.CreatedById;
               emToInsert.LastModifiedById = em.LastModifiedById;
               emListToInsert.add(emToInsert);
           } 
        }
         if(emListToInsert.size() > 0){
            insert emListToInsert;
            
            // merge log
            List<Merge_Log__c> mlList = new List<Merge_Log__c>();
            Set<Id> deleteCaseIds = new Set<Id>();
            for(Case caseObj : caseRecords){
                Merge_Log__c ml = new Merge_Log__c();
                ml.Case__c = caseObj.Id;
                ml.MergedWith__c = caseObj.DuplicateOf__c;
                ml.Case_Details__c = JSON.serializePretty(caseObj);
                ml.Merge_Details__c = '';
                mlList.add(ml);
            }
            if(mlList.size() > 0){
                insert mlList;
            }
             //delete duplicate cases
            delete caseRecords; 
        }
     }
    
    // Returns a dynamic SOQL statement for the whole object, includes only creatable fields since we will be inserting a cloned result of this query
    public static string getCreatableFieldsSOQL(String objectName, String whereClause){
         
        String selects = '';
         
        if (whereClause == null || whereClause == ''){ return null; }
         
        // Get a map of field name and field token
        Map<String, Schema.SObjectField> fMap = Schema.getGlobalDescribe().get(objectName.toLowerCase()).getDescribe().Fields.getMap();
        list<string> selectFields = new list<string>();
         
        if (fMap != null){
            for (Schema.SObjectField ft : fMap.values()){ // loop through all field tokens (ft)
                Schema.DescribeFieldResult fd = ft.getDescribe(); // describe each field (fd)
                if (fd.isCreateable() && fd.getName() != 'ValidatedFromAddress'){ // field is creatable
                    selectFields.add(fd.getName());
                }
            }
        }
         
        if (!selectFields.isEmpty()){
            for (string s:selectFields){
                selects += s + ',';
            }
            if (selects.endsWith(',')){selects = selects.substring(0,selects.lastIndexOf(','));}
             
        }
         
        return 'SELECT ' + selects + ' FROM ' + objectName + ' WHERE ' + whereClause;
         
    }
     
}
how to create the test class for it?
Any suggestions?
Hi All,
i have a lightning component in which i am taking records of a custom object .here when i click on checkbox the record is removed.
but after reloading the page its coming again in data table i want that in this records  i have a Checkbox field (False_Positive__c). this field become true for the record. so that the record does not show again on data table.
how to do it?
Any suggestions?
my component and controller is given below:-
<aura:component controller="FBGFamilyController"
                implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" 
                access="global" >
    
    <!--aura:attribute name="PageHeading" type="String" default="Remove  False positive On Click Of Check Box" /-->
    <aura:attribute name="mydata" type="Object"/>
    <aura:attribute name="mycolumns" type="List"/>
    <aura:handler name="init" value="{!this}" action="{!c.doinit}" />
    
    
    <div class="slds-section slds-is-open">
        <h3 class="slds-section__title slds-theme_shade">
            <span class="slds-truncate slds-p-horizontal_small" title="Section Title">Family Records</span>
            <lightning:layoutItem class="right-align">
                <lightning:button label="New" onclick="{!c.createRecord}" class="buttonStyle"/>
            </lightning:layoutItem> 
        </h3>
        <lightning:datatable data="{! v.mydata }" 
                             columns="{! v.mycolumns }" 
                             keyField="Id" 
                             onrowselection="{! c.removeRow }"
                             hideCheckboxColumn="false"
                             />
        
    </div>
</aura:component>
Controller is given below:-
({
    doinit : function(component, event, helper) {
        component.set('v.mycolumns', [
            
            {label: 'Name', fieldName: 'linkName', type: 'url', 
             typeAttributes: {label: { fieldName: 'Name' }, target: '_blank'}},
            /*{label: 'Sister Account ', fieldName: 's1', type: 'url', 
             typeAttributes: {label: { fieldName: 'Sister_Company__r.Name' }, target: '_blank'}},
            {label: 'Sister Account ', fieldName: 's2', type: 'url', 
             typeAttributes: {label: { fieldName: ' Sister_Company2__r.Name' }, target: '_blank'}}*/
            {label: 'Division', fieldName: 'd1', type: 'text'},
            {label: 'Sister Account', fieldName: 's1', type: 'text'},
            {label: 'Sister Account', fieldName: 's2', type: 'text'},
            {label: 'State', fieldName: 'State__c', type: 'text'},
            {label: 'Type', fieldName: 'Type__c', type: 'text'},
            {label: 'Owner', fieldName: 'Oid', type: 'text'}
        ]);
        
        var action = component.get('c.fetchRecords');
        var recordId =  component.get("v.recordId");
        action.setParams({rid : recordId});
        action.setCallback(this, function(response){
            var state = response.getState();
            if(state === "SUCCESS"){
                var allValues = response.getReturnValue();
                
                for (var i = 0; i < allValues.length; i++) {
                    var row = allValues[i];
                    row.s1 = row.Sister_Company__r.Name;
                }
                for (var i = 0; i < allValues.length; i++) {
                    var row = allValues[i];
                    row.s2 = row.Sister_Company2__r.Name;
                }
                 for (var i = 0; i < allValues.length; i++) {
                    var row = allValues[i];
                    row.d1 = row.Sister_Company__r.RecordType.Name;
                }
                for (var i = 0; i < allValues.length; i++) {
                    var row = allValues[i];
                    row.Oid = row.Owner.Name;
                }
                 
                allValues.forEach(function(record){
                    record.linkName = '/'+record.Id;
                });
                /* allValues.forEach(function(record){
                     record.s1 = '/'+record.Sister_Company__r.Id;
                }); 
                 allValues.forEach(function(record){
                    record.s2 = '/'+record.Sister_Company2__r.Id;
                }); */
                console.log("allValues--->>> " + allValues);
                component.set('v.mydata', allValues);
            }
            else if(state === "ERROR") {
                var errors = response.getError();
                if(errors){
                    if(errors[0] && errors[0].message){
                        console.log("Error Message: " + errors[0].message);
                    }
                }
                else{
                    console.log("Unknown Error");
                }
            }
        });
        $A.enqueueAction(action);
    },
    
    removeRow : function(component, event, helper){
        var selRows = event.getParam('selectedRows');
        
        // Remove the record from the table
        var rows = component.get('v.mydata');
        for (var i = 0; i<selRows.length; i++){    
            var rowIndex = rows.indexOf(selRows[i]);
            console.log('rowIndex---->>> ' + rowIndex);
            var r=rows.splice(rowIndex, 1);   
            
            console.log('rrr---->>> ' + JSON.stringify(r));
            component.set('v.mydata', rows);
        }
    },
    
     createRecord : function (component, event, helper) {
        var createRecordEvent = $A.get("e.force:createRecord");
        createRecordEvent.setParams({
            "entityApiName": "FBG_Family__c"
        });
        createRecordEvent.fire();
    }
    
})
my Apex class is given below:-
public class FBGFamilyController {
        @AuraEnabled
    public static List<FBG_Family__c> fetchRecords(String rid) {
        return [SELECT Id, Name, Owner.Name,Type__c, Sister_Company__r.RecordType.Name, False_Positive__c,
                State__c, Division1__c, Sister_Company__r.Name, Sister_Company2__r.Name 
                FROM FBG_Family__c
                WHERE Sister_Company__c =: rid 
                AND False_Positive__c = FALSE
                ORDER BY Name  ASC ];
    }
}
i want when i click on Checkbox on data table a CheckBox field become False_Positive__c become true for that record.
how to do it?
Any suggestions?
Hi All,
i have a lightning component in which i am taking records of a custom object .here when i click on checkbox the record is removed.
but after reloading the page its coming again in data table i want that this records does not show again in data table.i dont want to delete the record.
how to do it?
Any suggestions?
my component and controller is given below:-
<aura:component controller="FBGFamilyController"
                implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" 
                access="global" >
    
    <!--aura:attribute name="PageHeading" type="String" default="Remove  False positive On Click Of Check Box" /-->
    <aura:attribute name="mydata" type="Object"/>
    <aura:attribute name="mycolumns" type="List"/>
    <aura:handler name="init" value="{!this}" action="{!c.doinit}" />
    
    
    <div class="slds-section slds-is-open">
        <h3 class="slds-section__title slds-theme_shade">
            <span class="slds-truncate slds-p-horizontal_small" title="Section Title">Family Records</span>
            <lightning:layoutItem class="right-align">
                <lightning:button label="New" onclick="{!c.createRecord}" class="buttonStyle"/>
            </lightning:layoutItem> 
        </h3>
        <lightning:datatable data="{! v.mydata }" 
                             columns="{! v.mycolumns }" 
                             keyField="Id" 
                             onrowselection="{! c.removeRow }"
                             hideCheckboxColumn="false"
                             />
        
    </div>
</aura:component>
Controller is given below:-
({
    doinit : function(component, event, helper) {
        component.set('v.mycolumns', [
            
            {label: 'Name', fieldName: 'linkName', type: 'url', 
             typeAttributes: {label: { fieldName: 'Name' }, target: '_blank'}},
            /*{label: 'Sister Account ', fieldName: 's1', type: 'url', 
             typeAttributes: {label: { fieldName: 'Sister_Company__r.Name' }, target: '_blank'}},
            {label: 'Sister Account ', fieldName: 's2', type: 'url', 
             typeAttributes: {label: { fieldName: ' Sister_Company2__r.Name' }, target: '_blank'}}*/
            {label: 'Division', fieldName: 'd1', type: 'text'},
            {label: 'Sister Account', fieldName: 's1', type: 'text'},
            {label: 'Sister Account', fieldName: 's2', type: 'text'},
            {label: 'State', fieldName: 'State__c', type: 'text'},
            {label: 'Type', fieldName: 'Type__c', type: 'text'},
            {label: 'Owner', fieldName: 'Oid', type: 'text'}
        ]);
        
        var action = component.get('c.fetchRecords');
        var recordId =  component.get("v.recordId");
        action.setParams({rid : recordId});
        action.setCallback(this, function(response){
            var state = response.getState();
            if(state === "SUCCESS"){
                var allValues = response.getReturnValue();
                
                for (var i = 0; i < allValues.length; i++) {
                    var row = allValues[i];
                    row.s1 = row.Sister_Company__r.Name;
                }
                for (var i = 0; i < allValues.length; i++) {
                    var row = allValues[i];
                    row.s2 = row.Sister_Company2__r.Name;
                }
                 for (var i = 0; i < allValues.length; i++) {
                    var row = allValues[i];
                    row.d1 = row.Sister_Company__r.RecordType.Name;
                }
                for (var i = 0; i < allValues.length; i++) {
                    var row = allValues[i];
                    row.Oid = row.Owner.Name;
                }
                 
                allValues.forEach(function(record){
                    record.linkName = '/'+record.Id;
                });
                /* allValues.forEach(function(record){
                     record.s1 = '/'+record.Sister_Company__r.Id;
                }); 
                 allValues.forEach(function(record){
                    record.s2 = '/'+record.Sister_Company2__r.Id;
                }); */
                console.log("allValues--->>> " + allValues);
                component.set('v.mydata', allValues);
            }
            else if(state === "ERROR") {
                var errors = response.getError();
                if(errors){
                    if(errors[0] && errors[0].message){
                        console.log("Error Message: " + errors[0].message);
                    }
                }
                else{
                    console.log("Unknown Error");
                }
            }
        });
        $A.enqueueAction(action);
    },
    
    removeRow : function(component, event, helper){
        var selRows = event.getParam('selectedRows');
        
        // Remove the record from the table
        var rows = component.get('v.mydata');
        for (var i = 0; i<selRows.length; i++){    
            var rowIndex = rows.indexOf(selRows[i]);
            console.log('rowIndex---->>> ' + rowIndex);
            var r=rows.splice(rowIndex, 1);   
            
            console.log('rrr---->>> ' + JSON.stringify(r));
            component.set('v.mydata', rows);
        }
    },
    
     createRecord : function (component, event, helper) {
        var createRecordEvent = $A.get("e.force:createRecord");
        createRecordEvent.setParams({
            "entityApiName": "FBG_Family__c"
        });
        createRecordEvent.fire();
    }
    
})
Hi All,
i have created a lightning component having lightning data table in which i am showing fields of custom object.
I have a formula field called Division having image, i want to show this in data table but its giving me only image source.like this:-<img src="/servlet/servlet.FileDownload?file=01541000001xSd8" alt=" " border="0"/>
i want to show image on it.
here is my component showing fields of custom objectUser-added imagei want to show image on it.
my controller is given below:-
({
    doinit : function(component, event, helper) {
        component.set('v.mycolumns', [
            {label: 'Name', fieldName: 'linkName', type: 'url', 
             typeAttributes: {label: { fieldName: 'Name' }, target: '_blank'}},
             {label: 'Division', fieldName: 'Division1__c', type: 'image'}, //here its showing only source
            {label: 'Sister Account', fieldName: 's1', type: 'text'},
            {label: 'Sister Account', fieldName: 's2', type: 'text'},
            {label: 'State', fieldName: 'State__c', type: 'text'},
            {label: 'Type', fieldName: 'Type__c', type: 'text'},
            {label: 'Owner', fieldName: 'Oid', type: 'text'}
        ]);
        
        var action = component.get('c.fetchRecords');
        var recordId =  component.get("v.recordId");
        action.setParams({rid : recordId});
        action.setCallback(this, function(response){
            var state = response.getState();
            if(state === "SUCCESS"){
                var allValues = response.getReturnValue();
                
                for (var i = 0; i < allValues.length; i++) {
                    var row = allValues[i];
                    row.s1 = row.Sister_Company__r.Name;
                }
                for (var i = 0; i < allValues.length; i++) {
                    var row = allValues[i];
                    row.s2 = row.Sister_Company2__r.Name;
                }
                for (var i = 0; i < allValues.length; i++) {
                    var row = allValues[i];
                    row.Oid = row.Owner.Name;
                }
                 
                allValues.forEach(function(record){
                    record.linkName = '/'+record.Id;
                });
                 console.log("allValues--->>> " + allValues);
                component.set('v.mydata', allValues);
            }
            else if(state === "ERROR") {
                var errors = response.getError();
                if(errors){
                    if(errors[0] && errors[0].message){
                        console.log("Error Message: " + errors[0].message);
                    }
                }
                else{
                    console.log("Unknown Error");
                }
            }
        });
        $A.enqueueAction(action);
    },
    
    removeRow : function(component, event, helper){
        var selRows = event.getParam('selectedRows');
        
        // Remove the record from the table
        var rows = component.get('v.mydata');
        for (var i = 0; i<selRows.length; i++){    
            var rowIndex = rows.indexOf(selRows[i]);
            console.log('rowIndex---->>> ' + rowIndex);
            var r=rows.splice(rowIndex, 1);   
            
            console.log('rrr---->>> ' + JSON.stringify(r));
            component.set('v.mydata', rows);
        }
    },
 
})
how to get image in the field?
what am i missing?
Anu suggestions?
Hi All,
         i am trying to make the lookup field a hyper link which show the Account clicking on it.
my controller  is given below:-
 ({

    doinit : function(component, event, helper) {
        component.set('v.mycolumns', [
            {label: 'Record Number ', fieldName: 'linkName', type: 'url', 
             typeAttributes: {label: { fieldName: 'Name' }, target: '_blank'}},
            {label: 'Sister Account ', fieldName: 's1', type: 'url', 
             typeAttributes: {label: { fieldName: 'Sister_Company__c' },value:{fieldName: 'Sister_Company__c.Id'}, target: '_blank'}},
            {label: 'Sister Account ', fieldName: 's2', type: 'url', 
             typeAttributes: {label: { fieldName: ' Sister_Company2__c' },value:{fieldName: 's2'}, target: '_blank'}}

          
        ]);
        
        var action = component.get('c.fetchRecords');
        var recordId =  component.get("v.recordId");
        action.setParams({rid : recordId});
        action.setCallback(this, function(response){
            var state = response.getState();
            if(state === "SUCCESS"){
                var allValues = response.getReturnValue();
            
                  allValues.forEach(function(record){
                    record.linkName = '/'+record.Id;
                });
               allValues.forEach(function(record){
                    record.s1 = '/'+record.Sister_Company__r.Name;
                }); 
                 allValues.forEach(function(record){
                    record.s2 = '/'+record.Sister_Company2__r.Id;

                }); 
                console.log("allValues--->>> " + allValues);
                component.set('v.mydata', allValues);
            }
            else if(state === "ERROR") {
                var errors = response.getError();
                if(errors){
                    if(errors[0] && errors[0].message){
                        console.log("Error Message: " + errors[0].message);
                    }
                }
                else{
                    console.log("Unknown Error");
                }
            }
        });
        $A.enqueueAction(action);
    },
    
    removeRow : function(component, event, helper){
        var selRows = event.getParam('selectedRows');
        
        // Remove the record from the table
        var rows = component.get('v.mydata');
        for (var i = 0; i<selRows.length; i++){    
            var rowIndex = rows.indexOf(selRows[i]);
            console.log('rowIndex---->>> ' + rowIndex);
            var r=rows.splice(rowIndex, 1);   
            
            console.log('rrr---->>> ' + JSON.stringify(r));
            component.set('v.mydata', rows);
         }
    }
 })     
                here the name is working as hyper link but on lookup i am getting ids as hyperlink not their name.
                i want lookup field (Sister_Company__c's name as hyper link.
                how to do it?
                Any suggestions?
Hi All,
 i created a ligtning component in which i am showing records of custom object having lookup of account.
i want that it should show only those custom object records which are related to that particular account in which related list  i am using it.
how to do it?
Any suggestions?
My component and controller is given below:-
<aura:component controller="FBGFamilyController"
                implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" 
                access="global" >
    
    <aura:attribute name="PageHeading" type="String" default="Remove  False positive On Click Of Check Box" />
    <aura:attribute name="mydata" type="Object"/>
    <aura:attribute name="mycolumns" type="List"/>

    
    <aura:handler name="init" value="{!this}" action="{!c.doinit}" />
    
    <div class="slds-m-top--xx-large">
        <div class="slds-page-header">
            <div class="slds-align--absolute-center">
                <div class="slds-text-heading--large">       
                    {!v.PageHeading}
                </div>
            </div>
        </div>
    </div>
    
 

    
    <div class="slds-section slds-is-open">
        <h3 class="slds-section__title slds-theme_shade">
              <span class="slds-truncate slds-p-horizontal_small" title="Section Title">Family Records</span>
          </h3>
        

        <lightning:datatable data="{! v.mydata }" 
                             columns="{! v.mycolumns }" 
                             keyField="Id" 
                             onrowselection="{! c.removeRow }"
                           />
    </div>
</aura:component>
**********************************
controller is given below:-
({
    doinit : function(component, event, helper) {
        component.set('v.mycolumns', [
           
            {label: 'Record Number', fieldName: 'Name', type: 'integer'},
            
            {label: 'Sister Account', fieldName: 's1', type: 'text'},
            {label: 'Sister Account', fieldName: 's2', type: 'text'}

        ]);
        
        var action = component.get('c.fetchRecords');
        action.setCallback(this, function(response){
            var state = response.getState();
            if(state === "SUCCESS"){
                var allValues = response.getReturnValue();
                 for (var i = 0; i < allValues.length; i++) {
                    var row = allValues[i];
                    row.s1 = row.Sister_Company__r.Name;
                }
                 for (var i = 0; i < allValues.length; i++) {
                    var row = allValues[i];
                    row.s2 = row.Sister_Company2__r.Name;
                }
                console.log("allValues--->>> " + allValues);
                component.set('v.mydata', allValues);
            }
            else if(state === "ERROR") {
                var errors = response.getError();
                if(errors){
                    if(errors[0] && errors[0].message){
                        console.log("Error Message: " + errors[0].message);
                    }
                }
                else{
                    console.log("Unknown Error");
                }
            }
        });
        $A.enqueueAction(action);
    },
    
    removeRow : function(component, event, helper){
        var selRows = event.getParam('selectedRows');
        
        // Remove the record from the table
        var rows = component.get('v.mydata');
        for (var i = 0; i<selRows.length; i++){    
            var rowIndex = rows.indexOf(selRows[i]);
            console.log('rowIndex---->>> ' + rowIndex);
            var r=rows.splice(rowIndex, 1);   
            console.log('rrr---->>> ' + JSON.stringify(r));
            component.set('v.mydata', rows);
        }
    }
})
******************************************************
public class FBGFamilyController {
        @AuraEnabled
    public static List<FBG_Family__c> fetchRecords() {
        return [SELECT Id, Name, Sister_Company__r.Name, Sister_Company2__r.Name FROM FBG_Family__c];
    }
}
 HI All,
 i created a lightning component in which i am using lightning data table and showing records of custom object.
 my component and controller is given below:-
 <aura:component controller="FBGFamilyController"
                implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" 
                access="global" >
    
    <aura:attribute name="PageHeading" type="String" default="Remove  False positive On Click Of Check Box" />
    <aura:attribute name="mydata" type="Object"/>
    <aura:attribute name="mycolumns" type="List"/>

    
    <aura:handler name="init" value="{!this}" action="{!c.doinit}" />
    
    <div class="slds-m-top--xx-large">
        <div class="slds-page-header">
            <div class="slds-align--absolute-center">
                <div class="slds-text-heading--large">       
                    {!v.PageHeading}
                </div>
            </div>
        </div>
    </div>
    
 

    
    <div class="slds-section slds-is-open">
        <h3 class="slds-section__title slds-theme_shade">
              <span class="slds-truncate slds-p-horizontal_small" title="Section Title">Family Records</span>
          </h3>
        

        <lightning:datatable data="{! v.mydata }" 
                             columns="{! v.mycolumns }" 
                             keyField="Id" 
                             onrowselection="{! c.removeRow }"
                           />
    </div>
</aura:component>
**********************************
Controller:-
controller is given below:-
({
    doinit : function(component, event, helper) {
        component.set('v.mycolumns', [
           
            {label: 'Record Number', fieldName: 'Name', type: 'integer'},
            
            {label: 'Sister Account', fieldName: 's1', type: 'text'},
            {label: 'Sister Account', fieldName: 's2', type: 'text'}

        ]);
        
        var action = component.get('c.fetchRecords');
        action.setCallback(this, function(response){
            var state = response.getState();
            if(state === "SUCCESS"){
                var allValues = response.getReturnValue();
                 for (var i = 0; i < allValues.length; i++) {
                    var row = allValues[i];
                    row.s1 = row.Sister_Company__r.Name;
                }
                 for (var i = 0; i < allValues.length; i++) {
                    var row = allValues[i];
                    row.s2 = row.Sister_Company2__r.Name;
                }
                console.log("allValues--->>> " + allValues);
                component.set('v.mydata', allValues);
            }
            else if(state === "ERROR") {
                var errors = response.getError();
                if(errors){
                    if(errors[0] && errors[0].message){
                        console.log("Error Message: " + errors[0].message);
                    }
                }
                else{
                    console.log("Unknown Error");
                }
            }
        });
        $A.enqueueAction(action);
    },
    
    removeRow : function(component, event, helper){
        var selRows = event.getParam('selectedRows');
        
        // Remove the record from the table
        var rows = component.get('v.mydata');
        for (var i = 0; i<selRows.length; i++){    
            var rowIndex = rows.indexOf(selRows[i]);
            console.log('rowIndex---->>> ' + rowIndex);
            var r=rows.splice(rowIndex, 1);   
            console.log('rrr---->>> ' + JSON.stringify(r));
            component.set('v.mydata', rows);
        }
    }
})
right now its looking like this:-User-added image

i want that it should look like this standard related list given below:-
User-added imagehow can i modify my code to achive this?
Any suggestions?
 
Hi All,
       i have a trigger in which i am inserting reverse records.i have imple mented the trigger its working fine for insertion . now i want that if i update or delete a record its reverse record should also get updated or deleted.
       my trigger is given below:-
       trigger Trigger_FBGFamily on FBG_Family__c (before insert, before update, 
                                            before delete, after insert, 
                                            after update, after delete) {
                                                
    FBGFamilyTriggerHelper.newFBGFamily = trigger.new;
    FBGFamilyTriggerHelper.oldFBGFamily = trigger.old;
    FBGFamilyTriggerHelper.newMapFBGFamily = trigger.newMap;
    FBGFamilyTriggerHelper.oldMapFBGFamily = trigger.oldMap;   
                                                
       if(!FBGFamilyTriggerHelper.runTrigger) {
        return;
    }
                                                if( Trigger.isAfter ){
                                                    if(Trigger.isInsert ){
                                                        FBGFamilyTriggerHelper.CreatingReverseFamilyRecords();   
                                                    }
                                                    
                                                }
                                                 if( Trigger.isBefore ){
                                                    if(Trigger.isDelete ){
                                                        FBGFamilyTriggerHelper.deletingReverseFamilyRecords();   
                                                    }
                                                    
                                                }
                                            }
        my helper class is given below:-
        public class FBGFamilyTriggerHelper {
    public static List<FBG_Family__c> newFBGFamily = new List<FBG_Family__c>();
    public static List<FBG_Family__c> oldFBGFamily = new List<FBG_Family__c>();
    public static Map<Id, FBG_Family__c> newMapFBGFamily = new Map<Id, FBG_Family__c>();
    public static Map<Id, FBG_Family__c> oldMapFBGFamily = new Map<Id, FBG_Family__c>();
    
        public static boolean runTrigger = TRUE;
    
     Public static void CreatingReverseFamilyRecords(){
        System.debug('processed'+newFBGFamily);
        List<FBG_Family__c> ListFamilyToInsert = New List<FBG_Family__c>();
         For(FBG_Family__c Family : newFBGFamily)
        {
            FBG_Family__c ReverseFamily = New FBG_Family__c();
            ReverseFamily.Sister_Company__c = Family.Sister_Company2__c;
            ReverseFamily.Sister_Company2__c = Family.Sister_Company__c;
            ListFamilyToInsert.Add(ReverseFamily);
            System.debug('ReverseFamily'+ListFamilyToInsert);

         }
        if(ListFamilyToInsert.Size() > 0){
            runTrigger = FALSE;
          Insert ListFamilyToInsert;
            runTrigger = TRUE;
           System.debug('ReverseFamily'+ListFamilyToInsert);

         }
    }
    public static void deletingReverseFamilyRecords(){
         //To store Family ids
    list<id> Famids = new list<id>();
    for(FBG_Family__c Family : oldFBGFamily)
    {
        system.debug('old list'+oldFBGFamily);
        Famids.add(Family.id);
    }  
    system.debug('Famids'+Famids);

    //Collecting all records related to Family records
        list<FBG_Family__c> listOfFamilyToDelete = [SELECT id  
                                                    FROM FBG_Family__c 
                                                    WHERE ID IN : Famids
                                                   ];
    system.debug('listOfFamily'+listOfFamilyToDelete);
    //deleting Reverse records
     if(listOfFamilyToDelete.Size() > 0){
     delete listOfFamilyToDelete;
      }  
    }
}
its not working for deletion.
Any suggestion? how to solve it?
Hi All,
         i have a requirement in which i created a trigger when a record is created. i am creating reverse records of same object. now i want that if record is updated or deleted it should update and delete the reverse record too.
my trigger and helper is given below:-
trigger Trigger_FBGFamily on FBG_Family__c (before insert, before update, 
                                            before delete, after insert, 
                                            after update, after delete) {
                                                
    FBGFamilyTriggerHelper.newFBGFamily = trigger.new;
    FBGFamilyTriggerHelper.oldFBGFamily = trigger.old;
    FBGFamilyTriggerHelper.newMapFBGFamily = trigger.newMap;
    FBGFamilyTriggerHelper.oldMapFBGFamily = trigger.oldMap;   
                                                
       if(!FBGFamilyTriggerHelper.runTrigger) {
        return;
    }
                                                if( Trigger.isAfter ){
                                                    if(Trigger.isInsert ){
                                                        FBGFamilyTriggerHelper.CreatingReverseFamilyRecords();   
                                                    }
                                                    
                                                }
                                            }
my helper is given below:-
public class FBGFamilyTriggerHelper {
    public static List<FBG_Family__c> newFBGFamily = new List<FBG_Family__c>();
    public static List<FBG_Family__c> oldFBGFamily = new List<FBG_Family__c>();
    public static Map<Id, FBG_Family__c> newMapFBGFamily = new Map<Id, FBG_Family__c>();
    public static Map<Id, FBG_Family__c> oldMapFBGFamily = new Map<Id, FBG_Family__c>();
    
        public static boolean runTrigger = TRUE;
    
     Public static void CreatingReverseFamilyRecords(){
        System.debug('processed'+newFBGFamily);
        List<FBG_Family__c> ListFamilyToInsert = New List<FBG_Family__c>();
         For(FBG_Family__c Family : newFBGFamily)
        {
            FBG_Family__c ReverseFamily = New FBG_Family__c();
            ReverseFamily.Sister_Company__c = Family.Sister_Company2__c;
            ReverseFamily.Sister_Company2__c = Family.Sister_Company__c;
            ListFamilyToInsert.Add(ReverseFamily);
            System.debug('ReverseFamily'+ListFamilyToInsert);

         }
        if(ListFamilyToInsert.Size() > 0){
            runTrigger = FALSE;
          Insert ListFamilyToInsert;
            runTrigger = TRUE;
           System.debug('ReverseFamily'+ListFamilyToInsert);

         }
    }
}
how to do it ? any suggestions?
Hi All,
I am creating a batch for the requirement in which if lead has duplicates based on name than a checkbox field named ToBeDeleted__c should set to true on the duplicate of a lead records.
Can anyone guide me with this requirement?
Thanks in advance
Hi All,
         i have a requirement in which i have a field on lead object called ToBeDeleted__c, which should be true when one of the following condition is true :-
1.lead name contains 'test'   
2.The owner of the lead is inactive.
3.lead has duplicate records than last created record need to be checked.
4.lead is created 1 year or more than one year ago.
I want to create a batch which set the checkbox field true when above condition met.
How to do it ?Can someone guide me with it?
Thanks
Hi All,
i am trying to automate a lightning component . i write a script for it .
but i have a lookup field on it i dont know how to test it?
my script is given below:-
package myPackage;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

public class FamilyRecords {
    public static void main(String[] args) {
         // declaration and instantiation of objects/variables
        System.setProperty("webdriver.chrome.driver","C:\\Users\\user\\Downloads\\Chromedriver_win32\\chromedriver.exe");
        WebDriver driver = new ChromeDriver();
        String baseUrl = "https://login.salesforce.com";
        driver.get(baseUrl);
        driver.findElement(By.id("username")).sendKeys("kmalek@fbgholdings.com.sfdcadmin");                        
        driver.findElement(By.id("password")).sendKeys("2&*ZMRrGFSx&");                        
        WebElement login = driver.findElement(By.id("Login"));
        login.submit();
        driver.navigate().to("https://fbg--sfdcadmin.lightning.force.com/lightning/r/Account/001S000000zb9KyIAI/view?0.source=alohaHeader");
        WebElement newpage = driver.findElement(By.cssSelector(".slds-button, .slds-button_neutral, .buttonStyle"));
        newpage.click(); 
        //driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);
        driver.navigate().to("https://fbg--sfdcadmin.lightning.force.com/lightning/o/FBG_Family__c/new?nooverride=1&backgroundContext=%2Flightning%2Fr%2FAccount%2F001S000000zb9KyIAI%2Fview%3F0.source%3DalohaHeader&0.source=alohaHeader");
        System.out.println("click submit");
        WebDriverWait wait=new WebDriverWait(driver, 20);
        WebElement namefield = wait.until(
                ExpectedConditions.visibilityOfElementLocated(By.id("5998:0")));
        namefield.sendKeys("June12");
        WebElement namefield2 = wait.until(
                ExpectedConditions.visibilityOfElementLocated(By.id("6103:0")));
        namefield2.sendKeys("June12");
        WebElement Accsubmit = driver.findElement(By.cssSelector(".slds-button, .slds-button--neutral, .uiButton--brand, .uiButton, .forceActionButton"));

        Accsubmit.click();
        System.out.println("record submit");
        WebElement option1 =  driver.findElement(By.cssSelector(".slds-checkbox_faux"));                            
        //This will Toggle the Check box         
        option1.click();    
        driver.close();
        
    }
}User-added image
 
Hi All,
i have a lightning component in which i am taking records of a custom object .here when i click on checkbox the record is removed.
but after reloading the page its coming again in data table i want that this records does not show again in data table.i dont want to delete the record.
how to do it?
Any suggestions?
my component and controller is given below:-
<aura:component controller="FBGFamilyController"
                implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" 
                access="global" >
    
    <!--aura:attribute name="PageHeading" type="String" default="Remove  False positive On Click Of Check Box" /-->
    <aura:attribute name="mydata" type="Object"/>
    <aura:attribute name="mycolumns" type="List"/>
    <aura:handler name="init" value="{!this}" action="{!c.doinit}" />
    
    
    <div class="slds-section slds-is-open">
        <h3 class="slds-section__title slds-theme_shade">
            <span class="slds-truncate slds-p-horizontal_small" title="Section Title">Family Records</span>
            <lightning:layoutItem class="right-align">
                <lightning:button label="New" onclick="{!c.createRecord}" class="buttonStyle"/>
            </lightning:layoutItem> 
        </h3>
        <lightning:datatable data="{! v.mydata }" 
                             columns="{! v.mycolumns }" 
                             keyField="Id" 
                             onrowselection="{! c.removeRow }"
                             hideCheckboxColumn="false"
                             />
        
    </div>
</aura:component>
Controller is given below:-
({
    doinit : function(component, event, helper) {
        component.set('v.mycolumns', [
            
            {label: 'Name', fieldName: 'linkName', type: 'url', 
             typeAttributes: {label: { fieldName: 'Name' }, target: '_blank'}},
            /*{label: 'Sister Account ', fieldName: 's1', type: 'url', 
             typeAttributes: {label: { fieldName: 'Sister_Company__r.Name' }, target: '_blank'}},
            {label: 'Sister Account ', fieldName: 's2', type: 'url', 
             typeAttributes: {label: { fieldName: ' Sister_Company2__r.Name' }, target: '_blank'}}*/
            {label: 'Division', fieldName: 'd1', type: 'text'},
            {label: 'Sister Account', fieldName: 's1', type: 'text'},
            {label: 'Sister Account', fieldName: 's2', type: 'text'},
            {label: 'State', fieldName: 'State__c', type: 'text'},
            {label: 'Type', fieldName: 'Type__c', type: 'text'},
            {label: 'Owner', fieldName: 'Oid', type: 'text'}
        ]);
        
        var action = component.get('c.fetchRecords');
        var recordId =  component.get("v.recordId");
        action.setParams({rid : recordId});
        action.setCallback(this, function(response){
            var state = response.getState();
            if(state === "SUCCESS"){
                var allValues = response.getReturnValue();
                
                for (var i = 0; i < allValues.length; i++) {
                    var row = allValues[i];
                    row.s1 = row.Sister_Company__r.Name;
                }
                for (var i = 0; i < allValues.length; i++) {
                    var row = allValues[i];
                    row.s2 = row.Sister_Company2__r.Name;
                }
                 for (var i = 0; i < allValues.length; i++) {
                    var row = allValues[i];
                    row.d1 = row.Sister_Company__r.RecordType.Name;
                }
                for (var i = 0; i < allValues.length; i++) {
                    var row = allValues[i];
                    row.Oid = row.Owner.Name;
                }
                 
                allValues.forEach(function(record){
                    record.linkName = '/'+record.Id;
                });
                /* allValues.forEach(function(record){
                     record.s1 = '/'+record.Sister_Company__r.Id;
                }); 
                 allValues.forEach(function(record){
                    record.s2 = '/'+record.Sister_Company2__r.Id;
                }); */
                console.log("allValues--->>> " + allValues);
                component.set('v.mydata', allValues);
            }
            else if(state === "ERROR") {
                var errors = response.getError();
                if(errors){
                    if(errors[0] && errors[0].message){
                        console.log("Error Message: " + errors[0].message);
                    }
                }
                else{
                    console.log("Unknown Error");
                }
            }
        });
        $A.enqueueAction(action);
    },
    
    removeRow : function(component, event, helper){
        var selRows = event.getParam('selectedRows');
        
        // Remove the record from the table
        var rows = component.get('v.mydata');
        for (var i = 0; i<selRows.length; i++){    
            var rowIndex = rows.indexOf(selRows[i]);
            console.log('rowIndex---->>> ' + rowIndex);
            var r=rows.splice(rowIndex, 1);   
            
            console.log('rrr---->>> ' + JSON.stringify(r));
            component.set('v.mydata', rows);
        }
    },
    
     createRecord : function (component, event, helper) {
        var createRecordEvent = $A.get("e.force:createRecord");
        createRecordEvent.setParams({
            "entityApiName": "FBG_Family__c"
        });
        createRecordEvent.fire();
    }
    
})
Hi All,
         i am trying to make the lookup field a hyper link which show the Account clicking on it.
my controller  is given below:-
 ({

    doinit : function(component, event, helper) {
        component.set('v.mycolumns', [
            {label: 'Record Number ', fieldName: 'linkName', type: 'url', 
             typeAttributes: {label: { fieldName: 'Name' }, target: '_blank'}},
            {label: 'Sister Account ', fieldName: 's1', type: 'url', 
             typeAttributes: {label: { fieldName: 'Sister_Company__c' },value:{fieldName: 'Sister_Company__c.Id'}, target: '_blank'}},
            {label: 'Sister Account ', fieldName: 's2', type: 'url', 
             typeAttributes: {label: { fieldName: ' Sister_Company2__c' },value:{fieldName: 's2'}, target: '_blank'}}

          
        ]);
        
        var action = component.get('c.fetchRecords');
        var recordId =  component.get("v.recordId");
        action.setParams({rid : recordId});
        action.setCallback(this, function(response){
            var state = response.getState();
            if(state === "SUCCESS"){
                var allValues = response.getReturnValue();
            
                  allValues.forEach(function(record){
                    record.linkName = '/'+record.Id;
                });
               allValues.forEach(function(record){
                    record.s1 = '/'+record.Sister_Company__r.Name;
                }); 
                 allValues.forEach(function(record){
                    record.s2 = '/'+record.Sister_Company2__r.Id;

                }); 
                console.log("allValues--->>> " + allValues);
                component.set('v.mydata', allValues);
            }
            else if(state === "ERROR") {
                var errors = response.getError();
                if(errors){
                    if(errors[0] && errors[0].message){
                        console.log("Error Message: " + errors[0].message);
                    }
                }
                else{
                    console.log("Unknown Error");
                }
            }
        });
        $A.enqueueAction(action);
    },
    
    removeRow : function(component, event, helper){
        var selRows = event.getParam('selectedRows');
        
        // Remove the record from the table
        var rows = component.get('v.mydata');
        for (var i = 0; i<selRows.length; i++){    
            var rowIndex = rows.indexOf(selRows[i]);
            console.log('rowIndex---->>> ' + rowIndex);
            var r=rows.splice(rowIndex, 1);   
            
            console.log('rrr---->>> ' + JSON.stringify(r));
            component.set('v.mydata', rows);
         }
    }
 })     
                here the name is working as hyper link but on lookup i am getting ids as hyperlink not their name.
                i want lookup field (Sister_Company__c's name as hyper link.
                how to do it?
                Any suggestions?
Hi All,
 i created a ligtning component in which i am showing records of custom object having lookup of account.
i want that it should show only those custom object records which are related to that particular account in which related list  i am using it.
how to do it?
Any suggestions?
My component and controller is given below:-
<aura:component controller="FBGFamilyController"
                implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" 
                access="global" >
    
    <aura:attribute name="PageHeading" type="String" default="Remove  False positive On Click Of Check Box" />
    <aura:attribute name="mydata" type="Object"/>
    <aura:attribute name="mycolumns" type="List"/>

    
    <aura:handler name="init" value="{!this}" action="{!c.doinit}" />
    
    <div class="slds-m-top--xx-large">
        <div class="slds-page-header">
            <div class="slds-align--absolute-center">
                <div class="slds-text-heading--large">       
                    {!v.PageHeading}
                </div>
            </div>
        </div>
    </div>
    
 

    
    <div class="slds-section slds-is-open">
        <h3 class="slds-section__title slds-theme_shade">
              <span class="slds-truncate slds-p-horizontal_small" title="Section Title">Family Records</span>
          </h3>
        

        <lightning:datatable data="{! v.mydata }" 
                             columns="{! v.mycolumns }" 
                             keyField="Id" 
                             onrowselection="{! c.removeRow }"
                           />
    </div>
</aura:component>
**********************************
controller is given below:-
({
    doinit : function(component, event, helper) {
        component.set('v.mycolumns', [
           
            {label: 'Record Number', fieldName: 'Name', type: 'integer'},
            
            {label: 'Sister Account', fieldName: 's1', type: 'text'},
            {label: 'Sister Account', fieldName: 's2', type: 'text'}

        ]);
        
        var action = component.get('c.fetchRecords');
        action.setCallback(this, function(response){
            var state = response.getState();
            if(state === "SUCCESS"){
                var allValues = response.getReturnValue();
                 for (var i = 0; i < allValues.length; i++) {
                    var row = allValues[i];
                    row.s1 = row.Sister_Company__r.Name;
                }
                 for (var i = 0; i < allValues.length; i++) {
                    var row = allValues[i];
                    row.s2 = row.Sister_Company2__r.Name;
                }
                console.log("allValues--->>> " + allValues);
                component.set('v.mydata', allValues);
            }
            else if(state === "ERROR") {
                var errors = response.getError();
                if(errors){
                    if(errors[0] && errors[0].message){
                        console.log("Error Message: " + errors[0].message);
                    }
                }
                else{
                    console.log("Unknown Error");
                }
            }
        });
        $A.enqueueAction(action);
    },
    
    removeRow : function(component, event, helper){
        var selRows = event.getParam('selectedRows');
        
        // Remove the record from the table
        var rows = component.get('v.mydata');
        for (var i = 0; i<selRows.length; i++){    
            var rowIndex = rows.indexOf(selRows[i]);
            console.log('rowIndex---->>> ' + rowIndex);
            var r=rows.splice(rowIndex, 1);   
            console.log('rrr---->>> ' + JSON.stringify(r));
            component.set('v.mydata', rows);
        }
    }
})
******************************************************
public class FBGFamilyController {
        @AuraEnabled
    public static List<FBG_Family__c> fetchRecords() {
        return [SELECT Id, Name, Sister_Company__r.Name, Sister_Company2__r.Name FROM FBG_Family__c];
    }
}
Hi All,
       i have a trigger in which i am inserting reverse records.i have imple mented the trigger its working fine for insertion . now i want that if i update or delete a record its reverse record should also get updated or deleted.
       my trigger is given below:-
       trigger Trigger_FBGFamily on FBG_Family__c (before insert, before update, 
                                            before delete, after insert, 
                                            after update, after delete) {
                                                
    FBGFamilyTriggerHelper.newFBGFamily = trigger.new;
    FBGFamilyTriggerHelper.oldFBGFamily = trigger.old;
    FBGFamilyTriggerHelper.newMapFBGFamily = trigger.newMap;
    FBGFamilyTriggerHelper.oldMapFBGFamily = trigger.oldMap;   
                                                
       if(!FBGFamilyTriggerHelper.runTrigger) {
        return;
    }
                                                if( Trigger.isAfter ){
                                                    if(Trigger.isInsert ){
                                                        FBGFamilyTriggerHelper.CreatingReverseFamilyRecords();   
                                                    }
                                                    
                                                }
                                                 if( Trigger.isBefore ){
                                                    if(Trigger.isDelete ){
                                                        FBGFamilyTriggerHelper.deletingReverseFamilyRecords();   
                                                    }
                                                    
                                                }
                                            }
        my helper class is given below:-
        public class FBGFamilyTriggerHelper {
    public static List<FBG_Family__c> newFBGFamily = new List<FBG_Family__c>();
    public static List<FBG_Family__c> oldFBGFamily = new List<FBG_Family__c>();
    public static Map<Id, FBG_Family__c> newMapFBGFamily = new Map<Id, FBG_Family__c>();
    public static Map<Id, FBG_Family__c> oldMapFBGFamily = new Map<Id, FBG_Family__c>();
    
        public static boolean runTrigger = TRUE;
    
     Public static void CreatingReverseFamilyRecords(){
        System.debug('processed'+newFBGFamily);
        List<FBG_Family__c> ListFamilyToInsert = New List<FBG_Family__c>();
         For(FBG_Family__c Family : newFBGFamily)
        {
            FBG_Family__c ReverseFamily = New FBG_Family__c();
            ReverseFamily.Sister_Company__c = Family.Sister_Company2__c;
            ReverseFamily.Sister_Company2__c = Family.Sister_Company__c;
            ListFamilyToInsert.Add(ReverseFamily);
            System.debug('ReverseFamily'+ListFamilyToInsert);

         }
        if(ListFamilyToInsert.Size() > 0){
            runTrigger = FALSE;
          Insert ListFamilyToInsert;
            runTrigger = TRUE;
           System.debug('ReverseFamily'+ListFamilyToInsert);

         }
    }
    public static void deletingReverseFamilyRecords(){
         //To store Family ids
    list<id> Famids = new list<id>();
    for(FBG_Family__c Family : oldFBGFamily)
    {
        system.debug('old list'+oldFBGFamily);
        Famids.add(Family.id);
    }  
    system.debug('Famids'+Famids);

    //Collecting all records related to Family records
        list<FBG_Family__c> listOfFamilyToDelete = [SELECT id  
                                                    FROM FBG_Family__c 
                                                    WHERE ID IN : Famids
                                                   ];
    system.debug('listOfFamily'+listOfFamilyToDelete);
    //deleting Reverse records
     if(listOfFamilyToDelete.Size() > 0){
     delete listOfFamilyToDelete;
      }  
    }
}
its not working for deletion.
Any suggestion? how to solve it?
Hi All,
 i created the batch given below:-
 //Batch to create FBGFamily junction records for Account having same name
public class BatchFBGFamilies implements Database.Batchable<sObject> {
    //run method to execute batch on one record
    public static void run( Set<Id> AccIds ) {
        List<Account> accountRecords =  [Select id, Name  
                                         From Account
                                         Where Id IN:  AccIds ];
        executeHelper( accountRecords );                  
    }
    //Start method to get All Account which is exetuing batch
    public Database.QueryLocator start(Database.BatchableContext BC){
        String query = 'Select Id, Name ' +
            'FROM Account';
        return Database.getQueryLocator(query);
    }
    
    public void execute(Database.BatchableContext BC, List<Account> accounts){
        executeHelper( accounts );
    }
    
    public void finish(Database.BatchableContext BC){
    }
    
    //method to perform record creation of junction object for Account having same name
    public static void executeHelper( List<Account> accounts ) {
        //set to get Account having duplicate name
        Set<String> duplicateNames = new Set<String>();
        for (Account account : accounts)
        {
            duplicateNames.add(account.Name);
        }
        
        
        //map to get Account name and list of AccountIds having same name
        Map<String, List<Account>> mapDuplicateAccNameToIds = new Map<String, List<Account>>();
        for(Account acc : [SELECT id,name FROM Account  where Name IN: duplicateNames AND ID NOT IN : accounts]) {
            if(mapDuplicateAccNameToIds.containsKey(acc.Name)) {
                List<Account> ListDuplicates = mapDuplicateAccNameToIds.get(acc.Name);
                ListDuplicates.add(acc);
                //System.debug('ListDuplicates'+ListDuplicates);
                mapDuplicateAccNameToIds.put(acc.Name, ListDuplicates);
            } else {
                mapDuplicateAccNameToIds.put(acc.Name, new List<Account> { acc });
            }
        }
        System.debug('mapDuplicateAccNameToIds'+mapDuplicateAccNameToIds);
        Map<String,FBG_Family__c> mapAlreadyexistFamily = new Map<String,FBG_Family__c>();
        for(FBG_Family__c existFamily : [select id, Name, Sister_Company__c, Sister_Company2__c FROM FBG_Family__c ]){
            String key = String.valueOf(existFamily.Sister_Company__c) + String.valueOf(existFamily.Sister_Company2__c);
            mapAlreadyexistFamily.put(key,existFamily);

        }
        //System.debug('Already exit'+mapAlreadyexistFamily);
        
        //creating junction object records
        List<FBG_Family__c> ListFBGFamily = new List<FBG_Family__c>();
        if(mapDuplicateAccNameToIds.Size() > 0){
            for (Account acc : accounts)
            {
                if( mapDuplicateAccNameToIds.containsKey(acc.Name) ){
                    System.debug('account'+accounts);
                    List<Account> DuplicateAccount = mapDuplicateAccNameToIds.get(acc.Name);
                    //System.debug('DuplicateAccount'+DuplicateAccount);
                    If(DuplicateAccount.Size() > 0) {
                        for(Account Acc1 : DuplicateAccount ){
                            FBG_Family__c Family =  new FBG_Family__c();
                            Family.Sister_Company__c =  acc.id;
                            if( acc.Id != Acc1.Id){
                                Family.Sister_Company2__c = Acc1.id;
                                String key = String.valueOf(Family.Sister_Company__c) + String.valueOf(Family.Sister_Company2__c);
                                if(!mapAlreadyexistFamily.containsKey(key)){
                                    ListFBGFamily.add(Family); 

                                }
                            } 
                        }
                    }   
                }
                
                system.debug('ListFBGFamily'+ListFBGFamily);
                
            }
        }
        if( ListFBGFamily.Size() > 0 ){
            FBGFamilyTriggerHelper.runTrigger = FALSE;
            Insert ListFBGFamily;
        }
    }
}
i created the test class for it but its not giving me the coverage.
my test  class is given below:-
@istest
public class BatchFBGFamiliesTest {
    Static testmethod void creatingFamilyRecordTest(){
        
        Account acc = new Account();
        acc.Name = 'Test18';
        insert acc;
        Account acc1 = new Account();
        acc1.Name = 'Test18';
        insert acc1;
        Account acc2 = new Account();
        acc2.Name = 'Test18';
        insert acc2;
        test.startTest();
        BatchFBGFamilies obj = new BatchFBGFamilies();
        database.executeBatch(obj);
        test.stopTest();
        List<FBG_Family__c> ListFamily = [SELECT id, Name
                                          FROM FBG_Family__c
                                         ];
        List<FBG_Family__c> ListFamilyHavingFirstAccount = [SELECT id, Name
                                                            FROM FBG_Family__c
                                                            WHERE Sister_Company__c =: acc.id 
                                                            OR Sister_Company2__c =: acc.id
                                                           ];
        List<FBG_Family__c> ListFamilyHavingSecondAccount = [SELECT id, Name
                                                             FROM FBG_Family__c
                                                             WHERE Sister_Company__c =: acc1.id 
                                                             OR Sister_Company2__c =: acc1.id
                                                            ];
        List<FBG_Family__c> ListFamilyHavingThirdAccount = [SELECT id, Name
                                                            FROM FBG_Family__c
                                                            WHERE Sister_Company__c =: acc2.id 
                                                            OR Sister_Company2__c =: acc2.id
                                                           ];
        List<FBG_Family__c> ListFamilyFirstAccountAsCompany1 = [SELECT id, Name
                                                                FROM FBG_Family__c
                                                                WHERE Sister_Company__c =: acc.id 
                                                               ];
        System.assertEquals(6, ListFamily.Size());
        System.assertEquals(4, ListFamilyHavingFirstAccount.Size());
        System.assertEquals(4, ListFamilyHavingSecondAccount.Size());
        System.assertEquals(4, ListFamilyHavingThirdAccount.Size());
        System.assertEquals(2, ListFamilyFirstAccountAsCompany1.Size());
        
        
    }
    static testmethod void RunMethodTest(){
        Account acc = new Account();
        acc.Name = 'Test18';
        insert acc;
        BatchFBGFamilies.run( new Set<Id>{ acc.Id });
    }
} how to cover the remaining part?bold lines are not covering
Any suggestions?
Hi All,
        i have created the batch in which i am creating  Custom object records for duplicate accounts.
        when i run  the batch i have null pointer exeption at bold lines.
        my batch is given below:-
        
        //Batch to create FBGFamily junction records for Account having same name
public class BatchFBGFamilies implements Database.Batchable<sObject> {
    //run method to execute batch on one record
    public static void run( Set<Id> AccIds ) {
        List<Account> accountRecords =  [Select id, Name  
                                         From Account
                                         Where Id IN:  AccIds ];
        executeHelper( accountRecords );                  
    }
    //Start method to get All Account which is exetuing batch
    public Database.QueryLocator start(Database.BatchableContext BC){
        String query = 'Select Id, Name ' +
            'FROM Account';
        return Database.getQueryLocator(query);
    }
    
    public void execute(Database.BatchableContext BC, List<Account> accounts){
        executeHelper( accounts );
    }
    
    public void finish(Database.BatchableContext BC){
    }
    
    //method to perform record creation of junction object for Account having same name
    public static void executeHelper( List<Account> accounts ) {
        //set to get Account having duplicate name
        Set<String> duplicateNames = new Set<String>();
        for (Account account : accounts)
        {
            duplicateNames.add(account.Name);
        }
        
        //map to get Account name and list of AccountIds having same name
        Map<String, List<Account>> mapDuplicateAccNameToIds = new Map<String, List<Account>>();
        for(Account acc : [SELECT id,name FROM Account  where Name IN: duplicateNames AND Id NOT IN : accounts]) {
            if(mapDuplicateAccNameToIds.containsKey(acc.Name)) {
                List<Account> ListDuplicates = mapDuplicateAccNameToIds.get(acc.Name);
                ListDuplicates.add(acc);
                mapDuplicateAccNameToIds.put(acc.Name, ListDuplicates);
            } else {
                mapDuplicateAccNameToIds.put(acc.Name, new List<Account> { acc });
            }
        }
        Map<String,FBG_Family__c> mapAlreadyexistFamily = new Map<String,FBG_Family__c>();
        for(FBG_Family__c existFamily : [select id, Name, Sister_Company__c, Sister_Company2__c FROM FBG_Family__c ]){
            String key = String.valueOf(existFamily.Sister_Company__c) + String.valueOf(existFamily.Sister_Company2__c);
            mapAlreadyexistFamily.put(key,existFamily);
        }
        //System.debug('Already exit'+mapAlreadyexistFamily);
        
        //creating junction object records
        List<FBG_Family__c> ListFBGFamily = new List<FBG_Family__c>();
        for (Account acc : accounts)
        {
            List<Account> DuplicateAccount = mapDuplicateAccNameToIds.get(acc.Name);
            System.debug('DuplicateAccount'+DuplicateAccount);
            for(Account Acc1 : DuplicateAccount ){    //here its giving null pointer exeption
                FBG_Family__c Family =  new FBG_Family__c();
                Family.Sister_Company__c =  acc.id;
                if( acc.Id != Acc1.Id){
                    Family.Sister_Company2__c = Acc1.id;
                    String key = String.valueOf(Family.Sister_Company__c) + String.valueOf(Family.Sister_Company2__c);
                    if(!mapAlreadyexistFamily.containsKey(key)){
                        ListFBGFamily.add(Family); 
                    }
                    
                } 
            }
        }
        if( ListFBGFamily.Size() > 0 ){
            FBGFamilyTriggerHelper.runTrigger = FALSE;
            Insert ListFBGFamily;
        }
    }
}
        how to solve this any suggestions?
 hi All,
i Created a map in which i am taking two ids as key .i created the map as below:-
 Map<Id,FBG_Family__c> mapAlreadyexitFamily = new Map<Id,FBG_Family__c>();
        for(FBG_Family__c existFamily : [select id, Name, Sister_Company__c, Sister_Company2__c FROM FBG_Family__c ]){
            String key = String.valueOf(existFamily.Sister_Company__c) + String.valueOf(existFamily.Sister_Company__c);
            mapAlreadyexitFamily.put(key,existFamily);
        }
but its giving me error:- Invalid id: nullnull.
how can i create a map having two ids as a key and get value related to that key which is  a record.
Any suggestions, how to do it?
Hi All,
        i have requirement in which i want to show custom object(FBG_Family__c) records in lighning component.every record has checkbox besides it and when the checkbox is clicked that record should be removed from the list (not delete from database)component.
        how to do it?
        Any suggestions?
All,
I'm working on Selenium Test Automation of my App using the LEX.  In Classic, locators are static in that I can reference an ID number or name, whereas it seems the same field/object in LEX has dynamic IDs depending on when I access said element.

HTML from LEX yields:
<a aria-required="true" class="select" aria-disabled="false" aria-haspopup="true" tabindex="0" role="button" aria-label="Enrollment Type" title="" href="javascript:void(0);" data-aura-rendered-by="2944:0" data-interactive-lib-uid="60">--None--</a>

I try to use the bold faced section as a locator, but it changes each time I click on it.  Here's another example of the same elment. As you can see the id is now 90, instead of 60 above.
<a aria-required="true" class="select" aria-disabled="false" aria-haspopup="true" tabindex="0" role="button" aria-label="Enrollment Type" title="" href="javascript:void(0);" data-aura-rendered-by="4995:0" data-interactive-lib-uid="90">--None--</a>

Here's a snippet from classic, where I can always US the same ID.  It never changes.  Has anyone found a solution to this problem for finding element locators in LEX?
<select id="00No000000DyWd7" name="00No000000DyWd7" tabindex="8"><option value="">--None--</option><option value="New Enrollment">New Enrollment</option><option value="Re-Enrollmet">Re-Enrollmet</option><option value="Re-Validation">Re-Validation</option><option value="Information Update">Information Update</option></select>