• Ravi Dutt Sharma
  • PRO
  • 2505 Points
  • Member since 2014
  • PayPal


  • Chatter
    Feed
  • 77
    Best Answers
  • 3
    Likes Received
  • 0
    Likes Given
  • 19
    Questions
  • 562
    Replies
Hello,
I have an Apex class where I am parsing the selected values from a multiselect.
How can I add double quotes to each element?
I have big, small, medium.
I need "big","small","medium"

Any suggestion would be appreciated.
Cheers,
P
I have written a schedule class to update the lead source to web if the lead source is null. I have written test class as well. But code coverage is 0% can anyone help me so that code coverage is 100%

Class 

global class LeadMaintanace implements Schedulable{
    global void execute(SchedulableContext SC) {
        List<Lead> li =[Select Id,Name from Lead where LeadSource = 'null' LIMIT 10];
        List<Lead> lu= new  List<Lead>();
        if(!li.isEmpty()){
            for(Lead ld:li){
                ld.LeadSource = 'Web';
                lu.add(ld);
            }
                }
        update lu;
    }

}

test class

@isTest
public class TestLeadMaintanace {
    @testsetup
    static void setup(){
        List<Lead> li = new List<Lead>();
        for(Integer i;i<10;i++){
            Lead ld = new Lead(Company = 'Proseraa',LastName ='MN',Status = 'Working - Contacted');
            li.add(ld);
            
            
        }
        update li;
        
    }
    static testmethod  void TestJobSchedule(){
        string sch = '0 30 12 2 20 ?';
        Test.startTest();
        string jobid=System.Schedule('SchedulableClass',sch, new LeadMaintanace());
        List<Lead> li =[Select Id from Lead where LeadSource=null limit 10];
        system.assertEquals(10,li.size());
        test.stopTest();
        
    }
    
    
}
Hi there,
I'm trying to return just the live Accounts through SOQL but when I attach status to the where clause it errors, is the Status column in the accounts table or do i need to join to another table? Whats the best way to find the whole schema?

Thank you

Dave.
 
Hello,
Lookin gto do an audit on the number of users assigned to all of the profiles in an org.  Is there a way to get the user count on each profile? Goal is to remove/consolidate profiles if possible.
Thanks
P
What is the easy way to retrieve all the components within a custom application and deploy to a seperate org. I used VS code but I had put every component in to the package xml file. Is there a ways that I can retrieve the full packagexml fiel of a app with all components.
Hi Team,

I have for-each loop in my LWC component. And I want to check below condition inside  the loop.
 
<template for:each={object.MonthListBefore} for:item="month" >
      <template if:true={month == 'Jan'}> 
       <li key={object.Id} class="year">{object.currentYear}</li>       
</template>
</template>



But this is not working.  I am not sure how could I use the arithmetic comparison in HTML file of LWC. Could anyone please help me to resolve this?
Hi,
I am need to to salesforce, I am writing a visualforce page to display check boxes and list of accounts with a process button. Upon slecting the accounts and the check boxes the process button should contain a method which displays the list of contacts related to selected accounts.
I am unable to retrieve the list of contact names using the selected accounts.I am getting an error when i use a soql query to retrieve the contacts using the account id.

Below is my apex code for above requirment.
Please let me know if my question is not clear.


public class accountcontactwrap {
 public list<accountwrap> warpacc{get;set;}
 public list<account> selectedAccounts{get;set;}
 public list<contact> cont{get;set;}
// public list<contactwrap> wrapcon{get;set;}
  public accountcontactwrap(){
   warpacc=new list<accountwrap>();
   for(account ab:[select id,name,phone from account limit 10]){
    warpacc.add(new accountwrap(ab));
   }
  }
  
public void showcontacts(){
cont=new list<contact>();
 for(accountwrap warpobj:warpacc)
 {
  if(warpobj.isSelected==true){
  cont=[select lastname from contact where account.id=warpobj.acc.id];
   
  }
 }
}

