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

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....................!

Monday, January 4, 2016

System.QueryException: unexpected token: 'where'

Whenever you’re making any dynamic query construction in apex we will be ending with many errors .Among them one common error is System.QueryException: unexpected token: 'where' 

Code Snippet:
 String queryString = 'Select id,name,industry,';  
 queryString = queryString +'From Account';  
 System.debug('queryString ..'+queryString);  
 Database.query(queryString);  

When I run above code snippet I'm receiving System.QueryException: unexpected token: 'where' and then I checked my debug for the query it's something like as below

Debug value : Select id,name,industry, From Account

WorkAround 

 The extra comma in between Industry and From is causing the issue so if you remove that extra comma it will work perfectly.

Modified Code Snippet:
 String queryString = 'Select id,name,industry ';  
 queryString = queryString +'From Account';  
 System.debug('queryString ..'+queryString);  
 Database.query(queryString);  

So when ever your making dynamic quires please keep below points in mind

 1. Any extra commas are coming in queries
 2. Whether space is provided between last column and FROM statement
 3. Give space between From and Object Name

Got the solution....Enjoy..........!

Sunday, January 3, 2016

How to Restrict creation of Contact on Lead Conversion

Here I'm trying to avoid the creation of Contact on Lead conversion.Here the thing is that we can't stop the contact creation on lead conversion because it's standard process .So to achieve this we have an alternative solution is to delete the contact after the lead got converted.

To Delete I have a written a trigger on Lead like below

 trigger noContactOnLeadConversion on Lead (after update)   
 {  
  list<contact> conlead=new list<contact>();  
  for(lead leadRec:Trigger.new)  
  {  
   if(trigger.oldMap.get(leadRec.id)isconverted==false && leadRec.isconverted && leadRec.ConvertedContactId != null)  
   {  
       contact con= new contact(Id=leadRec.ConvertedContactId);  
       conlead.add(con);  
   }  
  }  
  delete conlead;  
 }  





















When I start converting the lead I'm ending up with an error System.DmlException: Delete failed. First exception on row 0 with id 0039000001pvmhtAAA; first error: ENTITY_IS_DELETED, entity is deleted: [] .





















Then I added the logic to stop recursion trigger and tried with before trigger also but still I'm getting the same error with different screen but error is same







WorkAround for the Error 

Move the deletion of contact part to the @future method(i.e.,Asynchronous execution )and use Boolean variable to stop Recursion trigger.Below is the modified code snippet.

Trigger code:
 trigger noContactOnLeadConversion on Lead (after update)   
 {  
 if(!LeadUpdateHandler.stopleadUpdateTrigger)  
 {  
  LeadUpdateHandler.stopleadUpdateTrigger= true;  
  list<contact> conlead=new list<contact>();  
  for(lead leadRec:Trigger.new)  
  {  
   if(trigger.oldMap.get(leadRec.id).isconverted==false && leadRec.isconverted && leadRec.ConvertedContactId != null)  
   {  
    contact con= new contact(Id=leadRec.ConvertedContactId);  
    conlead.add(con);  
   }  
  }  
  LeadUpdateHandler.AsyncExecution(JSON.serialize(conlead));  
  }  
 }  

Handler Class Code:
 global class LeadUpdateHandler  
 {  
   public static boolean stopleadUpdateTrigger = false;  
   @future  
   public static void AsyncExecution(String JsonStr)  
   {  
    List<Contact> conList = new List<Contact>();  
     conList = (List<Contact>)JSON.deserialize(JsonStr, List<Contact>.class);  
     delete conList;  
   }  
 }  

For more update please join this site or just like my Facebook page I Love Coding..You? 

Enjoy.....!

Thursday, December 24, 2015

Apex Exception Email Option Under Email Adminstartion

Whenever an exception occurs in Apex ,code execution halts.Any DML operation performed will be rollbacked and those changes will not be committed.Exceptions gets logged in debug logs.

Unhandled Exceptions:

   Exceptions that are not handled in code or exceptions that the code doesn't catch are called as Unhanded exceptions.When these type of errors are occurred in code,salesforce sends an email to Last modified by user specified in class or trigger and an end users sees an error in the Salesforce user interface.This email report includes apex stack trace and the customer’s org and user ID. No other customer data is returned with the report.

Apex Exception Email Option :

  By using this option all unhanded exception emails are sent to Last modified by user and In addition to that you can sent same email report to user of the your organisation and to arbitrary email addresses(outside salesforce).

Apex Exception Email Apex Exception Email :

1. Goto Setup-->Email Administration-->Apex Exception Email.





























2. Select Add User option or add External user mail address separated by comma,semicolun,space,\t,\n or \r




3. Search for the user in your org and select then save.




Unhandled Exceptions in the User Interface:

If an end user runs into an exception that occurred in Apex code while using the standard user interface, an error message appears. The error message includes text similar to the notification shown below .




















Notes :

1.If duplicate exceptions occur in Apex code that runs synchronously, subsequent exception emails are suppressed and only the first email is sent. This email suppression prevents flooding of the developer’s inbox with emails about the same error. For asynchronous Apex, including batch Apex and methods annotated with @future, emails for duplicate exceptions aren’t suppressed.

2.You can also configure Apex exception emails using the Tooling API object ApexEmailNotification.


Tuesday, December 22, 2015

System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_EXECUTE_FLOW_TRIGGER, The record couldn’t be saved because it failed to trigger a flow.

When I'm trying to execute a Test class I'm getting an System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_EXECUTE_FLOW_TRIGGER, The record couldn’t be saved because it failed to trigger a flow.Looking at this error message I can say it is related to Flows or Process Builder but the thing is that how we need to identify in which flow it causing an error.In this post now I'm going to explain how to produce this issue and what is work around solution for this issue.

