Thursday, February 9, 2017

Does a Lightning Component know if it is in a Community or a standard Lightning Salesforce page?

Title says it all. Does a Lightning Component know if it is in a Community or a standard Lightning Salesforce page?
I have a component that implements both the interface for Community as Standard Lightning.
Some people suggest to add an attribute and set it in the Lightning App Builder or Community Builder so as to distinguish in which kind of environment we are.

It is quite annoying for the System Administrator to configure the behavior of the component each time it is needed.

But what if this can be achieved automatically by only a few lines of code?

Here is how I did it:

Your component must first extends a controller.

I Hope that this post will be helpful to you. Cheers!!
Lightning component .cmp aura:component implements="force:hasRecordId, force:appHostable, flexipage:availableForAllPageTypes, forceCommunity:availableForAllPageTypes" controller="CustomController"> aura:handler name="init" value="{!this}" action="{!c.init}"/> /aura:component Apex controller .cls public with sharing class CustomController { @AuraEnabled public static boolean isCommunity(){ Id siteId = Site.getSiteId(); if (siteId != null) { return true; } return false; } } Lightning component controller .js ({ init : function(component, event, helper) { var action = component.get("c.isCommunity"); action.setCallback(this, function(response) { var isCommunity = response.getReturnValue(); // do any operation needed here }); $A.enqueueAction(action); } })

No comments:

Post a Comment