Showing posts with label Errors. Show all posts
Showing posts with label Errors. Show all posts

Thursday, December 5, 2019

System.LimitException: Too many DML statements: 1

Exception:

If you use below code it will throw an error System.LimitException: Too many DML statements: 1 if you have any dml statement in your aura-method.






public with sharing class GetAllAccountsCntrl {
   @AuraEnabled(cacheable=true)
    public static List<Account> processAllAccounts() 
 {
        List<Account> lstAcc = new List<Account>();
  for(Account acc:[SELECT Id, Name,AccountSource,Website, Createddate FROM Account Limit 10])
  {
      acc.Name = 'LWC Testing...';
   lstAcc.add(acc);
  }
  Database.update(lstAcc,false);
  return lstAcc;
    }

}

Workaround:

Please remove (cacheable=true) from your method declared above,then this will work without any error



public with sharing class GetAllAccountsCntrl {
   @AuraEnabled
    public static List<Account> processAllAccounts() 
 {
        List<Account> lstAcc = new List<Account>();
  for(Account acc:[SELECT Id, Name,AccountSource,Website, Createddate FROM Account Limit 10])
  {
      acc.Name = 'LWC Testing...';
   lstAcc.add(acc);
  }
  Database.update(lstAcc,false);
  return lstAcc;
    }

}


Hope this helps you..Enjoy..!

How To Throw An Exception From Apex (Server Side) To JavaScript(Client Side) Controller in LWC

In lightning if you want to throw something as error from Apex class to client side Js controller ,we can use the salesforce standard class AuraHandledException.

Please look at the below code snippet where I'm trying to call an api to get the weather information,basis on the api response you can throw an exception(received in valid status,received process status but didn't got the expected response etc..) wherever you want throw an exception to the client side controller.

If your using try and catch in your code and if you raise an exception in try it will automatically goes to catch block and from there it will return to client side controller.


global class WeatherReportCntrl
{

@AuraEnabled(cacheable=true)
public static string fetchWeatherReport()
{
   Http http = new Http();
   HttpResponse res = new HttpResponse();
   HttpRequest req = new HttpRequest();
   req.setEndpoint('endpoint');
   req.setMethod('GET');
   try
    {
 res = http.send(req);                      
 string responseValue =res.getBody();
 if(res.getStatus()=='OK' && res.getStatusCode()==200 && String.isNotBlank(responseValue)
 {
    //while processing some error came then
    System.debug('responseValue--->'+responseValue);
    if(someerror)
     throw new AuraHandledException('Error while Processing data');  

   return 'data processed successfully';
 }
 else
       {
 // Received some invalid status code
  throw new AuraHandledException('Received some invalid status');
 
 }
    }
   Catch(Exception e)
   {
       AuraHandledException ex = new AuraHandledException(String.valueOf(e));
       ex.setMessage('Exception caught in catch block');
       throw ex;
   }
 } 
}


Hope this helps you..Enjoy..!

Wednesday, December 4, 2019

Issue With Lightning-Button Click Action (Outside the button) In LWC

Issue:

If your using <lightning-button> in your component and this button is invoking the action even if you clicked outside of the button(it means the horizontally anywhere on the screen).

Route Cause:

This is because by default if your not setting any width to the button it will considers the entire width as the scope of the button.So,if you click anywhere on the screen horizontally to this,it will invokes the action automatically.

If you look at the below image the blue line has occupied entire width of the screen ,it means the scope of the button is spread like blue line.So,if you click anywhere it's get invoked automatically.



Sample button code:


 <template if:true={showIsCheck} class="slds-is-relative">
     <lightning-button label="Check ?" title="Check" 
          variant="success" onclick={checkIsCan} 
          class="slds-align_absolute-center slds-m-top_medium ">
     </lightning-button>
    
        <div if:true={isLoading}>
            <lightning-spinner alternative-text="Loading..." variant="brand" size="large" class="slds-is-absolute"></lightning-spinner>
        </div>
 </template>

Workaround:

Please set the width of the button so that the scope of the button will automatically bounds within the button.If you look at the below code snippets and image you can clearly undertsraynd that as soon as I sets the width the blue line is becoming small(Scope of the button).


 <template if:true={showIsCheck} class="slds-is-relative">
        <lightning-button label="Check ?" title="Check" 
            variant="success" onclick={checkIsCan} 
          class="slds-align_absolute-center slds-m-top_medium slds-size_medium"></lightning-button>
    
        <div if:true={isLoading}>
            <lightning-spinner alternative-text="Loading..." variant="brand" size="large" class="slds-is-absolute"></lightning-spinner>
        </div>
 </template>


a)when size as small