 public class accountwrap{
 public account acc{get;set;}
 public boolean isSelected{get;set;}
  public accountwrap(account a){
   acc=a;
   isSelected=false; 
  }
I have written a test class for which it is showing 45% coverage, when i clicked on the code coverage to see what part of my code is not tested, the option is none and i cant see all tests option also i cannot see the blue and red coloured highlights in my test class? how can i see the coloured highlights and how can i get the all tests option?
THANKS!
Hi Gurus,
I have a trigger which inturn calls a apex method to make a API call to the third party.  After the third party returns the response, I should he updating the values on the record which called the API.

I am able to capture the response but while updating the record I am getting the error.  I am sure, the way I am calling the update method is causing the issue.  

Here is the trigger code:
-------------------------------------------

trigger updateSEToTR on Service_Entity__c (after insert, after update) { 
    //instead of calling the method directly, first iterate over all records and collects Ids of all records to be processed.
    //synchSEDeptSitesToTR.syncSEToTR();
       List<Id> lstSEToUpdate=new List<Id>(); 
        system.debug('---Inside---');
        if((Trigger.isInsert && Trigger.isAfter) || (Trigger.isUpdate && Trigger.isAfter))
        //if((Trigger.isInsert && Trigger.isAfter))
        {
            for(Service_Entity__c se : (List<Service_Entity__c>)trigger.new)
            {   
                If (se.Sync_Status__c<>'Error' && se.Send_To_TR__c==True)
                {
                    lstSEToUpdate.add(se.Id);
                }
            }
        system.debug('---lstSEToUpdate.size()---'+lstSEToUpdate.size());    
        //if there are records to update, call future method for callout, future method can only take list of Ids and can't take objects. Also Trigger.New and Trigger.IsInsert etc will not work in future method.
         If (lstSEToUpdate.size()> 0){
            synchSEDeptSitesToTR.syncSEToTR(lstSEToUpdate);
            synchSEDeptSitesToTR.LockSERecord(lstSEToUpdate);
         }

    }system.debug('-At the End--lstSEToUpdate.size()---'+lstSEToUpdate.size());        
}
-------------------------------------------
Here is the Apex code:
--------------------------------------------
public class synchSEDeptSitesToTR {
   @Future(callout=true) //needed to change the annotation
    public static void syncSEToTR(List<String> serviceEntityIds) {
        String trCustomerCode,trCustomerId,syncStatus,syncErrorMessage;
        List<Id> lstServiceEntitiesToUpdate=new List<Id>();
        system.debug('--serviceEntityIds--'+serviceEntityIds);
        List<Service_Entity__c> recordsToProcess=[Select Name, Id,Sync_Status__c,Send_To_TR__c, TR_Customer_Code__c,TR_Customer_Id__c,GP_Customer_Accounting_Code__c,CurrencyISOCode,
                                                  AcquisitionDB__c,Customer_Name__c,Legal_Entity__c,Sub_Branch__c,Accountrep__c,
                                                  NextRateIncrease__c,LeadSource__c,Account_Industry__c,DiscontinueService__c,
                                                  Taxable__c,TaxCode__c,Delivery_Contact__c,Delivery_Address__c,Delivery_Address_2__c,
                                                  Delivery_Contact_Phone__c,Delivery_Contact_Email__c,Delivery_State__c,Delivery_City__c,
                                                  Delivery_Postal__c,Billing_Contact__c,Billing_Address__c,Billing_Address_2__c,Billing_Contact_Phone__c,
                                                  Billing_Contact_Email__c,Billing_State__c,Billing_City__c,Billing_Postal__c,PO_Number__c,
                                                  Billing_Group__c,Breach_Reporting_Services__c,Admin_Fee_V4__c,Online_Tools__c,Billing_Dept__c,
                                                  Information__c,Customer_Notes__c,Operations_Note__c,Display_as_a_pop_up_note__c,Conversion_Services__c,
                                                  HC_Storage__c,Shredding__c,Software__c,Media_Vault__c,AcctPrefixCode__c,TR_Account_Status__c,TR_NextRateIncrease__c,
                                                  Sub_Branch__r.Sub_Branch_Code__c
                                                  from Service_Entity__c where id in : serviceEntityIds and Send_To_TR__c=True and Sync_Status__c!='Error'];
        system.debug('--Before Try--');
        try{
        //get the records, added couple of more fields which are being used down
        system.debug('--Before For--');
        for (Service_Entity__c se1 : recordsToProcess)
        {
        system.debug('--Inside For--');
            string reqXML=createXMLforServiceEntity(se1);
            system.debug('--ServiceEntity--reqXML--' +reqXML);    
            
            HttpResponse response;
            //LockSERecord(recordsToProcess);
            if ((se1.TR_Customer_Id__c==null || se1.TR_Customer_Id__c=='0') && se1.Send_To_TR__c==True)
            { 
                system.debug('------before insertTR is called');
            response=insertTR(reqXML,'E'); 
                system.debug('------after insertTR is called');
            }
            else if ((se1.TR_Customer_Id__c<>null || se1.TR_Customer_Id__c<>'0') && se1.Send_To_TR__c==True)
            {
            system.debug('------before updateTR is called');    
            system.debug('--Userinfo.getName()---'+Userinfo.getName());    
            response=updateTR(reqXML,'E'); 
            system.debug('after updateTR is called');
            }    
            
            // Parse the JSON response
            // 400 bad request
            // 200 success
            String respText=response.getBody();
            if (response.getStatusCode() != 200) {
                syncStatus='Error';
                syncErrorMessage=respText.substringBetween('<ErrorMessage>','</ErrorMessage>');
                System.debug('The status code returned was not expected: ' +
                             response.getStatusCode() + ' ' + response.getStatus());
                system.debug('syncStatus:'+syncStatus); 
            } else {
                System.debug(response.getBody());
                if (response.getStatusCode() == 200){
                    system.debug('---' + response.getStatusCode() + ' ' + response.getStatus());
                    trCustomerCode=respText.substringBetween('<TRCustomerCode>', '</TRCustomerCode>');
                    trCustomerId=respText.substringBetween('<TRCustomerId>', '</TRCustomerId>');
                    syncErrorMessage='';
                    syncStatus='Synced';
                    system.debug('trCustomerCode:'+trCustomerCode);
                    system.debug(' trCustomerId:'+ trCustomerId);
                    system.debug('syncStatus:'+syncStatus); 
                    se1.TR_Customer_Code__c=trCustomerCode;
                    se1.TR_Customer_Id__c=trCustomerId;
                    se1.Sync_Status__c=syncStatus;
                    
                  //lstServiceEntitiesToUpdate.add(se1.Id);  
                }
                //Method to update this record with the values from the response
                updateSERecord(se1.Id,trCustomerCode,trCustomerId,syncStatus);
                
            }
            
        }

        }
        catch(Exception e){ 
            System.debug('Exception:'+e.getMessage());
        } 
          
         UnLockSERecord(recordsToProcess);
    }
    //method to get token
    public static string getToken()
    {
        Http http = new Http();
        HttpRequest request = new HttpRequest();
        request.setEndpoint(tokenUrl);
        request.setMethod('POST');
        request.setHeader('Content-Type', 'application/json;charset=UTF-8');
        String jsonBody ='username=' + 'user1' + '&password=' + '12345';
        request.setBody(jsonBody);
        request.setHeader('Content-Type', 'application/x-www-form-urlencoded;charset=UTF-8');
        HttpResponse response = http.send(request);  

        String respText=response.getBody();
        String respToken=respText.substringAfter('access_token');
        
        //System.debug('---respToken---' + respToken);
        String respToken1=respText.substringBetween('access_token', 'token_type');
        String respToken2=respToken1.replace('":"','');
        String respToken3=respToken2.replace('","','');
   
        System.debug('--respToken3--' +respToken3);  
        
        return respToken3;    
    }
    //new method to create XML for Service entity
    public static string createXMLforServiceEntity(Service_Entity__c se1){
        String ZeroOne='';
        string seReq='';
        seReq=seReq+'<ServiceEntity>';
        seReq=seReq+'<ServiceEntityID>' + se1.Id+'</ServiceEntityID>';
        seReq=seReq+'<ServiceEntityCode>' + se1.Name+'</ServiceEntityCode>';
        seReq=seReq+'<TRCustomerCode>' + se1.TR_Customer_Code__c+'</TRCustomerCode>';
        //seReq = seReq.replace('null','');
        seReq=seReq+'<TRCustomerId>' + se1.TR_Customer_Id__c+'</TRCustomerId>';
        seReq=seReq+'<CustomerName>' + se1.Customer_Name__c+'</CustomerName>';
        //seReq=seReq+'<SubBranch>' + se1.Sub_Branch__c+'</SubBranch>';
        //seReq = seReq.replace('null','');
        seReq=seReq+'<SubBranchCode>'+se1.Sub_Branch__r.Sub_Branch_Code__c+'</SubBranchCode>';
        If (se1.AcctPrefixCode__c<>'-')
        {
        seReq=seReq+'<AccountPrefixCode>' + se1.AcctPrefixCode__c+'</AccountPrefixCode>';
        }
        else
        {
        seReq=seReq+'<AccountPrefixCode>MA-8</AccountPrefixCode>';
        }    
        //seReq = seReq.replace('-','MA-8');
        seReq=seReq+'<GPCustomerAccountingCode>' + se1.GP_Customer_Accounting_Code__c+'</GPCustomerAccountingCode>';
        seReq=seReq+'<Currency>' + se1.CurrencyISOCode+'</Currency>';
        //List<acquisition__c> a; //acquisition__c a;
        List<acquisition__c> a=[select name from acquisition__c where id=:se1.AcquisitionDB__c Limit 1];        
        If (a.size()==0)
        {
        seReq=seReq+'<Acquisition></Acquisition>';     
        }
        else{
            seReq=seReq+'<Acquisition>' + a[0].Name+'</Acquisition>';}
  
        string LineOfBusiness='';
               
        seReq=seReq+'<LinesofBusiness>' + LineOfBusiness+'</LinesofBusiness>';
        seReq=seReq+'<LegalEntity>' + se1.Legal_Entity__c+'</LegalEntity>';
        
        List<User> c3=[select name from User where id=:se1.Accountrep__c Limit 1];

        If (c3.size()==0){
        seReq=seReq+'<AccountRep></AccountRep>';
        }
        Else
        {seReq=seReq+'<AccountRep>' + c3[0].Name+'</AccountRep>';
        }
        //seReq=seReq+'<AccountRep>' + se1.Accountrep__c+'</AccountRep>';
        seReq=seReq+'<AccountStatus>' +se1.TR_Account_Status__c+'</AccountStatus>';

        seReq=seReq+'</ServiceEntity>';    
        seReq = seReq.replace('null',''); 
        return seReq;
    }
        //method to make the call to TR and submit the request
    public static httpresponse insertTR(String Reqxml, String Type)
    {
              String token=getToken();  
            system.debug('token---'+token);
            String header1='Bearer '+token;
            Http http1 = new Http();
            HttpRequest request1 = new HttpRequest();
        If (Type=='E')
        {system.debug('before create Account///');
            request1.setEndpoint(url1);
        system.debug('after create Account///');}
        else If (Type=='D')
                    {system.debug('before create Department////');
            request1.setEndpoint(url12);
        system.debug('after create Department////');}
         else If (Type=='S')        {system.debug('before create Site///');
            request1.setEndpoint(url13);
        system.debug('after create Site///');}
            request1.setMethod('POST');
            //request1.setHeader('Content-Type', 'application/json;charset=UTF-8');
            
            request1.setHeader('Authorization',header1);
            request1.setHeader('Accept', 'application/xml');
            request1.setHeader('Content-Type', 'application/xml');
            
            //string reqXML=createXMLforServiceEntity(se1);
            system.debug('---reqXML--' +ReqXML);
            request1.setBody(ReqXML);
            request1.setTimeout(60000);
            If (test.isRunningTest())
            {
                //write the code for response
                
            }
        Else{//once u generate the fake response uncomment the 238 and comment 240
            //HttpResponse response1 = http1.send(request1);  
            }   
            HttpResponse response1 = http1.send(request1);
        
            System.debug('--response1.getStatusCode() + -- + response1.getStatus()'+response1.getStatusCode() + ' ' + response1.getStatus());
            System.debug('---response1.getBody--' +response1.getBody());
            return response1;
    }
    public static httpresponse updateTR(String Reqxml,String Type)
    {
              String token=getToken();  
            //system.debug('token---'+token);
            String header1='Bearer '+token;
            Http http1 = new Http();
            HttpRequest request1 = new HttpRequest();
        If (Type=='E')
        {   system.debug('before update Account'); 
            request1.setEndpoint(url14);//?_HttpMethod=PATCH');
        system.debug('after update Account');}
        else If (Type=='D')
                    {system.debug('before update Department');
            request1.setEndpoint(url15);
        system.debug('after update Department');}
         else If (Type=='S')        {system.debug('before update Site');
            request1.setEndpoint(url16);
        system.debug('after update Site');}    
        //request1.setHeader('X-HTTP-Method-Override','PATCH');
        request1.setMethod('PUT');
       //request1.setMethod('PATCH');
            //request1.setHeader('Content-Type', 'application/json;charset=UTF-8');
            
            request1.setHeader('Authorization',header1);
            request1.setHeader('Accept', 'application/xml');
            request1.setHeader('Content-Type', 'application/xml');
            
            //string reqXML=createXMLforServiceEntity(se1);
            system.debug('---reqXML--' +ReqXML);
            request1.setBody(ReqXML);
            //request1.setTimeout(10000);
            HttpResponse response1 = http1.send(request1);  
            System.debug('--response1.getStatusCode() + -- + response1.getStatus()'+response1.getStatusCode() + ' ' + response1.getStatus());
            System.debug('---response1.getBody--' +response1.getBody());
            return response1;
    }
    //Lock the submitted record so that no one can edit.
    public static void LockSERecord(List<Id> recordsToProcess1)
    {
                //Lock the record from editing
        Approval.LockResult[] lrList = Approval.lock(recordsToProcess1, false);
        for(Approval.LockResult lr : lrList) { 

           if (lr.isSuccess()) 
        { 
         // Operation was successful, so get the ID of the record that was processed 
         System.debug('Successfully locked SE with ID: ' + lr.getId()); 
           } 
           else { 
         // Operation failed, so get all errors         
         for(Database.Error err : lr.getErrors()) { 
               System.debug('The following error has occurred.');           
               System.debug(err.getStatusCode() + ': ' + err.getMessage()); 
               System.debug('SE fields that affected this error: ' + err.getFields()); 
             } //for end
           } // else end
         } // main for end
        
        //End Locking process
    }
//unLock the submitted record after successful response code.
    public static void UnLockSERecord(List<Service_Entity__c> recordsToProcess1)
    {
                //Lock the record from editing
        Approval.unLockResult[] lrList = Approval.unlock(recordsToProcess1, false);
        for(Approval.unLockResult lr : lrList) { 

           if (lr.isSuccess()) 
        { 
         // Operation was successful, so get the ID of the record that was processed 
         System.debug('Successfully unlocked SE with ID: ' + lr.getId()); 
           } 
           else { 
         // Operation failed, so get all errors         
         for(Database.Error err : lr.getErrors()) { 
               System.debug('The following error has occurred.');           
               System.debug(err.getStatusCode() + ': ' + err.getMessage()); 
               System.debug('SE fields that affected this error: ' + err.getFields()); 
             } //for end
           } // else end
         } // main for end
        
        //End unLocking process
    }
    