How to Produce the Issue

I have created a flow on Opportunity object with the help of Process builder .The main theme of the flow is that it has to execute an action after 6 days of  Opportunity Stage Name as Closed Won along with 2 more conditions.


Flow Criteria

1. Opportunity StageName equal "Closed Won" AND
2. Opportunity Amount is Greater than $25,000.00 AND
3. Opportunity related Account filed Sid_Desc__c(field in Account) is equals "Test"

Process Builder Flow is successfully created and activated.Please find the below image for clear picture





Now I'm going to write a sample test class to create a new opportunity

 @isTest  
  public class TestOppInsertFlow  
  {  
   static testMethod void insertOpp()  
   {  
   Opportunity op = new Opportunity();  
   op.Name = 'TestOpp';  
   op.StageName = 'Closed Won';  
   op.Closedate = System.today()+1;  
    insert op;  
   }  
  }  
When I am executing the above test class it will fail by displaying an error System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_EXECUTE_FLOW_TRIGGER, The record couldn’t be saved because it failed to trigger a flow.

If you check in the debug logs you can clearly observe a flow error like The flow failed to access the value for myVariable_current.Account.SicDesc because it hasn't been set or assigned see below image.





Root Cause:


In flow we are referring the opportunity related Account filed value Sid_Desc__c but in our test class we are not passing any account value for the opportunity so it referring the Sid_Desc__c value in null account value.


Work Around Solution

1. By adding a null check for relation Ship fields in Process Builder(in our case AccountId)
 

 






































2. To pass the AccoutId value to the opportunity record in test class.See modified class below
 @isTest  
  public class TestOppInsertFlow  
  {  
   static testMethod void insertOpp()  
   {  
   Account acc = new Account();  
   acc.Name = 'tesst';  
   insert acc;  
   Opportunity op = new Opportunity();  
   op.Name = 'TestOpp';  
   op.StageName = 'Closed-Won';  
   op.Closedate = System.today()+1;  
   op.Accountid = acc.id;  
   insert op;  
   }  
  }  

3.If this issue is coming whenever your trying to perform deployment into Production and if you don't have time to fix this issue,best option is to deactivate it and perform deployment and activate it again

Note:
Whenever you encountered with this type of error you will be receiving an email from salesforce





















Enjoy....... Thanks for Visiting. Please follow us at FaceBook and twitter for more updates.

Tuesday, December 15, 2015

Illegal assignment from LIST<Account> to LIST<Account> at line in Apex Class

Whenever you have return Query on any object if it is returning more than one record then we will be using the List datatype to store that result .Here is the some interesting issue that I faced when I am assigning my results of type List<Account> to List<Account>

Public class AccountController
{
 List<Account> listAcc{get;set;}
 public AccountController()
 {
    listAcc = new List<Account>();
 listAcc = [Select id,name FROM Account ];
 }
}

When I am execute this class I am getting an error at line Query Illegal assignment from LIST<Account> to LIST<Account> at line in Salesforce Class.
Here I'm getting list of accounts from query and I am assigning that to List<Account> listAcc only but why still I getting this error.I searched for it so many places finally I got the solution(Thanks for the Jitendra who provided me the solution).

WorkAround:
In my organization somewhere I have created a class named "Account". That is why the compiler is not able to understand that it is standard Object Account or the class created in my org.Now I renamed my class to some other name now it's working perfectly.

Thursday, December 10, 2015

System.LimitException: DML currently not allowed

Whenever we trying to perform any DML operations at the time of initial page load we will be ending up with an error called System.LimitException: DML currently not allowed. In this post I am going to show how to produce the issue with simple example and workaround for the same issue.

1.Create simple page and class as shown below

VF Page Name : DeleteAllConts
 <apex:page controller="DeleteAllContCtrl">  
 </apex:page>  

Controller
1:  public class DeleteAllContCtrl  
2:  {  
3:   public DeleteAllContCtrl()  
4:   {  
5:    Id AccId = Apexpages.CurrentPage().getParameters().get('id');    
6:    Delete ([SELECT id FROM Contact WHERE AccountID=:AccId]);  
7:   }  
8:  }  

Now create a simple page with hyperlink and run it by passing any AccountID
1:  <apex:page standardController="Account">  
2:        <apex:outputLink value="/apex/DeleteAllConts?id={!Account.id}"> Delete All Contacts</apex:outputLink>   
3:  </apex:page>  

When user clicks on link it will be calling the DeleteAllConts page by passing the current AccountID as parameter.Once the execution starts at the controller it will be throwing an error System.LimitException: DML currently not allowed at delete statement(line number 6) in DeleteAllContCtrl class.

Reason for the Error:
1.When you are trying invoke any controller from visual force page to perform any dml operations (insert/delete/update/upsert) inside the constructor or any method called from constructor it will not allowed.
2.Within a single transaction - Web Service callouts just after the DML operation.(Thanks for Girish for providing this point)

Workaround for solutions 

1. Move the dml statements out of the constructor
2.Create a method place that dml operations inside that method and invoke that method directly from page using the action attribute in <apex:page> tag

Modified DeleteAllConts Page and Controller

 <apex:page controller="DeleteAllContCtrl" action="{!delContacts}">  
 </apex:page>  

1:  public class DeleteAllContCtrl  
2:  {  
3:   public DeleteAllContCtrl()  
4:   {  
5:    System.debug('Eneterd Inside Contsructor');  
6:   }  
7:   public void delContacts()  
8:   {  
9:    Id AccId = Apexpages.CurrentPage().getParameters().get('id');    
10:    Delete ([SELECT id FROM Contact WHERE AccountID=:AccId]);  
11:   }  
12:  }  

Thanks for visiting....Enjoy.....