新手求助:Aura控制器中action.setParams能否直接传入{!User.ContactId}?
Great question—let's break this down clearly since you're just getting started with Aura controller development!
Why Your Initial Approach Won't Work
You can’t directly use action.setParams({"variable" : "{!User.ContactId}"}) in an Aura controller’s JavaScript. Here’s the key reason:
- The
{!User.ContactId}expression is a server-side merge field. It only gets resolved when Salesforce renders server-side content (like your button’s OnClick JavaScript, which is processed before the page loads in the browser). - Aura controller JS files are pure client-side code—they don’t go through the server’s expression parsing step. If you write
"{!User.ContactId}"here, you’ll pass the literal string"{!User.ContactId}"to your action, not the actual Contact ID value.
Working Alternatives
Here are two reliable ways to pass the User’s Contact ID to your Aura action:
1. Use a Component Attribute
First, define an attribute in your Aura component (.cmp file) to store the Contact ID:
<aura:attribute name="currentUserContactId" type="String" default="{!$User.ContactId}" />
Then in your controller JS, retrieve this attribute value and pass it to the action:
var contactId = component.get("v.currentUserContactId"); action.setParams({"variable": contactId});
This works because the attribute’s default value uses the server-side merge field {!$User.ContactId}, which gets resolved when the component loads.
2. Fetch the Value Directly via $A.get()
You can also access the User’s Contact ID directly in your controller JS using the $A.get() method, which pulls from Salesforce’s global user context:
var contactId = $A.get("$User.ContactId"); action.setParams({"variable": contactId});
This is a more concise approach if you don’t need to reuse the Contact ID elsewhere in the component.
Why Your Button Approach Worked
Your button’s OnClick JavaScript works because that code is part of the button’s server-side configuration. Salesforce resolves {!User.ContactId} to the actual value before sending the page to the client, so the browser gets the raw Contact ID string instead of the merge field expression.
Quick Tip
Don’t forget to add a check for empty values! Some Salesforce users might not have a linked Contact record, so handling cases where contactId is null or empty will prevent errors in your action logic.
内容的提问来源于stack exchange,提问作者molinet