    //method to update the SE record that got the response from API call
    @future
    public static void updateSERecord(Id ids,string trCustCode, string trCustId, string syncstatus)
    {
      List<Service_Entity__c> se2=[Select id from Service_Entity__c where id = :ids];  
      for (Service_Entity__c se3 : se2 )
        {  
      se3.TR_Customer_Code__c=trCustCode;
      se3.TR_Customer_Id__c=trCustId;
      se3.Sync_Status__c=syncstatus;
      update se3;      
        }
        
    }

--------------------------------------------
Here is the error i am getting
---------------------------------------------
Future method cannot be called from a future or batch method: synchSEDeptSitesToTR.syncSEToTR(List<String>)
---------------------------------------------

Kindly guide me in fixing this issue.

Thanks
Rao
  • July 20, 2019
  • Like
  • 0
Hi developer,
I have a doubt regarding to filtering the SOQL query.
I have a three set of id's that is:
Set<id> source;
Set<id>destination;
Set<id> sharedserver;(contains id of source and destination as well)
I have wrote query 
baselist=[select id ,name from base element where id in:sharedserver And( not in:source And not in: destination)]

but its not giving exact output. Can anyone help me out?
Thanks.
Hi All Veterans
We have a requirement wherein we have to write a trigger on contact after update. There will be a field called IsDeleted in contacts, when that field will be selected the contact will automatically get associated with a private account. Now the challenge is we have to create the  private account dynamically. Before associating the contact we have to check if that pfivate account contains 10000 contacts if yes then create a new private account and associate that contact with the newly created private account else with the previous account, this process will continue.

Thanks in advance...:)
How do you write an Apex unit test for logic that involves a time-based workflow rule? For example, a user sets a Case status = 'Completed' (soft close). Then a time-based workflow rule sets the status = 'Closed', and a beforeUpdate trigger saves the status only if all child Cases have status = 'Closed'. 

Hi,

I am trying to show a footer with navigation buttons on this lwc when the "currentStep" attribute reaches 5. This child component gets the number of "currentStep" from the parent. Once the 'Next' button is pressed, I want it to change the number to 6. I can't figure out how to send the change in number of 'currentStep' to the parent component.

shortened version of lwc.html - 

<footer class="slds-modal__footer slds-modal__footer_directional">
     <div if:true={currentStepCheck}>
            <lightning-button  variant="neutral" label="Back" icon-name="utility:back" icon-position="left"  title="Back" onclick={moveBack}>
            </lightning-button>
            <lightning-button variant="brand"  label="Next" icon-name="utility:forward  icon-position="right" title="Next" onclick={moveNext}>
            </lightning-button>
      </div>
</footer>
shortened lwc.js
import { LightningElement, api} from 'lwc';

export default class PtmForWizard extends LightningElement {
    @api recordId;
    @api parentId;
    @api currentStep;

    currentStepCheck(){
        this.currentStep = '5';
    }
    moveNext(){
         this.currentStep = '6';
    }
      moveBack(){
        this.currentStep = '4';
   }
}
shortened parent.cmp
<aura:component  implements="flexipage:availableForRecordHome,force:hasRecordId,flexipage:availableForAllPageTypes,force:lightningQuickAction,force:appHostable" access="global"> 
    <aura:attribute name="recordId" type="Id"/>
    <aura:attribute name="parentId" type="Id"/>
    <aura:attribute name="currentStep" type="String" default="1"/>

    <aura:registerEvent name="recordUpdated" type="c:selectedsObjectRecordsEvent"/>

     <force:recordData aura:id="record"
                      layoutType="FULL"
                      recordId="{!v.recordId}"
                      targetRecord="{!v.record}"
                      targetFields="{!v.efRecord }"
                      mode="VIEW"/>

