+ Start a Discussion
Nashle PakNashle Pak 
Hello Ohana,
I use Lightning Out to integrate my LWCs on external sites.

My LWC displays contact records and works perfectly on my Salesforce app homepage.
User-added image

On an external site, my LWC is displayed but not the records.
User-added image
The code of the LWC and my application is available at this address:https://github.com/Nashle/lightningout/
The live is available at this address:https://nashle.github.io/lightningout/

Do I need to create an application connected with OAuth to allow GestUsers to access the application's data? And if so, how should it be configured to allow my LWC to display the data when it is hosted on a remote site?

Can you help me please ?
Best Answer chosen by Nashle Pak
Nayana KNayana K
UI API responses respect CRUD access, field-level security settings, and sharing settings(like "with sharing" mode). 
 Make sure you have proper OWD/ records shared with community guest user along with CRUD and field-level security. 
Peter CowenPeter Cowen 
I have created a class that links a case with the case comment for a visualforce page but for the life of me I cannot remember how I write a test class for the apex class.

The class I require tests for is:

public class Caselinktocomment
{
    public CaseComment comment { get; set; }
    public String commentText {get; set;}
    public String PublicPrivateAction {get; set;}


    public Caselinktocomment(ApexPages.StandardController stdController) 
    {
        this.comment = new CaseComment(ParentId = stdController.getId());
    }

    public PageReference saveComment()
    {
        insert comment;
        return null;
    }
}

The test Class I have written is:
@istest

Private class Caselinktocommenttests {
    

    static testmethod void createtestdata() {
    Id RecordId = Schema.SObjectType.Case.getRecordTypeInfosByDeveloperName().get('Service_Desk').getRecordTypeId();
        Case tcase = new Case();
        tCase.Status = 'New';
        tCase.Description = 'This ticket has been created as a test';
        tCase.Subject = 'Test Case';
        tCase.RecordTypeId = RecordId;
        tCase.Reason = 'Access Requests';
        tCase.Origin = '';Phone
        
        INSERT tCase;
        
        CaseComment tComment = new CaseComment();
        tComment.ParentId = tCase.Id;
        tComment.CommentBody = 'Test Comment';
        tComment.IsPublished = FALSE;
        tComment.IsNotificationSelected= FALSE;
        Test.startTest();
        INSERT tComment;
        Test.stopTest();
        system.assertEquals(1, [SELECT count() From CaseComment], 'Test Comment');
        }   
}

The code coverage does not seem to increase. Can anyone advise where I have gone wrong. 
Best Answer chosen by Peter Cowen
Foram Rana RForam Rana R
Hi Peter,

I hope you are doing well .....!!
Please use the below code:
@istest

Private class Caselinktocommenttests {
    

    static testmethod void createtestdata() {
        case obj = new case();
        obj.Status = 'New';
        obj.Description = 'This ticket has been created as a test';
        obj.Subject = 'Test Case';
        insert obj;
        
        CaseComment   tComment = new CaseComment();
        tComment.ParentId = obj.Id;
        tComment.CommentBody = 'Some Comment';
        tComment.IsPublished = TRUE;
        
        INSERT tComment;
        
        ApexPages.StandardController sc = new ApexPages.StandardController(obj);
        Caselinktocomment objCaseComment = new Caselinktocomment(sc);
        objCaseComment.commentText = 'Test';
        objCaseComment.PublicPrivateAction = 'Test';
        objCaseComment.saveComment();
        
    }
}

Hope this helps you.
If this helps kindly mark it as solved so that it may help others in the future.

Thanks & Regards,
Foram Rana
parth sachi 7parth sachi 7 
Even i changes name field ,update trigger is getting called and adding un-neccessary discount to price.Expected is that it should update only if brand is getting change.How can i remove this ?


trigger MobileShopeeDiscount on Mobile__c (before insert,before Update) {
    if(trigger.isInsert == true ){
        MobileShopeeDiscount.MobileShopeeDiscountFuncation(Trigger.new);
    }
       if(trigger.isUpdate == true){
       MobileShopeeDiscount.OldCustomerDiscountFuncation(Trigger.new);
    }

}

public class MobileShopeeDiscount {

