Lightning – How to Display Toast Message with Custom Field Value

I have a requirement to display message toast on detail page when any record is opened.
This message will be from a custom field (Alert_Text__c) on Account which is a text field.

Below is the code to display toast message

Lightning component:

<aura:component implements="force:appHostable,flexipage:availableForAllPageTypes">
    <div>
        <lightning:button label="Information"
                          variant="brand"
                          onclick="{!c.showInfo}"/>
        
    </div> 
</aura:component>

Javascript:

({
    showInfo : function(component, event, helper) {
        var toastEvent = $A.get("e.force:showToast");
        toastEvent.setParams({
            title : 'Info',
            message: 'This is an information message.',
            duration:' 5000',
            key: 'info_alt',
            type: 'info',
            mode: 'dismissible'
        });
        toastEvent.fire();
    }
})

Now, is there any way to display value of Alert_Text__c as a message when this button is clicked instead of pre-defined message.
Please suggest

Best Answer

You can, but you'll need to load that data first:

<aura:component implements="force:hasRecordId,force:appHostable,flexipage:availableForAllPageTypes">
    <aura:attribute name="record" type="Map" default="{}" />
    <aura:attribute name="disabled" type="Boolean" default="true" />
    <force:recordData targetFields="{!v.record}"
        recordId="{!v.recordId}"
        recordUpdated="{!c.recordLoaded}"
        fields="Alert_Text__c" />
    <div>
        <lightning:button label="Information"
                          variant="brand"
                          disabled="{!v.disabled}" 
                          onclick="{!c.showInfo}"/>
        
    </div> 
</aura:component>

Then, you can display the message as you'd expect:

({
    recordLoaded: function(component, event, helper) {
        component.set("v.disabled", false);
    },
    showInfo : function(component, event, helper) {
        var record = component.get("v.record");
        var toastEvent = $A.get("e.force:showToast");
        toastEvent.setParams({
            title : 'Info',
            message: record.Alert_Text__c,
            duration:' 5000',
            key: 'info_alt',
            type: 'info',
            mode: 'dismissible'
        });
        toastEvent.fire();
    }
})
Related Topic