     <div class="{!v.currentStep == '5' ? 'slds-show' : 'slds-hide'}" >
             <c:ptmForWizard recordId="{!v.efRecord.jstcl__PlacementTeamMember__c}" aura:id="childCmp5" parentId="{!v.recordId}" currentStep="{!v.currentStep}"/>
      </div>
</aura:component>
shortened parent.js

 
Hi All, 

I have created a trigger to prevent the deactivation of a user if they own any Accounts, Contacts or unconverted leads - as this causes issues with the Pardot sync (the Marketing team lead me to believe)

The trigger works as expected, though I'm aware that with containing SOQL queries within the FOR loop I'm breaking best practice - but would there be a performance issue on taking this out of the loop and running them on every update (even when they are not needed)

Constructive criticism welcomed

Thanks
 
//Trigger to prevent deactivation of user if they own any records referenced by Pardot.
//Deactivating a user while they still own these records (accounts, contacts, uncoverted leads) will cause issues with Pardot sync

trigger UserPreventDeactivation on User (before update) {
  
    for(User u : Trigger.new){
        User oldU = Trigger.oldMap.get(u.Id);  
        
        //Check if user has changed from active to inactive
        if(!u.IsActive && oldU.IsActive){
            
            //Query number of Accounts, Contacts and Unconverted Leads in User's Name
        	//SHOULD BE OUTSIDE OF LOOP TO BE BULKIFIED? but don't want to run these queries on every update to user if not needed.
        	//but as have only internal users, not likely to deactivate users in bulk
        	Integer contactCount = [SELECT count()
                                      FROM Contact
                                     WHERE ownerId = :u.id
                                     LIMIT 1]; 
        	Integer accountCount = [SELECT count()
                                      FROM Account
                                     WHERE ownerId = :u.id
                                     LIMIT 1];
        	Integer leadCount = [SELECT count()
                                   FROM Lead
                                  WHERE ownerId = :u.id
                                    AND isConverted = FALSE
                                  LIMIT 1];
            
            //add error to screen alerting user
            if( (contactCount + accountCount + leadCount) > 0){
            	u.addError('This user may own accounts, contacts, or unconverted leads.' +
                          'Ensure that these records are transferred to a different owner ' +
                          'before deactivating this user. This is due to issues it will cause ' +
                          'with the Pardot sync.');    
            }     
        }
    }
}



 

The code is with before insert, and I need tb before updating the code run. But when I use the Before update the code works incorrectly, it blocks everything.


trigger ReservDuplicateDate on Reserva__c (before insert) {
    
    for(Reserva__c a:Trigger.new)
    {
        List<Reserva__c> lista=new List<Reserva__c>([Select ID,Data_de_terminio__c,Data_de_inicio__c,sala__c,Orador__c from Reserva__c]);
        for(Reserva__c existentes:lista){
            if(a.sala__c == existentes.sala__c && a.Data_de_inicio__c >= existentes.Data_de_inicio__c &&
               a.Data_de_terminio__c <= existentes.Data_de_terminio__c) {
                a.adderror('Reserva Ja existente na sala com a mesma data!');
            }
            if(a.sala__c == existentes.sala__c && a.Data_de_inicio__c <= existentes.Data_de_inicio__c && 
               a.Data_de_terminio__c <= existentes.Data_de_terminio__c && a.Data_de_terminio__c >= existentes.Data_de_inicio__c ) {
                a.adderror('Reserva Ja existente na sala com a mesma data!');
            }
            if(a.sala__c == existentes.sala__c && a.Data_de_inicio__c >= existentes.Data_de_inicio__c && 
               a.Data_de_terminio__c >= existentes.Data_de_terminio__c && a.Data_de_inicio__c <= existentes.Data_de_terminio__c) {
                a.adderror('Reserva Ja existente na sala com a mesma data!');
            }
           
            if(a.sala__c == existentes.sala__c && a.Data_de_inicio__c <= existentes.Data_de_inicio__c && 
               a.Data_de_terminio__c >= existentes.Data_de_terminio__c ) {
                a.adderror('Reserva Ja existente na sala com a mesma data!');
                           
            }
            if(a.Orador__c == existentes.Orador__c && a.Data_de_inicio__c >= existentes.Data_de_inicio__c &&
               a.Data_de_terminio__c <= existentes.Data_de_terminio__c) {
                a.adderror('Esse Orador ja esta em cargo de uma reserva!');
            }
            if(a.Orador__c == existentes.Orador__c && a.Data_de_inicio__c <= existentes.Data_de_inicio__c && 
               a.Data_de_terminio__c <= existentes.Data_de_terminio__c && a.Data_de_terminio__c >= existentes.Data_de_inicio__c ) {
                a.adderror('Esse Orador ja esta em cargo de uma reserva!');
            }
            if(a.Orador__c == existentes.Orador__c && a.Data_de_inicio__c >= existentes.Data_de_inicio__c && 
               a.Data_de_terminio__c >= existentes.Data_de_terminio__c && a.Data_de_inicio__c <= existentes.Data_de_terminio__c) {
                a.adderror('Esse Orador ja esta em cargo de uma reserva!');
            }
           
            if(a.Orador__c == existentes.Orador__c && a.Data_de_inicio__c <= existentes.Data_de_inicio__c && 
               a.Data_de_terminio__c >= existentes.Data_de_terminio__c ) {
                a.adderror('Esse Orador ja esta em cargo de uma reserva!');
            }

        }
    }
    
}
 
hi, I have to write a test class for controller extension. How we apply best practice about bulking in this case? Controller extension constructor takes one standard controller instance. Do i have to instantiate for 200 Times the controller extension in test class? Thank you in advance 
Hi All

I am trying to use lightning out functionality to embed my ligthning component on some public webistes and i want it should be used there only.

Please let me know if there is any way to restrict the usuage to same.
Hi...

I'm calling a controller function in the client - side from blur event in the component.

component code 
<div class="slds-form-element slds-grid slds-wrap">
                                    <div class="slds-form-element__control slds-grow">
                                        <ui:inputText class="slds-input inputFieldWidth"
                                                      labelClass="slds-form-element__label slds-form-element__label_edit slds-no-flex"
                                                      aura:id="inputId"
                                                      blur ="{!c.closeNameBox}"
                                                      change="{!c.onNameChange}"
                                                      maxlength="17"
                                                      required="true"
                                                      label="Tracking #"
                                                      value="{!v.singleRec.Shipping_Track_Number__c}" />
                                    </div>
                                </div>

In the controller:
onNameChange : function(component,event,helper){ 
        // if edit field value changed and field not equal to blank,
        // then show save and cancel button by set attribute to true

        if(event.getSource().get("v.value").trim() != ''){ 
            component.set("v.showSaveCancelBtn",true);

        }

    },   
    
    closeNameBox : function (component, event, helper) {

      // on focus out, close the input section by setting the 'nameEditMode' att. as false   
        component.set("v.nameEditMode", false); 
      // check if change/update Name field is blank, then add error class to column -
      // by setting the 'showErrorClass' att. as True , else remove error class by setting it False   

        if(event.getSource().get("v.value").trim() == 0){
            component.set("v.showErrorClass",true);
        }else{
            component.set("v.showErrorClass",false);
        }
    }

I got the error: Cannot read property 'trim' of undefined. So, the event.getSource() return undefined...

Note: The <input... component is inside a <aura:iteration... so the aura:id="inputId" is the same for all input. I don't know if this is the reason for the error.

Please, let me know if you need more code...

Thanks,


 
I have a custom button in lightning and whenever user clicks that, whoever clicks should be assigned with his namee. what is the query that i should use in Apex controller
Hi,

I am trying to launch a flow from an aura component. In the flow, I have an apex variable of type "Apex-Defined Collection variable". How to set the value of this variable from the aura component? I have two other string variables in the flow, I am able to set them, but when I set the value in the apex defined var, the flow throws an error. Below is the relevant code from the aura component:
const flow = component.find("flowData");
const inputVariables = [
            {
            name: "varCaseId",
            type: "String",
            value: component.get("v.recordId")
        },
        {
            name: "varAccountNumber",
            type: "String",
            value: response.accountNumber
        },
        {
            name: "varIntents",
            type: "Intent",
            value: response.intents
        }
];
flow.startFlow(response.flowAPIName, inputVariables);
If I remove the third element from the inputVariables array, then the flow launches correctly, otherwise not.

 
Hi,

In LWC, on the component load, I am fetching the latitude and longitude of the logged in user and trying to display it on the component. I have created two attributes named lat and lng and marked it with @track decorator so that whenever the value of these attributes is changed, the component will rerender automatically. I am setting the value of these attributes in connectedCallback, but the updated value is not getting reflected on the component. Below is the html and js files.
 
<template>
    <div class="slds-box">
        <div class="slds-text-heading--large">Weather Report - {lat} {lng}</div>
    </div>
</template>
 
import { LightningElement, track } from 'lwc';

export default class WeatherAppContainer extends LightningElement {
    @track lat;
    @track lng;
    connectedCallback() {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(showPosition);
        }
        