    public static void MobileShopeeDiscountFuncation(list<mobile__c>VarList){
        for(mobile__c tempvar :VarList){
            if(tempvar.Brand__c == 'samsung'){
                tempvar.Price__c = tempvar.Price__c-(tempvar.Price__c *0.1);
                tempvar.DiscountStatus__c = 'Congrates !! You got 10% Discount';
            }else if(tempvar.Brand__c == 'Apple'){
                tempvar.Price__c = tempvar.Price__c-(tempvar.Price__c *0.2);
                tempvar.DiscountStatus__c = 'Congrates !! You got 20% Discount';
            }
        }
    }

public static void OldCustomerDiscountFuncation(list<mobile__c>VarList1){
        for(Mobile__c tempvar :VarList1 ){
            if(tempvar.Brand__c == 'samsung'){
                tempvar.Price__c = tempvar.Price__c-(tempvar.Price__c *0.05);
                tempvar.DiscountStatus__c = 'Congrates !! You got 5% Discount';
            }else if(tempvar.Brand__c == 'Apple'){
               // tempvar.Price__c = tempvar.Price__c-(tempvar.Price__c *0.2);
                tempvar.DiscountStatus__c = 'No Discount Applicable on this purchase';
            }
        }
        
    }


}
Best Answer chosen by parth sachi 7
Maharajan CMaharajan C
Hi,

Use the Trigger.OldMap to Compare the old value and new value.

Please find the bewlo update code:

trigger MobileShopeeDiscount on Mobile__c (before insert,before Update) {
    if(trigger.isInsert == true ){
        MobileShopeeDiscount.MobileShopeeDiscountFuncation(Trigger.new);
    }
       if(trigger.isUpdate == true){
       MobileShopeeDiscount.OldCustomerDiscountFuncation(Trigger.new,Trigger.OldMap);
    }

}


public class MobileShopeeDiscount {

    public static void MobileShopeeDiscountFuncation(list<mobile__c>VarList){
        for(mobile__c tempvar :VarList){
            if(tempvar.Brand__c == 'samsung'){
                tempvar.Price__c = tempvar.Price__c-(tempvar.Price__c *0.1);
                tempvar.DiscountStatus__c = 'Congrates !! You got 10% Discount';
            }else if(tempvar.Brand__c == 'Apple'){
                tempvar.Price__c = tempvar.Price__c-(tempvar.Price__c *0.2);
                tempvar.DiscountStatus__c = 'Congrates !! You got 20% Discount';
            }
        }
    }

public static void OldCustomerDiscountFuncation(list<mobile__c>VarList1, Map<Id,mobile__c> oldRecMap){
        for(Mobile__c tempvar :VarList1 ){
            Mobile__c oldRec = oldRecMap.get(tempvar.Id);
            if(tempvar.Brand__c == 'samsung' && oldRec.Brand__c != tempvar.Brand__c){

                tempvar.Price__c = tempvar.Price__c-(tempvar.Price__c *0.05);
                tempvar.DiscountStatus__c = 'Congrates !! You got 5% Discount';
            }else if(tempvar.Brand__c == 'Apple'&& oldRec.Brand__c != tempvar.Brand__c){
               // tempvar.Price__c = tempvar.Price__c-(tempvar.Price__c *0.2);
                tempvar.DiscountStatus__c = 'No Discount Applicable on this purchase';
            }
        }
        
    }
}


Thanks,
Maharajan.C
Spencer BerkSpencer Berk 
This component redirects a community user to the user's Account Detail page in a community. How would I change the code to redirect to a custom object (Billing__c) Detail page? I've tried changing the recordId path to LoggedInUser.Contact.AccountId.Billing__c with no luck. My path might be wrong. I am not a developer so any advice would be greatly appreciated.
({
    redirectToAccount: function(component, event, helper) {
        var loggedInUser;
        var state;
        var navEvt;
        
        var action = component.get("c.getLoggedInUser");
        action.setCallback(this, function(response) {
            state = response.getState();
            if (state === "SUCCESS") {
                loggedInUser = response.getReturnValue();
                navEvt = $A.get("e.force:navigateToSObject");
                navEvt.setParams({
                    "recordId": loggedInUser.Contact.AccountId,
                    "slideDevName": "detail"
                });
                navEvt.fire();
            }
        });
        $A.enqueueAction(action);
    }
})

 
Best Answer chosen by Spencer Berk
Maharajan CMaharajan C
Hi Berk,