b)when size as medium


Thanks for visiting..hope this helps you!

Tuesday, July 12, 2016

System.QueryException: List has no rows for assignment to SObject

Usually we will come across this type issue in many places and in many situations also .In the same way I have come across the same issue in one of the my class and I have done some work around it to fix this issue.I will explain this one with an example which may brings you an complete understanding about the issue.

Scenario:
I have 3 objects called Time_Track__c,Expert__c and User.Expert__c and User having a lookup relationship where User (Sforce_User__c) is acting as parent for Expert object and Time_Track__c and Expert__c also having lookup relationship where Time_Track__c is acting as child for Expert (Expert_Name__c) object .I have an visual force page which is using Time_Track__c  as a Standard Controller and I am having some extension class on same page .In the constructor of the extension class I am trying to query on Expert__c object based on logged in user to assign this expert to new time track as shown below

Source Code:
public class TrackExtn {
  public Time_Track__c timeTrack{get;set;} 

  public TrackExtn(ApexPages.StandardController controller) {
    timeTrack = new Time_Track__c();        
    timeTrack= (Time_Track__c)controller.getRecord();
       
    if(controller.getId()==null)
    {
       Expert__c exp = new Expert__c();
       //In below line you will receive List has no rows for assignment to SObject
       exp = [Select id from Expert__c where Sforce_User__c=:UserInfo.getUserId() limit 1];
       timeTrack.Expert_Name__c = exp!=null?exp.id:null;
           
    }

    }
}

Error:

When you execute the above code at run time if your having at least one matching Expert__c record for logged in user it will work very smoothly .If there is no matching Expert__c record for logged in user will end up with System.QueryException: List has no rows for assignment to SObject . Even if the matching record is not there it should continue fir the next lines with out throwing any error but here it's failing and terminating the complete execution. To handle this we need to follow below work around solution.


Workaround Solution:

We need to convert the Query result holder from SObject type to List<SObject> type that will resolve the issue .Please look at the below code for the work around solution

public class TrackExtn {
  public Time_Track__c timeTrack{get;set;} 

  public TrackExtn(ApexPages.StandardController controller) {
    timeTrack = new Time_Track__c();        
    timeTrack= (Time_Track__c)controller.getRecord();
      
    if(controller.getId()==null)
    {
        //Convert Sobject type to List<Sobject> type to store query result
        List<Expert__c> listexp =new List<Expert__c>();
        listexp = [Select id from Expert__c where Sforce_User__c =:UserInfo.getUserId() limit 1];
        System.debug('loggedinTech ..'+listexp );
        td.Technician__c = listexp.isEmpty()?null:listexp[0].id;
           
    }

    }
}

Thanks for visiting...Enjoy!

Monday, July 11, 2016

System.QueryException: Only variable references are allowed in dynamic SOQL/SOSL.

Error:

Whenever your working with Dynamic SOQL construction you should be very careful regarding the Single Quotes(',') or Open/Close parentheses'(' ')'  and bind variables(':') in query string.If your also getting the same error as mentioned above please refer below code.

Source Code:

public void fetchOrders()
{
List<Order__c> listOrders = new List<Order__c>();
String selWOStatus ='Test'  // Usually value for this comes from visual force page

String q ='SELECT Id, Name, Location__c,End_Date__c,Createddate FROM Order__c where 
           Location__r.OwnerId=:'+UserInfo.getUserId();
                        
if('All'.equalsIgnoreCase(selWOStatus))
  q + = ' AND (Createddate =LAST_N_MONTHS:6 OR End_Date__c < NEXT_N_MONTHS:6) LIMIT 1000'; 

else
  q + =' AND (Status =\''+String.escapeSingleQuotes(selWOStatus)+'\' 
         AND Createddate = LAST_N_MONTHS:6) LIMIT 1000';

System.debug('q....'+q); 

listOrders  = Database.query(q);

System.debug('listTSOOrders....'+listOrders);

}

When you run this above code at run time you will end up with System.QueryException: Only variable references are allowed in dynamic SOQL/SOSL .This is due to the (':') bind variable usage in dynamic query construction which will cause the error and that causes missing a single quote for logged in user ID as shown query string coming at run time as shown below

Actual Query String at Run time:

'SELECT Id, Name, Location__c,End_Date__c,Createddate 
FROM Order__c 
where Location__r.OwnerId=:00560000004LFQkAAO 
AND (Status ='Test' AND Createddate = LAST_N_MONTHS:6) LIMIT 1000';

Excepted Query String at Run time:


'SELECT Id, Name, Location__c,End_Date__c,Createddate 
FROM Order__c 
where Location__r.OwnerId='00560000004LFQkAAO'
AND (Status ='Test' AND Createddate = LAST_N_MONTHS:6) LIMIT 1000';


Work Around Solution
Remove bind variable from query string and add single quotes before and after the user id

public void fetchOrders()
{
List<Order__c> listOrders = new List<Order__c>();
String selWOStatus ='Test'  // Usually value for this comes from visual force page

String qry ='SELECT Id, Name, Location__c,End_Date__c,Createddate FROM Order__c where 
           Location__r.OwnerId=\''+UserInfo.getUserId()+'\'';
                        
if('All'.equalsIgnoreCase(selWOStatus))
  qry + = ' AND (Createddate =LAST_N_MONTHS:6 OR End_Date__c < NEXT_N_MONTHS:6) LIMIT 1000'; 

else
  qry + =' AND (Status =\''+String.escapeSingleQuotes(selWOStatus)+'\' 
         AND Createddate = LAST_N_MONTHS:6) LIMIT 1000';

System.debug('qry....'+qry); 

listOrders  = Database.query(qry);

System.debug('listTSOOrders....'+listOrders);

}


Thanks for visiting...Enjoy!

Friday, July 8, 2016

System.StringException: Invalid id Error in Salesforce

Usually this kind of error we will be receiving in test classes.This is due to when your working with any kind of relationship fields in objects.Let me explain with an example below

Error:

We have a two objects called Order__c and Time__c and these two objects are having a lookup relationship where Order__c is Child and Time__c is a parent.Now i have to create a test record for Time__c along with Order__c and then I want to update Time__c record Order__c with null value.
@isTest 
private class TestTimeEntry {
    static testMethod void validateTime() {
        Order__c ord = new Order__c();
        ord.Name ='Test Order';
        insert ord;
        
        Time__c tm1 = new Time__c();
        tm1.Order__c = ord.id;
        tm1.name = 'test time';
        insert tm1;
        
        Time__c tm2 =[Select id,name,Order__c from Time__c where id=:tm1.id];
        tm2.Order__c =''; //At runtime we will receive Error here
        update tm2;
    }
}

Root Cause:

So when you run this test class you will receive a runtime error called System.StringException: Invalid id  at an update statement due to assigning an empty string(empty space) to Order__c.Usually all relationship fields will accepts Ids or null key word. 