        function showPosition(position) {
            console.log("position: ",position);
            console.log("position coords: ",position.coords);
            console.log("position coords lat: ",position.coords.latitude);
            this.lat = position.coords.latitude; 
            this.lng = position.coords.longitude; 
            console.log("lat: ",this.lat);
            console.log("lng: ",this.lng);
        }
    }

}

The console "position coords lat" prints the value correctly, but the next console statment does not get printed. I am guessing that we cannot use this keyword in the connectedCallback. Any pointers how to solve this? Thanks.
Hi,

Need inputs on how to parse below string and extract all the relevant information such as Source, Name etc.

Source: Web Visitor 
Name: Ravi Sharma 
Age of primary applicant: 9 


Email: test@yahoo.com 
Phone: 1234567 
Address: 10th Street 
City: Woodstock 
State: GA 
Comments: Test Comments 
Winter 19 release has brought this new tag - lightning:map to show google maps in lightning maps. I am trying to implment below example in my dev org, but the map marker is not showing up on the org.

Example given here:https://developer.salesforce.com/docs/component-library/bundle/lightning:map/example

When I check the broswer console, I can see below error:

util.js:218 Google Maps JavaScript API warning: NoApiKeys https://developers.google.com/maps/documentation/javascript/error-messages#no-api-keys
lw.j @ util.js:218
(anonymous) @ js?key=&callback=LightningPrimitiveMap.init:183
(anonymous) @ js?key=&callback=LightningPrimitiveMap.init:76
(anonymous) @ js?key=&callback=LightningPrimitiveMap.init:73
(anonymous) @ js?key=&callback=LightningPrimitiveMap.init:76
(anonymous) @ js?key=&callback=LightningPrimitiveMap.init:164
(anonymous) @ js?key=&callback=LightningPrimitiveMap.init:76
(anonymous) @ js?key=&callback=LightningPrimitiveMap.init:164
Ee @ js?key=&callback=LightningPrimitiveMap.init:75
Ae.xa @ js?key=&callback=LightningPrimitiveMap.init:164
(anonymous) @ stats.js:1
util.js:218 Google Maps JavaScript API warning: InvalidKey https://developers.google.com/maps/documentation/javascript/error-messages#invalid-key

Question1: Do we need to explicitly add google map api key? Only then the map would work? I am assuming that Salesforce should automatically take care of this?
Question 2: If the answer to above question in yes, then how do we add the api key? I have a developer key, but not sure how to add it.
Hi,

I am trying to configure SSO between Salesforce and Ringcentral. When I login to Ringcentral using the SSO option, it redirects me to the Salesforce error screen. On checking the SAML trace, I can see below error:

GET https://domain-name.my.salesforce.com/_nc_external/identity/saml/SamlError?idpError=1605 HTTP/1.1

Any pointers on how to resolve this?

 
It seems that there is a bug with lightning:input type="datetime-local" tag. When I add this tag in my component, thenchoose a date and time using the date time selector and try to save the record to database, apex is not able to take the value? Any pointers on how to save this value to a date time field present on an object. Below is the sample code I am trying to implement:

dateTimeLocal.cmp
 
<aura:component controller="DateTimeLocalCtrl">
    <aura:attribute name="lead" type="Lead" default="{'sobjectType':'Lead','id':'00Q9000001BtwNE'}"/>
	<lightning:input type="datetime-local" label="Start" name="Start" value="{!v.lead.Start__c}"/>
    <lightning:button label="Save" iconName="utility:save" onclick="{!c.doSave}"/>
</aura:component>
dateTimeLocalController.js
({
	doSave : function(component, event, helper) {
		
       var action = component.get("c.upsertLead");
        var lead = component.get("v.lead");
        console.log("*****Date: "+component.get("v.lead.Start__c"));
        // set param to method  
        action.setParams({
            'ld': lead
        });
        // set a callBack    
        action.setCallback(this, function(response) {
            var state = response.getState();
            if (state === "SUCCESS") {
                console.log("*****Success");
            }else{
                console.log("*****Failure");
            }
        });
        // enqueue the Action  
        $A.enqueueAction(action);
	}
})

DateTimeLocalCtrl.apxc
public class DateTimeLocalCtrl {

    @AuraEnabled
    public static Lead upsertLead(Lead ld){
        upsert ld;
        return ld;
    }

}


 
The convertTimeZone() does not work properly between 12am to 1pm. It gives the output for the previous day. My user is in (GMT+10:00) Australian Eastern Standard Time (New South Wales) (Australia/Sydney) timezone and when the time in this timezone is between 12am to 1am, the SOQL query gives incorrect results:

SELECT Id FROM Activity__c WHERE DAY_ONLY(convertTimeZone(Activity_Closed_Date_Time__c)) =: Date.today() 
 
I have a action support inside a apex command link which is present inside a page block table. The action support in not calling the apex method.

 
<apex:column headerValue="Call Attempt">
                        <apex:commandLink>{!cmpgnMember.Call_Attempt__c}
                        	<apex:actionSupport action="{!createCallReport}" event="onclick" />
                        </apex:commandLink>
</apex:column>
 
public PageReference createCallReport(){
        System.debug('******contactId: ');
        return null;
}

 
On the Manage Members standard page, there is a filter as shown in image below:

User-added image

Any idea how do we handle conditions such as starts with, contains, does not contain in SOQL?
I have 2 functions in my JS helper - getLatLng and getResponse. getLatLng gets the current location of the user and sets two attributes in the component namely lat and lng. getResponse uses these two attributes for further processing. I am calling both these functions from my JS controller one after the other. The problem is that getResponse gets called even before the execution of getLatLng is completed. Is there any way to set a callback so that when getLatLng sets the lat and lng on component, then only getResponse is called? Here is the code for JS controller and  JS helper.

WeatherController.js
 
({
    doInit : function(component, event, helper) {
        helper.getLatLng(component);
        helper.getResponse(component);
    }
})
WeatherHelper.js
({
    getResponse : function(component){
        var action = component.get("c.getCalloutResponseContents");
        var lat = component.get("v.lat");
        var lng = component.get("v.lng");
        action.setParams({
            "url": 'http://api.openweathermap.org/data/2.5/weather?lat=' +lat+ '&lon=' +lng+ '&appid=9b2719bd93477d05ad2575ccb81cb666&units=metric'
        });
        action.setCallback(this, function(response){
            var state = response.getState();
            if (component.isValid() && state === "SUCCESS") {
                component.set("v.response", JSON.parse(response.getReturnValue()));
            }
        });
        $A.enqueueAction(action);
    },
    
    getLatLng : function(component) {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(function(position) {
                component.set("v.lat", position.coords.latitude);
                component.set("v.lng", position.coords.longitude);
            });
        } 
    }
    
})
Thanks in advance for your help.
I am trying to build a lightning component which will display the weather condition of a particular area. For getting the weather details, I am making a webservice callout. In Weather.cmp component, I have defined a handler for the init event. So as soon as the page is loaded, the init handler gets executed, and calls a method which is present in my Apex controller named WeatherCtrl which makes a webservice callout and returns the response. I have debug statments in my Apex controller and I see that the response is coming in the Apex controller. But when I return the response from my JS helper - WeatherHelper.js, the response.getReturnValue() seems to be null. 
Any ideas what I may be doing wrong here. Here is the code:

Weather.cmp
 
<aura:component controller="WeatherCtrl">
	
    <aura:handler name="init" action="{!c.doInit}" value="{!this}"/>
    
    <aura:attribute name="response" type="WeatherResponse"/>
    
    Longitude : <ui:outputText value="{!v.response.coord.lon}"/>
    
</aura:component>

WeatherController.js
 
({
	doInit : function(component, event, helper) {
		helper.getResponse(component);
	}
})

WeatherHelper.js
 
({
	getResponse : function(component) {
		var action = component.get("c.getCalloutResponseContents");
        action.setParams({
            "url": 'http://api.openweathermap.org/data/2.5/weather?lat=12.971599&lon=77.594563&appid=9b2719bd93477d05ad2575ccb81cb666'
        });
        action.setCallback(this, function(response){
            var state = response.getState();
            if (component.isValid() && state === "SUCCESS") {
                console.log(response.getReturnValue());
                component.set("v.response", response.getReturnValue());
            }
        });
        $A.enqueueAction(action);
	}
})

WeatherCtrl.apxc
 
public class WeatherCtrl {
    
    // Pass in the endpoint to be used using the string url
    @AuraEnabled
    public static WeatherResponse getCalloutResponseContents(String url) {
        
        // Instantiate a new http object
        Http h = new Http();
        
        // Instantiate a new HTTP request, specify the method (GET) as well as the endpoint
        HttpRequest req = new HttpRequest();
        req.setEndpoint(url);
        req.setMethod('GET');
        
        // Send the request, and return a response
        HttpResponse res = h.send(req);
        System.debug('*****response: '+WeatherResponse.parse(res.getBody()));
        return WeatherResponse.parse(res.getBody());
    }
    
}

WeatherResponse.apxc
 
//
// Generated by JSON2Apex http://json2apex.herokuapp.com/
//

public class WeatherResponse{
    public static void consumeObject(JSONParser parser) {
        Integer depth = 0;
        do {
            JSONToken curr = parser.getCurrentToken();
            if (curr == JSONToken.START_OBJECT || 
                curr == JSONToken.START_ARRAY) {
                depth++;
            } else if (curr == JSONToken.END_OBJECT ||
                curr == JSONToken.END_ARRAY) {
                depth--;
            }
        } while (depth > 0 && parser.nextToken() != null);
    }

    public class Weather {
        public Integer id {get;set;} 
        public String main {get;set;} 
        public String description {get;set;} 
        public String icon {get;set;} 

        public Weather(JSONParser parser) {
            while (parser.nextToken() != JSONToken.END_OBJECT) {
                if (parser.getCurrentToken() == JSONToken.FIELD_NAME) {
                    String text = parser.getText();
                    if (parser.nextToken() != JSONToken.VALUE_NULL) {
                        if (text == 'id') {
                            id = parser.getIntegerValue();
                        } else if (text == 'main') {
                            main = parser.getText();
                        } else if (text == 'description') {
                            description = parser.getText();
                        } else if (text == 'icon') {
                            icon = parser.getText();
                        } else {
                            System.debug(LoggingLevel.WARN, 'Weather consuming unrecognized property: '+text);
                            consumeObject(parser);
                        }
                    }
                }
            }
        }
    }
    