Update your class like below:

Public class BillingController{
    @AuraEnabled
    public static Id getLoggedInUser() {
        Id billingId;
        try
        {
            User u = [SELECT Id, Contact.AccountId FROM User WHERE Id =: UserInfo.getUserId()];    
            Id accId = u.Contact.AccountId;
            Billing__c billingRec= [Select Id from Billing__c where Account__c =: accId limit 1];  // use the correct Api name for Account__c master detail field from Biiling Object in this line
            billingId = billingRec.Id;
        }
        catch(Exception ex){
            system.debug(' Exception ==> ' + ex.getMessage());
        }
        return billingId;
    }
}


Updated JS Controller:

({
    redirectToBilling: function(component, event, helper) {
        var billingId;
        var state;
        var navEvt;
        
        var action = component.get("c.getLoggedInUser");
        action.setCallback(this, function(response) {
            state = response.getState();
            if (state === "SUCCESS") {
                billingId = response.getReturnValue();
                navEvt = $A.get("e.force:navigateToSObject");
                navEvt.setParams({
                    "recordId": billingId,
                    "slideDevName": "detail"
                });
                navEvt.fire();
            }
        });
        $A.enqueueAction(action);
    }
})


Thanks,
Maharajan.C
@DEVS@DEVS 
Why does this RegEx pattern not working in Salesforce ?

pattern myPattern = pattern.compile('@(microsoft|ms|microsoftsurface|msstore).com');
System.debug(myPattern.matcher('aba@ms.com').matches());

I tested it in https://regexr.com/ and it works !
Best Answer chosen by @DEVS
Alain CabonAlain Cabon
find() instead of matches().
pattern myPattern = pattern.compile('@(microsoft|ms|microsoftsurface|msstore).com');
System.debug(myPattern.matcher('aba@ms.com').find());

pattern myPattern = pattern.compile('.+@(microsoft|ms|microsoftsurface|msstore).com');
System.debug(myPattern.matcher('aba.com').matches());

find()
Attempts to find the next subsequence of the input sequence that matches the pattern. This method returns true if a subsequence of the input sequence matches this Matcher object's pattern.

matches()
Attempts to match the entire region against the pattern.

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_pattern_and_matcher_matcher_methods.htm#apex_classes_pattern_and_matcher_matcher_methods
 
Trif Cristian 7Trif Cristian 7 

Hi all,

i'm trying to figure it out what I'm doing wrong here, when I'm looking for my Debog Logs I see this error:

User-added imageUser-added imageand my part of code where is the error.

Can anyone help me with this error?

Best Answer chosen by Trif Cristian 7
Max H. GoldfarbMax H. Goldfarb
Use this:
return Database.getquerylocator([SELECT Id,OwnerId,Name,Owner.Email,SIG_Service_Request_Escalation_Email, (Select Id,OwnerId,Name,Owner.Email from SVMXC__Work_Orders__r where SIG_Due_Date__c =:dt and SVMXC__Order_Status__c NOT IN ('Closed','Completed')), (Select Id,OwnerId,Name,Owner.Email from Administrative_Tasks__r where SIG_Due_Date__c =:dt and SIG_Status__c Not IN ('Closed','Completed')) From SVMXC__Service_Request__c WHERE SVMXC__Status__c = 'Open' and SVMX_SIG_Due_Date__c =: dt]);
Sachin Bhalerao 17Sachin Bhalerao 17 
Dear Team ,

M working on REST API and i write following code . But m receiving error plz have a look on code and snapshot :
 
APEX Code:

public with sharing class AccountRest {
    
 
    
    public list<account> acc{get{
    
    	//Define http Request 
    	//append your Query to the base url
    	HttpRequest req = new HttpRequest();
        req.setEndpoint('https://'+URL.getSalesforceBaseUrl().getHost()+'/services/data/v47.0/query/?q=SELECT Id,Name,AccountNumber,Type FROM Account limit 10');
        req.setMethod('GET');
        
        //Get SessionId
        string autho = 'Bearer '+userInfo.getSessionId();
        req.setHeader('Authorization', autho);
        
        //Get Response
        Http http = new Http();
        HTTPresponse res= http.send(req);
        string response = res.getBody();
        
        //Deserialize obtained json response
        string str = '['+ response.substring(response.indexOf('records":[')+10,response.indexof(']}')) +']';
        acc = (list<Account>)JSON.deserialize(str,list<Account>.class);
        
        return acc;    
    }set;}
    
}

