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

Wednesday, March 11, 2020

Record Is Not Createable Issue In LWC

Most of the times you will receive this error when your using the base lightning components in your application.

Recently I got the same error while I'm using the <lightning-record-form > base component in one of the LWC component.My use case is just to display the record details basis on the given record id and with set of specified fields.

RecDetails.html

<template>
<lightning-record-form 
        mode="readonly" 
        columns="2" 
        object-api-name="WebSite_Details__c" 
        record-id={recId} 
        fields={objFields} >
        </lightning-record-form>
</template>

RecDetails.js

import { LightningElement,api,track,wire } from 'lwc';
import Lan_FIELD from '@salesforce/schema/WebSite_Details__c.Language__c';
import Site_FIELD from '@salesforce/schema/WebSite_Details__c.Site__c';
import Site_FIELD from '@salesforce/schema/WebSite_Details__c.Company__c';

export default class CallPopup extends NavigationMixin(LightningElement){
    @track objFields = [Site_FIELD, Site_FIELD,Lan_FIELD];
    @track recId;
 
//Wired Method Which Returns Record id
   @wire(fetchWebDet)
    wiredfetchWebDet({ error, data }) 
    {
         
        if (data) 
            {
 this.recId = data; // Dynamically assigns the record from the response
   
     }
 }
}

When I'm executing the component I was getting the same error Record Is Not Createable.
Then I started debugging the user related profile details and I figured out the user is not having an access to create a new record.

Interesting Point To Be Noted Here Is:

But still I'm not trying to create any new record,just trying to display the record which is already exist but it's internally trying to create a new record but logged in user is not having a create access on the specified object so it's failing.

If you look at the code I'm fetching the record id dynamically from wired method and assigning to it recId which is record Id in my case.So,here what is happening is the <lightning-record-form > will display the record details in view mode in case if record-id value is available if not then it will try to create a new record.

When the component got rendered this recId is not available so it's trying to create a new record that is why it's causing issue.

Solution:

Simple if condition which checks the whether record id is available would solves this problem.So,please invoke <lightning-record-form > if and only if record id is available.If record id is not available don't invoke the <lightning-record-form > .This solves the issue.Please find the update code below.

<template>
 <template if:true={recId}> //This if check solves your problem
  <lightning-record-form 
   mode="readonly" 
   columns="2" 
   object-api-name="WebSite_Details__c" 
   record-id={recId} 
   fields={objFields} >
  </lightning-record-form>
 </template>
</template>



Please comment or write us if you have any queries/requirements.

Please like,follow,bookmark,subscribe this site to receive daily updates.




Hope this helps you..Enjoy..!




Saturday, December 28, 2019

Error: [LWC error]: Invalid event type "WireContextEvent" dispatched in element force-aloha-page

Usually when we are rendering any LWC component in Lightning experiences or Lightning console applications sometimes you will receive this error.

The complete looks like below in your browser console

aura_proddebug.js:4283 Error: [LWC error]: Invalid event type "WireContextEvent" dispatched in element <force-aloha-page>. Event name must 1) Start with a lowercase letter 2) Contain only lowercase letters, numbers, and underscores
<force-aloha-page>
    at Object.logError (aura_proddebug.js:4279)
    at AlohaPage.dispatchEvent (aura_proddebug.js:7633)
    at DomContextBinding.get (contextService.js:106)
    at findContextProvisions (contextService.js:296)
    at getContextProvisions (contextService.js:337)
    at Object.getContextValue (contextService.js:355)
    at getDelegate (pageService.js:7)
    at PageServiceClient.getCurrentPageReference (pageService.js:28)
    at AlohaPage.connectedCallback (alohaPage.js:688)
    at callHook (aura_proddebug.js:8345)
logError @ aura_proddebug.js:4283


According to Salesforce LWC Documentation the LWC components are not completely supported in all the environments,applications and display sections.

So,this error comes when your rendering any LWC component in any of the area where salesforce doesn't support these LWC components.

Solution:

To fix this error please place your LWC component in Aura component then the LWC component will work without any errors.

Notes:

  • This could also comes in the cases where your using any lightning interface or feature which will not support in classic environment then also this comes.
  • In those cases wrapping inside the aura also will not help us.



Hope this helps you..Enjoy..!

Invalid Reference lightning-navigation Of Type Module in file .js Issue in LWC

Usually you will receive this error when your trying to import the navigation package of Salesforce for navigation in LWC.

Error Code:

import { LightningElement,api,track,wire } from 'lwc';
import { NavigationMixin } from 'lightning-navigation';

export default class YourClassName extends NavigationMixin(LightningElement)
{
  // your code
}

If you try to save the class with above code you will receive same error.So,to fix this issue please replace lightning-navigation with lightning/navigation while importing.

Solution:


import { LightningElement,api,track,wire } from 'lwc';
import { NavigationMixin } from 'lightning/navigation';

export default class YourClassName extends NavigationMixin(LightningElement)
{
  // your code
}

Hope this helps you..Enjoy..!

Monday, December 16, 2019

System.JSONException: Apex Type unsupported in JSON: Object

You will receive this error when your parsing/deserialize  the JSON responses either user the JSON classes or JSON Parser classes.Please read the below points
  • When you deserialize the response into specified class type and if that class is having any field with data type "Object" you will receive this error.
  • When you any JSONToApex Converter or JSONToC# we will end up with this issue.
  • Please replace all the fields with Object data type into String/Integer etc..
Sample JSON:


{
  "item": [
    {
      "CONTRACT": 1001117406,
      "SOLD_TO": 10081120,
      "PURCH_NO_C":,
      "STREET": "1290 Hamner Ave",
      "STR_SUPPL1": "",
      "STR_SUPPL2":,     
    }
  ]
}

After Coverting JSONToApex:

public class Item
{
    public integer CONTRACT { get; set; }
    public integer SOLD_TO { get; set; }
    public object PURCH_NO_C { get; set; }
    public string STREET { get; set; }
    public string STR_SUPPL1 { get; set; }
    public object STR_SUPPL2 { get; set; }
}

public class RootObject
{
    public List<Item> item { get; set; }
}



Deserialize the JSON:

JSONParser parser = JSON.createParser('sampleJsonResponse');
 RootObject pr= (RootObject)parser.readValueAs(RootObject.class); 
//Here you will receive an error because the RootObject.class is having fields (PURCH_NO_C,STR_SUPPL2)  of type Object .

WorkAround:
Please change the wrapper class fields data type from Object to appropriate types as integer,double,string etc

public class Item
{
    public integer CONTRACT { get; set; }
    public integer SOLD_TO { get; set; }
    public string PURCH_NO_C { get; set; }
    public string STREET { get; set; }
    public string STR_SUPPL1 { get; set; }
    public string STR_SUPPL2 { get; set; }
}

public class RootObject
{
    public List<Item> item { get; set; }
}

Hope this helps you..Enjoy..!


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!