    public class Coord {
        public Integer lon {get;set;} 
        public Integer lat {get;set;} 

        public Coord(JSONParser parser) {
            while (parser.nextToken() != JSONToken.END_OBJECT) {
                if (parser.getCurrentToken() == JSONToken.FIELD_NAME) {
                    String text = parser.getText();
                    if (parser.nextToken() != JSONToken.VALUE_NULL) {
                        if (text == 'lon') {
                            lon = parser.getIntegerValue();
                        } else if (text == 'lat') {
                            lat = parser.getIntegerValue();
                        } else {
                            System.debug(LoggingLevel.WARN, 'Coord consuming unrecognized property: '+text);
                            consumeObject(parser);
                        }
                    }
                }
            }
        }
    }
    
    public class Wind {
        public Double speed {get;set;} 
        public Double deg {get;set;} 

        public Wind(JSONParser parser) {
            while (parser.nextToken() != JSONToken.END_OBJECT) {
                if (parser.getCurrentToken() == JSONToken.FIELD_NAME) {
                    String text = parser.getText();
                    if (parser.nextToken() != JSONToken.VALUE_NULL) {
                        if (text == 'speed') {
                            speed = parser.getDoubleValue();
                        } else if (text == 'deg') {
                            deg = parser.getDoubleValue();
                        } else {
                            System.debug(LoggingLevel.WARN, 'Wind consuming unrecognized property: '+text);
                            consumeObject(parser);
                        }
                    }
                }
            }
        }
    }
    
    public class Rain {
        public Integer h3 {get;set;} 

        public Rain(JSONParser parser) {
            while (parser.nextToken() != JSONToken.END_OBJECT) {
                if (parser.getCurrentToken() == JSONToken.FIELD_NAME) {
                    String text = parser.getText();
                    if (parser.nextToken() != JSONToken.VALUE_NULL) {
                        if (text == 'h3') {
                            h3 = parser.getIntegerValue();
                        } else {
                            System.debug(LoggingLevel.WARN, 'Rain consuming unrecognized property: '+text);
                            consumeObject(parser);
                        }
                    }
                }
            }
        }
    }
    
    public class Clouds {
        public Integer all {get;set;} 

        public Clouds(JSONParser parser) {
            while (parser.nextToken() != JSONToken.END_OBJECT) {
                if (parser.getCurrentToken() == JSONToken.FIELD_NAME) {
                    String text = parser.getText();
                    if (parser.nextToken() != JSONToken.VALUE_NULL) {
                        if (text == 'all') {
                            all = parser.getIntegerValue();
                        } else {
                            System.debug(LoggingLevel.WARN, 'Clouds consuming unrecognized property: '+text);
                            consumeObject(parser);
                        }
                    }
                }
            }
        }
    }
    
    public Coord coord {get;set;} 
    public Sys sys {get;set;} 
    public List<Weather> weather {get;set;} 
    public Main main {get;set;} 
    public Wind wind {get;set;} 
    public Rain rain {get;set;} 
    public Clouds clouds {get;set;} 
    public Integer dt {get;set;} 
    public Integer id {get;set;} 
    public String name {get;set;} 
    public Integer cod {get;set;} 

    public WeatherResponse(JSONParser parser) {
        while (parser.nextToken() != JSONToken.END_OBJECT) {
            if (parser.getCurrentToken() == JSONToken.FIELD_NAME) {
                String text = parser.getText();
                if (parser.nextToken() != JSONToken.VALUE_NULL) {
                    if (text == 'coord') {
                        coord = new Coord(parser);
                    } else if (text == 'sys') {
                        sys = new Sys(parser);
                    } else if (text == 'weather') {
                        weather = new List<Weather>();
                        while (parser.nextToken() != JSONToken.END_ARRAY) {
                            weather.add(new Weather(parser));
                        }
                    } else if (text == 'main') {
                        main = new Main(parser);
                    } else if (text == 'wind') {
                        wind = new Wind(parser);
                    } else if (text == 'rain') {
                        rain = new Rain(parser);
                    } else if (text == 'clouds') {
                        clouds = new Clouds(parser);
                    } else if (text == 'dt') {
                        dt = parser.getIntegerValue();
                    } else if (text == 'id') {
                        id = parser.getIntegerValue();
                    } else if (text == 'name') {
                        name = parser.getText();
                    } else if (text == 'cod') {
                        cod = parser.getIntegerValue();
                    } else {
                        System.debug(LoggingLevel.WARN, 'Root consuming unrecognized property: '+text);
                        consumeObject(parser);
                    }
                }
            }
        }
    }
    
    public class Sys {
        public String country {get;set;} 
        public Integer sunrise {get;set;} 
        public Integer sunset {get;set;} 

        public Sys(JSONParser parser) {
            while (parser.nextToken() != JSONToken.END_OBJECT) {
                if (parser.getCurrentToken() == JSONToken.FIELD_NAME) {
                    String text = parser.getText();
                    if (parser.nextToken() != JSONToken.VALUE_NULL) {
                        if (text == 'country') {
                            country = parser.getText();
                        } else if (text == 'sunrise') {
                            sunrise = parser.getIntegerValue();
                        } else if (text == 'sunset') {
                            sunset = parser.getIntegerValue();
                        } else {
                            System.debug(LoggingLevel.WARN, 'Sys consuming unrecognized property: '+text);
                            consumeObject(parser);
                        }
                    }
                }
            }
        }
    }
    
    public class Main {
        public Double temp {get;set;} 
        public Integer humidity {get;set;} 
        public Integer pressure {get;set;} 
        public Double temp_min {get;set;} 
        public Double temp_max {get;set;} 

        public Main(JSONParser parser) {
            while (parser.nextToken() != JSONToken.END_OBJECT) {
                if (parser.getCurrentToken() == JSONToken.FIELD_NAME) {
                    String text = parser.getText();
                    if (parser.nextToken() != JSONToken.VALUE_NULL) {
                        if (text == 'temp') {
                            temp = parser.getDoubleValue();
                        } else if (text == 'humidity') {
                            humidity = parser.getIntegerValue();
                        } else if (text == 'pressure') {
                            pressure = parser.getIntegerValue();
                        } else if (text == 'temp_min') {
                            temp_min = parser.getDoubleValue();
                        } else if (text == 'temp_max') {
                            temp_max = parser.getDoubleValue();
                        } else {
                            System.debug(LoggingLevel.WARN, 'Main consuming unrecognized property: '+text);
                            consumeObject(parser);
                        }
                    }
                }
            }
        }
    }
    
    
    public static WeatherResponse parse(String json) {
        return new WeatherResponse(System.JSON.createParser(json));
    }
}


 
I have created a VF page and associated controller to override the standard New Button on lead page. In the controller, I am creating a PageReference and in the url, I am passing a parameter which populates a picklist field present on Lead record. This works fine, the picklist gets populated as expected. Now on the page layout, if I make the picklist field as read-only, the field no longer gets populated. Any hack to populate a read-only field through url params? Attaching the code for reference :

VF Page :
<apex:page standardController="Lead" extensions="LeadFieldsAutoPopulateCtrl" action="{!doRedirect}">
  </apex:page>

Apex Class :
public class LeadFieldsAutoPopulateCtrl {

    public LeadFieldsAutoPopulateCtrl(ApexPages.StandardController stdController){
    
    }
    