VF :

<apex:page controller="AccountRest">

   
	<apex:sectionHeader title="Accounts" subtitle="List View"/>
	<apex:pageBlock>
	
		<apex:pageBlockTable value="{!acc}" var="key">
		
			<apex:column>
				<apex:facet name="header">Account Name</apex:facet>
				<apex:outputLink value="/{!key.Id}">{!key.Name}</apex:outputLink>
			</apex:column>
			<apex:column value="{!key.AccountNumber}"/>
			<apex:column value="{!key.Type}"/>	
		
		</apex:pageBlockTable>
	
	</apex:pageBlock>

</apex:page>

User-added image
Best Answer chosen by Sachin Bhalerao 17
Nayana KNayana K
Ok. Now with Url.getOrgDomainUrl()., we don't have to add endpoint in remote site setting.

req.setEndpoint(Url.getOrgDomainUrl().toExternalForm()+'/services/data/v46.0/query?q=SELECT+Id,+Name,+AccountNumber,+Type+FROM+Account+limit+10');

Just change this line and check
 
Anurag Reddy KanchimireddyAnurag Reddy Kanchimireddy 

Hi,

Im using nested loop for fetching case comments depending on the languages(its a list), To achieve this I have implemented nested Loop.
1st loop fetches all the languages from the custom object and 
2nd loop fetches case comments depending on the language.
While im using this  "Too many SOQL queries" is firing please suggest me solution.

 

Best Answer chosen by Anurag Reddy Kanchimireddy
Dev-FoxDev-Fox
Hi Anurag,
Just make it somple like below:
set<strinng> langSet = new set<string>();
for(language_obj obj:[select lang_field from language_obj where <your query condition>]){
  langSet.add(obj.lang_field);
}
for(casecomment commObj:[select id, other_fields from casecomment where lang_field IN :]langSet){
  //do process here
}
hope this helps
Laxmi Pandey 20Laxmi Pandey 20 
Hi, I am trying to combine two picklist values from two different objects for selection on my vf page.

let's say, I have an object opportunity with Stage picklist

there is another object as "Order Intake" which is the child of opportunity; it has a picklist which says if the oif days are due by options:
10 days
20 days
30 days

I am creating a picklist for vf page as 'Select category' where I want options as Stage values + Order Intake values;
when I select the options it should display respective Order Intake or opportunity.

Please assist
Best Answer chosen by Laxmi Pandey 20
Dev-FoxDev-Fox
try this
Schema.DescribeFieldResult OppFldResult = Opportunity.Stagename.getDescribe();
List<Schema.PicklistEntry> Opple = OppFldResult.getPicklistValues();

Schema.DescribeFieldResult ObjFldResult = CustomObject.PickistField.getDescribe();
List<Schema.PicklistEntry> Objple = ObjFldResult.getPicklistValues();

list<selectoption> optionLst = new list<selectoption>();
optionLst.add(new selectoption('', '-None-'));
for( Schema.PicklistEntry OppickListVal : Opple){
    for(Schema.PicklistEntry ObjpickListVal : Objple){
        optionLst.add(new selectoption(OppickListVal.getValue()+'-'+ObjpickListVal.getValue(), OppickListVal.getLabel()+'-'+ObjpickListVal.getLabel()));
    }
}

 
Best Answer chosen by Md Hassan
vijay kumar kvijay kumar k
Hi Md Hassan

Yes , you can integrate SSO in any website with Salesforce for that Salesforce needs only Metadata file of which one to you integrate. So first generate METADATA file in Your CRM tool use this file in Salesforce.

SSO Implementationntation method in Salesforce.
https://help.salesforce.com/articleView?id=sso_saml.htm&type=5&sfdcIFrameOrigin=null

If you have time practice the same thing in Salesforce trailhead. https://trailhead.salesforce.com/en/content/learn/modules/identity_login/identity_login_sso

Regards
Vijay