Work Around Solution
So when your trying to assign an empty value for relationship field we have to specify null keyword instead of an empty space('')
@isTest 
private class TestTimeEntry {
    static testMethod void validateTime() {
        Order__c ord = new Order__c();
        ord.Name ='Test Order';
        insert ord;
        
        Time__c tm1 = new Time__c();
        tm1.Order__c = ord.id;
        tm1.name = 'test time';
        insert tm1;
        
        Time__c tm2 =[Select id,name,Order__c from Time__c where id=:tm1.id];
        tm2.Order__c =null; //An empty space replaced with null keyword
        update tm2;
    }
}



Thanks for visiting...Enjoy!


Friday, July 1, 2016

Stronger Security is Required Issue when logging into Sandbox

Issue:

Stronger Security is Required Issue when logging into Sandbox


When you try to login into sandbox from June 25 ,2016 on wards and if you end of  with an error called Stronger security is required, don't worry please read the below instructions to resolve it


Root Causes

This is due to the below reasons

  • As per the salesforce notifications they will stop supporting TLS 1.0 and automatically all sandboxes will be upgraded to TLS 1.1 from June 25,2016 .
  • All the production orgs will be upgraded to TLS 1.1 from March 4,2017.
  • So when your trying to login into sandbox from the browsers that will not support this TLS 1.1 will end up with this error and you will not be able to proceed further

WorkAround 

We need to make sure that the browser that your using will support TLS 1.1 and higher, if not you need to update the browser version or manually we need to enable TLS 1.1  to support it.

Action Required for Browser Compatibility
  • Google Chrome - Chrome 38 and Higher will support TLS 1.1 by default
  • Mozilla Firefox - FireFox 27 and Higher will support TLS 1.1 by default
  • IE  - Desktop and mobile IE version 11 will support TLS 1.1 by default
For more information refer salesforce notes at below links
Thanks for visiting...Enjoy!

Wednesday, June 22, 2016

Method only allowed during testing" Error in Test Classes

Issue:

Lets take an example where you have a test class which contains Test.startTest() and Test.stopTest() methods and you have more than one test method in test class.When you run this test class in any way it touches any class that implements the Queueable interface your test classes methods more than one will fails

WorkAround:

Split all your test class methods into individual test class in salesforce. For more information please refer salesforce known issues page 


Thanks for visiting...Enjoy!

Issue with action support function on select of select list values

Today we had an issue with selection of pick-list. I am just trying to invoke a controller method when a user selects a pick list value from drop down and we are using an <apex:actionSupport> to make a call to the controller and the event is onchnage on onselect but unfortunately we are not able to make a call to controller method and the actionsupport with onselect or onchange in not working along with rerender also.



After a multiple hours of surfing over the internet we got some suggestion that just replace the onselect or onchnage with onclick event then it is started working and then after again reverted back to onselect or onchange now I'm able to make a call to controller method .I am not sure why is it working like that.

If you people are also facing the same issue just replace the your event onselect or onchange with onclick and try to invoke a controller method and if it's able to make a call to controller then again revert the onclick with onselect or onchange.

Thanks for visiting....Enjoy!



INVALID_FIELD_FOR_INSERT_UPDATE, Account: bad field names on insert/update call: Name: [Name]

When your working with Person Accounts in Salesforce we should be very careful because these Accounts can also acts as a Contact .It means these person accounts will share many fields with contacts.

The Person Account name will contains First Name and Last Name .When your trying to load any Person Accounts with data loader or with any other apex code we should follow some naming conventions .If your trying to map these field values to Name field of Account we will end up with the same error.

So when your loading the Person Accounts data your .csv file must contain a columns FirstName and LastName but not only the Name.

For more information visit Salesforce Document here 

Thanks for visiting....Enjoy!




Monday, June 20, 2016

FIELD_INTEGRITY_EXCEPTION, Related To ID: id value of incorrect type: [WhatId]:

We have a trigger on some custom object and it would sent an email notification based on few changes to record.When we are sending an email with help of Messaging.SingleEmailMessage class and we are also using an email template so to populate the merge fields in template we are setting the whatId to custom object which full fills the merge fields in template but unfortunately we are end up with an below error



Error: Invalid Data. 
Review all error messages below to correct your data.
Apex trigger SummaryTrigger caused an unexpected exception, contact your administrator: SummaryTrigger: execution of AfterInsert caused by: System.EmailException: SendEmail failed. First exception on row 0; first error: FIELD_INTEGRITY_EXCEPTION, Related To ID: id value of incorrect type: a0JJ000000A6TDWMA3: [WhatId]: Class.SummaryTrigHandler.sendEmailNotification: line 101, column 1

Root Cause:
Even after I am setting the correct WhatId I am getting the same error .This issue is not related to object WhatId it's actually related to Activity record whatId.
Because by default the setSaveAsActivity has a value true, which saves the emailing as an activity so If your WhatId custom object not allowed for activity tracking then you will receive this error.

Solution:

  • So if your facing the same issue please goto object detail page (i.e.,the object that your setting as part of whatId) and enable the activities for the object
  • Change in your code like do not save the activity by setting the setSaveAsActivity as false Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();  email.setSaveAsActivity(false)



Thanks for visiting....Enjoy!

Tuesday, April 19, 2016

First error: NO_APPLICABLE_PROCESS, No applicable approval process was found

When your trying to make any kind of deployment on Production by default all the test classes will be run .To make smother deployment we need to have at least 75% code coverage .Recently when I'm making deployment to production I end up with the below error.

Deployment /Test Class Error:

System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, ORequestTrigger: execution of AfterInsert caused by: System.DmlException: Process failed. First exception on row 0; first error: NO_APPLICABLE_PROCESS, No applicable approval process was found.: [] Trigger.ORequestTrigger: line 81, column 1: []

Reason for the Issue:

If you running any Test class that in turn causes a Main class or Trigger to submit the Test record for an Approval Process (through Apex coding) and If that particular record is failing to meet at least one of the Approval Processes Entry Criteria then it will fail with above error.

Work Around Solution:

Modify the test record data as per the entry criteria of any one of required Approval Process.


Thanks for visiting...Enjoy


Thursday, February 4, 2016

myRule_4_A3 (Action Call) - We can't find an action with the name and action type that you specified

This type error will occurs whenever your performing any deployment activities.This error mainly related to the Process Builder processes or Any Flows that are the part of the deployment package. 

The sample error message looks like below.

Update Oppty-17 Flow Version 0 0 myRule_4_A3 (Action Call) - We can't find an action with the name and action type that you specified.

This error message says that action (Email alert,Field update,task etc) related to this Process Update Oppty-17   is missing as part of the deployment package or not in the targeting instance.

Work Around :

1. Please include that action as part of the deployment package
                                               (or)
2.Make sure that action is available in target instance before your making a deployment

Enjoy....!!

How to Delete the Records Permanently from the Recycle Bin in Salesforce

Basically in salesforce when you have deleted any record from an object, it will not be deleted permanently and it will be stored in Recycle bin till 15 days from the deletion date.The number of records stored in recycle bin depends on Number of Licenses your organisation has pursed and multiply it with 5000 records.
If the number of records in recycle bin crosses this limit salesforce automatically deletes the old records from Recycle Bin which are at least in recycle bin for 2 hours.If you want to delete the records permanently from recycle bin before salesforce deletes it you can emptyRecylebin() method.


     EmptyRecycleBinResult[] = DataBase.emptyRecyclebin(List of Ids)

Example:

    1. Account Acc = new Account(Id='0016000000I549m');
        Database.emptyRecycleBin(Acc);


Notes:

1. Maximum number of records per call that we can pass is 200
2. Using this function records deleted can not be undeleted again.
3. Theses deleted records from recycle bin can be accessed using the DataBase.queryAll() for some time typically that would be with in 24 hours or may shorter or longer.

Monday, January 25, 2016

Compile Error: Incompatible key type Datetime for Map<String,List<Event>> at line

You will receive this type of error commonly when your working with collections or while doing at variable assignments .This error basically comes whenever your passing incorrect key datatype to maps.

1:  List<Event> eventRec= [Select StartDateTime,EndDateTime from Event limit 10];  
2:  Map<String,List<Event>> mapEvents = new Map<String,List<Event>>();  
3:  mapEvents.put( eventRec[1].StartDateTime,eventRec);  

In the above code snippet you will an error like Compile Error: Incompatible key type Datetime for Map&lt;String,List&lt;Event&gt;&gt; at line 3 column 1 because the mapEvents map key datatype is String but we are passing Datetime (eventRec.StartDateTime) type parameter. 

Wok Around Solution
Pass the correct key value datatype based on your map declaration.In our we need to pass so modified code as below
1:  List<Event> eventRec= [Select StartDateTime,EndDateTime from Event limit 10];  
2:  Map<String,List<Event>> mapEvents = new Map<String,List<Event>>();  
3:  mapEvents.put( String.valueOf(eventRec[1].StartDateTime),eventRec);  

Enjoy..........!!

Tuesday, January 19, 2016

Error: entity is not org-accessible?

Basically we will be getting this error because of the many reasons among them here I'm listing few scenarios where we will be getting this one.

1. While deployment if your getting this means some features are enabled in source org and same has not been enabled in target org.
 
    Example: Enabled the Territories in Source Org and not in Target Org
    Solution : Enable Territories in Target Org also

2. While saving any Apex class/Trigger if your getting means you are using some feature which is not enabled currently in your org.

    Example : If your using OpportunityTeamMember object in Opportunity Trigger but in your organisation you haven't enabled the Opportunity Teams you will be receiving same error.
    Solution  : Enable Opportunity Team feature in your org first.

3. Any Spelling mistakes in API Names also causes same.

Enjoy.......!


Monday, January 18, 2016

Settings and Uploading Custom metadata Records with Custom Metadata Loader in Salesforce

In my previous posts I have explained what is Custom MetaData Loader .Now I'm going to explain how to set up this tool/application in salesforce.

1. Download the Complete application Zip file from the git hub Source.

2. Deploy the Downloaded Zip file into your org using below tools
3. Once you have deployed the zip file successfully it will creates below components
  • 10 Apex Classes
  • 2  Apex Page
  • 1  Custom Application
  • 1  Custom meta data type
  • 1  Custom tab
  • 1  Permission Set
    For complete package.xml file you can refer here

4. Goto Setup-->Permission Sets-->Click on Custom Metadata loader-->Manage Assignments

5. Click on Add Assignments -->Add the users to whom you want to give access for this App.

6. Goto Application menu Select Custom Metadata Loader application.

7. Clicking on Custom Metadata Loader you will be receiving below error.




















8.To resolve that error we need to create a one Remote Site Setting. On clicking on the below Create Remote Site Setting button it will automatically creates a remote site setting directly.























9. Even after clicking the button your not able to create or if your getting error like Cannot create a new component with the namespace: srinu_dev_ed. Only components in the same namespace as the organization can be created through the API it means in your org you have enabled/created some custom domain.

10.To fix this issue copy the complete page url where your receiving this error and goto Remote Site setting and give below details and save it.

 Remote Site Name : c_mdapi
 Remote Site URL         : Copied page URL
 Active                       : Checked

11. Now everything is finished on clicking on the Custom metadata loader you will receive the below screen.So you can start uploading the .csv file to insert the records.




























Note:
The .csv file header names must be the Api names of the Custom meta data type for auto mapping the fields.

Enjoy with Custom Metadata Loader....................!