    //Method gets called before the Visualforce page gets loaded. It redirects the user to the New Lead detail page.
    public PageReference doRedirect(){
        Pagelayout_FieldNames__c ownerGeographyFieldName = Pagelayout_FieldNames__c.getValues('Lead_OwnerGeographyPicklist');
        String redirectURL = '/00Q/e?retURL=%2F00Q%2Fo&nooverride=1';
        String userId = UserInfo.getUserId();
        List<User> userList = new List<User>();
        if(String.isNotBlank(userId)){
            userList = [SELECT Geography__c FROM User WHERE Id =:userId];
        }
        String userGeography = '';
        if(userList.size() > 0){
            userGeography = userList.get(0).Geography__c;
        }
        if(String.isNotBlank(userGeography) && String.isNotBlank(ownerGeographyFieldName.PagelayoutFieldName__c)) {
            redirectURL = redirectURL + '&' + ownerGeographyFieldName.PagelayoutFieldName__c + '=' + EncodingUtil.urlEncode(userGeography,'UTF-8');
        }
    	PageReference pageRef = new PageReference(redirectURL);
        return pageRef;
    }
}


 
I am trying to create a clone functionality which clones the related list records as well. When I clone an account record, I clone the associated quote records also (Quotes are related to account through AccountId field). The cloned quote record has reference to the old account and I need to update the AccountId field to the new account that is cloned by my code. But since the AccountId field on Quote object is neither createable nor updateable, I am getting an exception. Any solution to this?
Thanks in advance for the help.
Lets say I have Id of Account record and I am initializing the sobject and assigning the Id to account variable. Below is the code :
sObject obj = Schema.getGlobalDescribe().get(parentObjName).newSObject() ;
obj.Id = recordId;
System.debug('****obj : '+obj);
Debug Result: 
****obj : Account:{Id=0019000001dbup5AAA}
I was hoping that the debug will have the entire information from the account example like : Account:{Id=0019000001dbup5AAA, Name=TestAccount,...}
Is there any way to initialize the sobject in a way such that it gets loaded with the entire information?
When we convert a lead, by default the account detail page is opened. I want to open the opportunity detail page if "Do not create a new opportunity upon conversion." checkbox is unchecked.
Is there any way to achieve this through configuration. I do not want to customize the entire lead conversion process for this because I have duplicate rules enabled in my org. And hadling duplicate rules in custom lead conversion will be an effort intensive task.

Thanks,
Ravi
I have DOB (API Name : BirthDate__c) and I want to calculate age in years and months. I have created two formula fields
 
Age in years

FLOOR((TODAY()- BirthDate__c )/365.2425)
 
Age in months (remaining months)

FLOOR(MOD((TODAY()-BirthDate__c),365.2425)/30)

If date of birth is 11 Aug 2013 and todays date is 11 Aug 2015, this gives result as 1 year 12 months. Instead the result should be 2 years 0 months.
I need to open quote standard page with some fields pre-populated. For that I have used URL Hacking (passing parameters in url). This technique works perfectly in browsers but does not work in Salesforce1 app.

Below is the relevant JS code :
 
window.top.location='/0Q0/e?retURL=%2F{!Opportunity.Id}&oppid={!Opportunity.Id}&Name={!Opportunity.Contact_First_Name__c}+{!Opportunity.Contact_Last_Name__c}';

Anyone has a workaround for that?
How to remove Del action link that appears on opportunity line items in a community. The profile of community user has only Read access on opportunity.
How to find associated price book for a given opportunity. For example, when I add a product under opportunity for the first time, it asks me to select a price book. Now in my apex code, I need to check whether a given opportunity already has a related price book or not?

User-added image
Hi,

I am trying to configure SSO between Salesforce and Ringcentral. When I login to Ringcentral using the SSO option, it redirects me to the Salesforce error screen. On checking the SAML trace, I can see below error:

GET https://domain-name.my.salesforce.com/_nc_external/identity/saml/SamlError?idpError=1605 HTTP/1.1

Any pointers on how to resolve this?

 
The convertTimeZone() does not work properly between 12am to 1pm. It gives the output for the previous day. My user is in (GMT+10:00) Australian Eastern Standard Time (New South Wales) (Australia/Sydney) timezone and when the time in this timezone is between 12am to 1am, the SOQL query gives incorrect results:

SELECT Id FROM Activity__c WHERE DAY_ONLY(convertTimeZone(Activity_Closed_Date_Time__c)) =: Date.today() 
 
I have DOB (API Name : BirthDate__c) and I want to calculate age in years and months. I have created two formula fields
 
Age in years

FLOOR((TODAY()- BirthDate__c )/365.2425)
 
Age in months (remaining months)

FLOOR(MOD((TODAY()-BirthDate__c),365.2425)/30)

If date of birth is 11 Aug 2013 and todays date is 11 Aug 2015, this gives result as 1 year 12 months. Instead the result should be 2 years 0 months.
How to display stagename and other fields on maps using lwc.
Currently, i am displaying only opportunity name and marker on map using location (Address fields salesforce). But how to display stagename and other fields on maps). (or) any account fields.
Please advise.Image of opportunities displayed on maps with only address
I've been working with the compent offered on this site:
https://sfdcmonkey.com/2017/04/19/download-csv-file-data-salesforce-lightning-component/

It's working perfectly, but one thing I missed is that it seems to pull all user records in my org, but really I just want to see those that are related to the Programming__c record where the button is clicked.

Is there a way to achieve this in my class?
 
public class User_List {
 
@AuraEnabled
   public static list <User_List__c> fetchList(){
      
      List <User_List__c> returnUserList = new List < User_List__c > ();
        
      for(User_List__c ul: [SELECT 	id, First_Name__c, Last_Name__c, Email__c, Extension_Number__c, Type_of_User_License__c, Phone_Model__c, Language__c, Outbound_Number_Display__c, Outbound_Name_Display__c, Voicemail_Option__c, CFNR_Number__c From User_List__c LIMIT 1000]) {
             returnUserList.add(ul);
          }
         return returnUserList;
   }
}

 
Hi,

I am trying to launch a flow from an aura component. In the flow, I have an apex variable of type "Apex-Defined Collection variable". How to set the value of this variable from the aura component? I have two other string variables in the flow, I am able to set them, but when I set the value in the apex defined var, the flow throws an error. Below is the relevant code from the aura component:
const flow = component.find("flowData");
const inputVariables = [
            {
            name: "varCaseId",
            type: "String",
            value: component.get("v.recordId")
        },
        {
            name: "varAccountNumber",
            type: "String",
            value: response.accountNumber
        },
        {
            name: "varIntents",
            type: "Intent",
            value: response.intents
        }
];
flow.startFlow(response.flowAPIName, inputVariables);
If I remove the third element from the inputVariables array, then the flow launches correctly, otherwise not.

 
I have a custom setting 'Licensename__c' where 'license__c' is the only field. I am using the below logic to access the data from it 

List<LicenseName__C> names = LicenseName__c.getall().values();
system.debug(names[0].License__c);
system.debug(names[1].License__c);
system.debug(names[2].License__c);
system.debug(names[3].License__c);

The debug statements are not giving the data in the order that i have entered in custom setting.

Is there any way to bring the data in the code in the same order i entered in custom setting!?

Also please let me know how to count the number of dataset in the custom setting.
Any help is appreciated.

Thank you!
Hi ,
I am getting issue in catch block due to retrun statement .Can anyone help me in thisUser-added image
Main Class

public with sharing class Common_DAO 
{
    //get the list of Table Component records
    public static List<Common_TableComponent__c> getTableComponentList(string recordName)
    {
        try
        {
            List<Common_TableComponent__c> tempList = new List<Common_TableComponent__c>();
            
            tempList = [SELECT ActionButtons__c,Advanced_Search_Criteria__c,Advanced_Search_Help_Text__c,
                        ColumnHeaderList__c,Columns_To_Sort__c,
                        Date_Filter_Values_New__c,DefaultView__c,Default_Filter_Column__c,Enable_Advanced_Search__c,Enable_Date_Filter__c,
                        Enable_Search__c,Enable_Sorting__c,Fields__c,IsActionColumnEnabled__c,Order_By_Clause__c,
                        Pagination_Type__c,SearchFields__c,Search_Help_Text__c,SOQLQuery__c,Where_Clause__c, Header_Default_Value__c,Header_Spanish_Value__c 
                        FROM Common_TableComponent__c WHERE Name = :recordName LIMIT 1];
            
            return tempList;
        }
        catch(exception e)
        {
            return null;
        }
    }
    
    //get the list of Table Search records
    public static List<Common_TableSearch__c> getTableSearchList(string recordName, string searchType)
    {
        try
        {
            List<Common_TableSearch__c> tempList = new List<Common_TableSearch__c>();
            
            tempList = [SELECT Name, Advanced_Search_SOQL_Query__c, Common_TableComponent__c,
                        Field_Type__c, Join_Column__c, Placeholder_Text__c, Possible_Values__c,
                        Search_Type__c,  Child_Column__c,Default_Filter_Column__c,Where__c,Order_By__c,Default_Filter_Value_SOQL__c,Default_Filter_Child_Column__c  
                        from Common_TableSearch__c 
                        where Common_TableComponent__r.Name = :recordName and Search_Type__c=: searchType order by Sequence_Number__c ];
            
            return tempList;
        }
        catch(exception e)
        {
            return null;
        }
    }
    
    //get the list of Table Search records
    public static List<Common_TableAction__c> getTableActionList(set<string> buttonsNameSet)
    {
        try
        {
            List<Common_TableAction__c> tempList = new List<Common_TableAction__c>();
            
            tempList = [SELECT Name,Action_Button_Display_Column_Values__c,
                        Action_Button_Display_Criteria_Column__c,
                        Action_Button_Ext_Display_Column_Values__c,
                        Action_Button_External_Display_Criteria__c,
                        APINameOfLink__c,Custom_Permissions__c,DynamicParams__c,
                        EnableAsLink__c,Is_Absolute_URL__c,IsActive__c,
                        Is_Remote_Action_Button__c,Enable_Pop_up__c,Self_Window__c,
                        Remote_Action_Class__c,Remote_Action_Method__c,Title__c,URL__c 
                        FROM Common_TableAction__c where Name IN : buttonsNameSet];
            
            return tempList;
        }
        catch(exception e)
        {
            return null;
        }
    }
}

Test class 
@IsTest
Public class Common_DAO_Test{
     @isTest  static testmethod void common_DAOTest1(){
     
        string recordName='';
        string searchType='';
        set<string> buttonsNameSet=new set<string> ();
        Common_DAO c=new Common_DAO();
        Common_DAO.getTableComponentList(recordName);
        Common_DAO.getTableSearchList(recordName,searchType);
        Common_DAO.getTableActionList(buttonsNameSet);
        system.assertequals(searchType,'');    
    }
    
    Public static testmethod void common_DAOTest2(){
        Common_DAO c=new Common_DAO();
        string recordName='test';
        string searchType='test';
        set<string> buttonsNameSet=new set<string> {'test'};
            
            
            try{
            
            Common_DAO.getTableComponentList(recordName);
           
            } catch(DMLException e) {
            
            system.assertEquals(e.getMessage(), e.getMessage()); 
            
            } 
            Common_DAO.getTableSearchList(recordName,searchType);
            Common_DAO.getTableActionList(buttonsNameSet);
        }
Hello,

I'm been trying to figure out how to get a list of all 167,000 accounts and put them in a csv and upload to S3 nightly. I'm running into multiple issues, mainly the size of the row return and uploading to S3 on a schedule. For the first part, i've been trying to use a Batchable class to bypass the 50,000 row limit, but Batchables don't allow @future calls, so I can't upload to S3. So then I tried using Queueable to bypass the @future problem, but I run into the 50,000 row limit. Is there a way to do this or am I stuck?
Hello,
I have an Apex class where I am parsing the selected values from a multiselect.
How can I add double quotes to each element?
I have big, small, medium.
I need "big","small","medium"

Any suggestion would be appreciated.
Cheers,
P
I am wanting to change the "assigned to" value in open (i.e. not closed) activities whenever the parent record owner changes. Our marketing automation system is automatically creating a bulk of tasks and assigning them to the current contact owner, but a few hours later a mass contact reassignment is happening and these tasks are not getting assigned to the new contact owner.

Desired functionality:
1. Contact Owner changes
2. Related open activities (tasks) are reassigned to new contact owner
-end-

Thanks in advance for your help.
I have written a schedule class to update the lead source to web if the lead source is null. I have written test class as well. But code coverage is 0% can anyone help me so that code coverage is 100%

Class 

global class LeadMaintanace implements Schedulable{
    global void execute(SchedulableContext SC) {
        List<Lead> li =[Select Id,Name from Lead where LeadSource = 'null' LIMIT 10];
        List<Lead> lu= new  List<Lead>();
        if(!li.isEmpty()){
            for(Lead ld:li){
                ld.LeadSource = 'Web';
                lu.add(ld);
            }
                }
        update lu;
    }

}

test class

@isTest
public class TestLeadMaintanace {
    @testsetup
    static void setup(){
        List<Lead> li = new List<Lead>();
        for(Integer i;i<10;i++){
            Lead ld = new Lead(Company = 'Proseraa',LastName ='MN',Status = 'Working - Contacted');
            li.add(ld);
            
            
        }
        update li;
        
    }
    static testmethod  void TestJobSchedule(){
        string sch = '0 30 12 2 20 ?';
        Test.startTest();
        string jobid=System.Schedule('SchedulableClass',sch, new LeadMaintanace());
        List<Lead> li =[Select Id from Lead where LeadSource=null limit 10];
        system.assertEquals(10,li.size());
        test.stopTest();
        
    }
    
    
}
Hi Forum Members,

I am trying to come up with a way to retrieve all Accounts within a hierarchy based on a supplied Id.  So, if the Id of the parent account is provided, all children records plus the parent record should be returned.  Similarly, if an Id of a child record is supplied, all parent, sibling, and children records should be returned.

User-added image

Any help in this regard is highly appreciated
  • February 11, 2020
  • Like
  • 0
Hello, everyone. 

I have a parent component, with a child component to simulate a multipicklist selection. I have to pass the list of selected values to the parent component, but it doesn't work. Does enyone know how to solve this? 

Child component:
<aura:attribute name="UFList" type="List" default="[]"/>
    <aura:attribute name="selectedUFList" type="List"  default="[]"/>
     
    <div class="slds-m-around_xx-small">
        <lightning:dualListbox aura:id="selectUF"
                               name="UF"
                               sourceLabel="Disponíveis"
                               selectedLabel="Selecionados"
                               options="{!v.UFList }"
                               value="{!v.selectedUFList}"
                               onchange="{!c.handleUFChange}"/>
        <lightning:button variant="brand" label="Salvar" onclick="{!c.getSelectedUF}" />
    </div>

Child controller:
getSelectedUF : function(component, event, helper){
        var selectedValues = component.get("v.selectedUFList");
        var componentEvent = component.getEvent("MultiPicklitsEvt");
            
            componentEvent.setParams({
                "UFVar" : component.get("v.selectedValues"),
            });
            
            componentEvent.fire();
        }


Event:
<aura:event type="COMPONENT"  >
    <aura:attribute name="UFVar" type="String"  />
</aura:event>

Parent component:
 <aura:handler name="MultiPicklitsEvt" event="c:MultiPicklitsEvt" action="{!c.handleMultiPicklitsEvt}"/>

Parent Controller:
handleMultiPicklitsEvt : function (component,event,helper) {
        
        var item = component.get("v.item");
        component.set("v.chosenUF", event.getParam("UFVar"));
        console.log(UFVar)
        
        item.UF__c = event.getParam("UFVar");
        log.console(chosenSP)
        
        component.set("v.item", item);     
    },
    
I have 5 Controllers which affect opportunities. Each has a test which provides > 90% code coverage in UAT. When I look in production, these tests provide 0% code coverage when the Controllers and related tests are identical between UAT and production. General question is what could cause these tests to fail given the success in UAT and the artifacts promote successfully to production?
Hi I'm new to Eainstein analytics. I would like to develop a lightning component which will take image url & show the image. So I created this component
<aura:component implements="flexipage:availableForAllPageTypes" access="global" controller="MyController" >
 <lightning:card title="Partner Information">
     <Div>
         <p><lightning:input aura:name="image" label ="Enter image url"  type="text"/></p>
	     <br></br> 
         <img url="{!v.image}" />
	
		
    
     </Div>
</lightning:card>
     
</aura:component>
My purpose is to display the image using the URL & predict the image using the url
But while running the component, I'm getting error message 
This page has an error. You might just need to refresh it.
Access Check Failed! AttributeSet.get(): attribute 'image' of component 'markup://c:EinsteinPrediction {3:0}' is not visible to 'markup://c:EinsteinPrediction {3:0}'.
Failing descriptor: {c:EinsteinPrediction}

Can you help me to resolve this issue?
I have a trigger on Contract Object, whenever the Contract record is updated the contract section in the associated opportunities will also get updated with the latest Contract data but while updating Contract record, Contract section in associated Opportunities is not updating instead I am getting validation errors which is created on Opportunity object.
Now I want to stop Opportunity validation rules when I update the contract section of Opportunity object from Contract trigger. Is there anything that we can pass from trigger to validation rules to stop validation rules errors?  Please help me.
 
Hi there,
I'm trying to return just the live Accounts through SOQL but when I attach status to the where clause it errors, is the Status column in the accounts table or do i need to join to another table? Whats the best way to find the whole schema?

Thank you

Dave.
 
Hello,
Lookin gto do an audit on the number of users assigned to all of the profiles in an org.  Is there a way to get the user count on each profile? Goal is to remove/consolidate profiles if possible.
Thanks
P