Forum Replies Created

Page 2 of 8
  • Messaging.MassEmailMessage massEmail = new Messaging.MassEmailMessage();
    massEmail.setTargetObjectIds(userIds);
    massEmail.setSaveAsActivity(false);
    massEmail.setTemplateId(templateId);
    List<Messaging.Email> emails = new List<Messaging.Email>{massEmail};
    emails.add(‘your email id’);
    Messaging.SendEmailResult[] results = Messaging.sendEmail(emails, false);

  • Deepak

    Member
    December 9, 2019 at 2:28 pm in reply to: What feature would you use to track changes to settings in Salesforce?

    Earlier this week a friend wanted to know how best to troubleshoot an error message he, and his users, were getting.  Every time anyone tried to access ANY record, they got an error that looked like this:

    “UNABLE_TO_LOCK_ROW : unable to obtain exclusive access to this record”

    That’s bad!  No one could work inside Salesforce!

    This meant that somewhere, something had changed to cause all the records in their org to be locked.  How does my friend figure out what changed so he can quickly un-do it?

    The Audit Trail to the rescue!!

    What is it?
    The Audit Trail helps you track the recent Setup changes that you and other administrators have made to your organization. This is especially useful in organizations with multiple administrators.

    The setup Audit Trail history shows you the 20 most recent Setup changes made to your organization. It lists:

    The date and time (with timezone) of the change.
    Who made it (by username).
    What the change was.
    Here’s an example:

    To view the setup Audit Trail history, click Setup –> Security Controls –> View Setup Audit Trail.

    What permissions do I need to view the Audit Trail?
    In order to view the Audit Trail, you’ll need “View Setup and Configuration” permission.

    What does it track?
    The Audit Trail tracks lots of things. For example: changing a page layout, changing tab names, or changing activity settings. Click here for a complete list of all the thing the Audit Trail tracks.

    Why would I need this?
    The Audit Trail is useful for troubleshooting. Because it captures date/time, you can often trace user issues back to a specific change. For example, if users all of a sudden are being asked to reset their passwords, you can trace that back to a change in password settings.

    It’s also a great record of all the work you’ve done to customize Salesforce. Smart administrators keep a log of the work they do, and the Audit Trail is a great place to start! This can be especially useful when review time comes around!

    What if I want to see more than the last 20 entries?
    To download your organization’s full Setup history for the past 180 days, click the Download link. This will give you a CSV file that can be opened in Excel and sorted.

    This thing is awesome! Is there anything it can’t do?
    The one thing the Audit Trail doesn’t do is capture the “why”. Why did Joe edit that workflow? Why would Sally change the email address for a user? These kinds of questions can’t be answered with the Audit Trail. But, you do know who to ask because their username is right there.

  • Trigger.old: Returns a list of the old versions of the sObject records. Trigger.old should return a type ofList<sObject__c>.Note that this sObject list is only available in the update and delete triggers.

    Trigger.oldMap: A map of IDs to the old versions of the sObject records. Trigger.oldMap should return a type of Map<Id, sObject__c>.Note that this map is only available in the update and delete triggers.

  • Deepak

    Member
    December 9, 2019 at 10:05 am in reply to: How to insert a list custom setting record from apex in Salesforce?

    Custom Settings Methods
    Custom settings are similar to custom objects and enable application developers to create custom sets of data, as well as create and associate custom data for an organization, profile, or specific user. All custom settings data is exposed in the application cache, which enables efficient access without the cost of repeated queries to the database. This data can then be used by formula fields, validation rules, flows, Apex, and the SOAP API.
    Usage
    Custom settings methods are all instance methods, that is, they are called by and operate on a particular instance of a custom setting. There are two types of custom settings: hierarchy and list. The methods are divided into those that work with list custom settings, and those that work with hierarchy custom settings.

    All custom settings data is exposed in the application cache, which enables efficient access without the cost of repeated queries to the database. However, querying custom settings data using Standard Object Query Language (SOQL) doesn't make use of the application cache and is similar to querying a custom object. To benefit from caching, use other methods for accessing custom settings data such as the Apex Custom Settings methods.
    For more information on creating custom settings in the Salesforce user interface, see “Create Custom Settings” in the Salesforce online help.
    Custom Setting Examples
    The following example uses a list custom setting called Games. Games has a field called GameType. This example determines if the value of the first data set is equal to the string PC.

    1
    List<Games__C> mcs = Games__c.getall().values();
    2
    boolean textField = null;
    3
    if (mcs[0].GameType__c == 'PC') {
    4
    textField = true;
    5
    }
    6
    system.assertEquals(textField, true);
    The following example uses a custom setting from Country and State Code Custom Settings Example. This example demonstrates that the getValues and getInstance methods list custom setting return identical values.1
    Foundation_Countries__c myCS1 = Foundation_Countries__c.getValues('United States');
    2
    String myCCVal = myCS1.Country_code__c;
    3
    Foundation_Countries__c myCS2 = Foundation_Countries__c.getInstance('United States');
    4
    String myCCInst = myCS2.Country_code__c;
    5
    system.assertEquals(myCCinst, myCCVal);
    Hierarchy Custom Setting Examples
    In the following example, the hierarchy custom setting GamesSupport has a field called Corporate_number. The code returns the value for the profile specified with pid.

    1
    GamesSupport__c mhc = GamesSupport__c.getInstance(pid);
    2
    string mPhone = mhc.Corporate_number__c;
    The example is identical if you choose to use the getValues method.The following example shows how to use hierarchy custom settings methods. For getInstance, the example shows how field values that aren't set for a specific user or profile are returned from fields defined at the next lowest level in the hierarchy. The example also shows how to use getOrgDefaults.

    Finally, the example demonstrates how getValues returns fields in the custom setting record only for the specific user or profile, and doesn't merge values from other levels of the hierarchy. Instead, getValues returns null for any fields that aren't set. This example uses a hierarchy custom setting called Hierarchy. Hierarchy has two fields: OverrideMe and DontOverrideMe. In addition, a user named Robert has a System Administrator profile. The organization, profile, and user settings for this example are as follows:Organization settings
    OverrideMe: Hello
    DontOverrideMe: World
    Profile settings
    OverrideMe: Goodbye
    DontOverrideMe is not set.
    User settings
    OverrideMe: Fluffy
    DontOverrideMe is not set.
    The following example demonstrates the result of the getInstance method if Robert calls it in his organization:1
    Hierarchy__c CS = Hierarchy__c.getInstance();
    2
    System.Assert(CS.OverrideMe__c == 'Fluffy');
    3
    System.assert(CS.DontOverrideMe__c == 'World');
    If Robert passes his user ID specified by RobertId to getInstance, the results are the same. This is because the lowest level of data in the custom setting is specified at the user level.1
    Hierarchy__c CS = Hierarchy__c.getInstance(RobertId);
    2
    System.Assert(CS.OverrideMe__c == 'Fluffy');
    3
    System.assert(CS.DontOverrideMe__c == 'World');
    If Robert passes the System Administrator profile ID specified by SysAdminID to getInstance, the result is different. The data specified for the profile is returned:1
    Hierarchy__c CS = Hierarchy__c.getInstance(SysAdminID);
    2
    System.Assert(CS.OverrideMe__c == 'Goodbye');
    3
    System.assert(CS.DontOverrideMe__c == 'World');
    When Robert tries to return the data set for the organization using getOrgDefaults, the result is:1
    Hierarchy__c CS = Hierarchy__c.getOrgDefaults();
    2
    System.Assert(CS.OverrideMe__c == 'Hello');
    3
    System.assert(CS.DontOverrideMe__c == 'World');
    By using the getValues method, Robert can get the hierarchy custom setting values specific to his user and profile settings. For example, if Robert passes his user ID RobertId to getValues, the result is:1
    Hierarchy__c CS = Hierarchy__c.getValues(RobertId);
    2
    System.Assert(CS.OverrideMe__c == 'Fluffy');
    3
    // Note how this value is null, because you are returning
    4
    // data specific for the user
    5
    System.assert(CS.DontOverrideMe__c == null);
    If Robert passes his System Administrator profile ID SysAdminID to getValues, the result is:1
    Hierarchy__c CS = Hierarchy__c.getValues(SysAdminID);
    2
    System.Assert(CS.OverrideMe__c == 'Goodbye');
    3
    // Note how this value is null, because you are returning
    4
    // data specific for the profile
    5
    System.assert(CS.DontOverrideMe__c == null);
    Country and State Code Custom Settings Example
    This example illustrates using two custom setting objects for storing related information, and a Visualforce page to display the data in a set of related picklists.

    In the following example, country and state codes are stored in two different custom settings: Foundation_Countries and Foundation_States.

    The Foundation_Countries custom setting is a list type custom setting and has a single field, Country_Code.
    The Foundation_States custom setting is also a List type of custom setting and has the following fields:Country Code
    State Code
    State Name

    The Visualforce page shows two picklists: one for country and one for state.
    01
    <apex:page controller="CountryStatePicker">
    02
    <apex:form >
    03
    <apex:actionFunction name="rerenderStates" rerender="statesSelectList" >
    04
    <apex:param name="firstParam" assignTo="{!country}" value="" />
    05
    </apex:actionFunction>
    06

    07
    <table><tbody>
    08
    <tr>
    09
    <th>Country</th>
    10
    <td>
    11
    <apex:selectList id="country" styleclass="std" size="1"
    12
    value="{!country}" onChange="rerenderStates(this.value)">
    13
    <apex:selectOptions value="{!countriesSelectList}"/>
    14
    </apex:selectList>
    15
    </td>
    16
    </tr>
    17
    <tr id="state_input">
    18
    <th>State/Province</th>
    19
    <td>
    20
    <apex:selectList id="statesSelectList" styleclass="std" size="1"
    21
    value="{!state}">
    22
    <apex:selectOptions value="{!statesSelectList}"/>
    23
    </apex:selectList>
    24
    </td>
    25
    </tr>
    26
    </tbody></table>
    27
    </apex:form>
    28
    </apex:page>
    The Apex controller CountryStatePicker finds the values entered into the custom settings, then returns them to the Visualforce page.view source
    print?
    01
    public with sharing class CountryStatePicker {
    02

    03
    // Variables to store country and state selected by user
    04
    public String state { get; set; }
    05
    public String country {get; set;}
    06

    07
    // Generates country dropdown from country settings
    08
    public List<SelectOption> getCountriesSelectList() {
    09
    List<SelectOption> options = new List<SelectOption>();
    10
    options.add(new SelectOption('', '-- Select One --'));
    11

    12
    // Find all the countries in the custom setting
    13
    Map<String, Foundation_Countries__c> countries = Foundation_Countries__c.getAll();
    14

    15
    // Sort them by name
    16
    List<String> countryNames = new List<String>();
    17
    countryNames.addAll(countries.keySet());
    18
    countryNames.sort();
    19

    20
    // Create the Select Options.
    21
    for (String countryName : countryNames) {
    22
    Foundation_Countries__c country = countries.get(countryName);
    23
    options.add(new SelectOption(country.country_code__c, country.Name));
    24
    }
    25
    return options;
    26
    }
    27

    28
    // To generate the states picklist based on the country selected by user.
    29
    public List<SelectOption> getStatesSelectList() {
    30
    List<SelectOption> options = new List<SelectOption>();
    31
    // Find all the states we have in custom settings.
    32
    Map<String, Foundation_States__c> allstates = Foundation_States__c.getAll();
    33

    34
    // Filter states that belong to the selected country
    35
    Map<String, Foundation_States__c> states = new Map<String, Foundation_States__c>();
    36
    for(Foundation_States__c state : allstates.values()) {
    37
    if (state.country_code__c == this.country) {
    38
    states.put(state.name, state);
    39
    }
    40
    }
    41

    42
    // Sort the states based on their names
    43
    List<String> stateNames = new List<String>();
    44
    stateNames.addAll(states.keySet());
    45
    stateNames.sort();
    46

    47
    // Generate the Select Options based on the final sorted list
    48
    for (String stateName : stateNames) {
    49
    Foundation_States__c state = states.get(stateName);
    50
    options.add(new SelectOption(state.state_code__c, state.state_name__c));
    51
    }
    52

    53
    // If no states are found, just say not required in the dropdown.
    54
    if (options.size() > 0) {
    55
    options.add(0, new SelectOption('', '-- Select One --'));
    56
    } else {
    57
    options.add(new SelectOption('', 'Not Required'));
    58
    }
    59
    return options;
    60
    }
    61
    }

  • Have you checked that all VF Pages and Classes are added to their Profiles? You can find that when you go to the profile and scroll down to the bottom. I hope this helps.

  • Deepak

    Member
    December 8, 2019 at 5:43 pm in reply to: How to rename multiple box folders through apex in Salesforce?

    This can be done by creating a script using our API. The specific endpoint you would need to update the name would be: https://developer.box.com/reference#update-information-about-a-folder. However, you would first need to find all the folder IDs of the folders with the same name. Perhaps someone else might be able to provide more details on that piece!

  • Transfer Chats to an Agent, Skill, or Button
    Chats can be transferred to another agent, skill, or button so your customers always receive the highest-quality help from the most relevant sources. This information applies to chats routed with Chat routing only.

    Available in: Salesforce Classic
    Available in: Performance Editions and in Developer Edition orgs that were created after June 14, 2012

    Available in: Unlimited Edition and Enterprise Edition with the Service Cloud
    Just as you forward an email or pass a case to another agent, you can transfer a chat. Transferring is useful when a customer has an issue that another agent can solve, or requires an agent with a particular skill. How the chat gets to the next agent depends on the kind of transfer you use.

    There are three types of transfers: Transfer to Agent, Transfer to Skill, and Transfer to Button. To ensure that your customers get help as quickly as possible, certain chat transfer types can exceed agents’ configured capacity. You can set agent capacity through the Chat Configuration. If your organization uses Omni-Channel, you can set agent capacity through the Presence Configuration.

    TYPE OF TRANSFER
    SCENARIO
    METHOD OF TRANSFER
    CAN EXCEED CONFIGURED AGENT CAPACITY?
    Transfer to Agent
    You want to transfer the chat to Agent Jane, because she’s the perfect fit for the case.
    A chat request is sent to Agent Jane. If she accepts the request, the chat is transferred to her, and your chat workspace closes.
    Yes
    Transfer to Skill
    You want to forward the chat to an agent who has the skill “billing specialist.”
    A chat request is sent to all agents assigned to the skill, and the chat is transferred to the first agent to accept it.
    Yes
    Transfer to Button
    You want to transfer a chat from the sales queue to the service queue.
    The chat is transferred to an available agent assigned to the selected button or queue.
    No
    When chats are transferred directly to an agent or skill group, the transferred chats are allowed to exceed the accepting agent’s capacity. As a result, agents always receive a chat request, even if they’re handling the maximum allowed number of chats. If the transfer request is rejected or times out, the original agent can try another recipient or transfer method.

    If an agent selects User = All Users with Skill, then the chat transfer request is broadcast to all agents who are available who have that skill. As a result, multiple agents can hear the incoming chat notification for a few seconds. If an agent immediately accepts the chat transfer or has auto-accept enabled, the request is no longer shown to the other agents but the agents might continue to hear the notification sound for a few seconds.

    Chats routed from buttons or queues always respect the configured agent capacity. So, agents assigned to that button or queue don’t receive the transfer request—or any other chat requests—until they have open capacity. But don’t worry: customers still won’t get stuck waiting for another agent. When a chat is sent to the next queue, it’s added into the list of incoming chats by its age, so it will appear higher up than brand-new chat requests.

    When an agent accepts a transferred chat, the records attached to the chat transcript, like a case or contact, open alongside the chat in the workspace. The accepting agent has the information to start assisting the customer right away, without having to search for related records. These records are also up-to-date, because the previous agent is prompted to save any changes when the transfer is initiated.

    When an agent accepts a transferred chat, only the chat is transferred to the agent. Ownership of related records, such as a case, aren't transferred to the agent.

    NOTE If the accepting agent doesn’t have permissions to view one or more of the attached objects, those items won’t open in the transferred workspace.
    Transfer Chats
    You can transfer chat sessions to other agents when a customer needs extra help with an issue, or to make room for new requests.
    Send a Chat Conferencing Request
    As wise as support agents are, sometimes a single support agent doesn’t have all the information that’s required to solve a customer’s problem. Chat conferencing lets you invite one or more agents into your customer chats. That way, your agents can turn boring chats into veritable support parties for your customers—all without disrupting the flow of conversation! Send a chat conferencing request to ask another agent to join you in a customer chat.
    Request Help with a Chat
    When you need help with a chat, you can raise a virtual flag to alert a supervisor. Supervisors are alerted that you need help, and they can respond directly via the console.

  • Deepak

    Member
    December 8, 2019 at 5:40 pm in reply to: How to add a new tab to Case Activity tabs in Salesforce?

    Whats' the custom tab? Keep in mind those tabs are meant for specific actions. Here's the trailhead that should help:

    Actions and Lightning Experience:
    https://developer.salesforce.com/trailhead/lex_migration_customization/lex_migration_customization_actions

    Here's a quick summary of how you'd customize the actions:

    You'll be creating your quick actions under the Buttons, Links, Actions options for the respective object (New Action). In your case, you would go the the Lead object under settings/object manager, then create a new Action, which will be whatever the custom action you'd like to do.

    Once created, you can go to the layout of the lead page and add that Quick Action to the area in your layout called "Salesforce1 and Lightning Experience Actions." You'll want to add as one of the first 4 actions for it to show in your layout.

  • Deepak

    Member
    December 8, 2019 at 5:38 pm in reply to: How to upload files in community using Salesforce lightning?

    Use lightning:fileUpload component in your page to upload files in salesforce object.

  • Deepak

    Member
    December 6, 2019 at 12:34 pm in reply to: How we can create google chart from apex class in Salesforce?

    <apex:page >
    <apex:includeScript id="a" value="https://www.google.com/jsapi" />
    <apex:sectionHeader subtitle="Reactive Call Outs Per Day"/>
    <!-- Google Charts will be drawn in this DIV -->
    <div id="chart_div" />

    <script type="text/javascript" src="/soap/ajax/20.0/connection.js"></script>
    <script type="text/javascript">
    sforce.connection.sessionId = "{!$Api.Session_ID}";
    var result = sforce.connection.query("SELECT DAY_ONLY(CreatedDate) days, count(createdDate) counts FROM Visits__c where createdDate = LAST_N_Days:90 GROUP BY DAY_ONLY(CreatedDate) order by DAY_ONLY(createdDate) desc");
    records = result.getArray("records");
    // Load the Visualization API and the piechart package.
    google.load('visualization', '1.0', {'packages':['corechart']});
    google.setOnLoadCallback(drawCharts);
    function drawCharts() {
    var data = new google.visualization.DataTable();
    data.addColumn('string', 'Created Date');
    data.addColumn('number', 'Record Count');
    data.addRows(records.length);
    for(var i = 0 ; i < records.length ; i++){
    data.setValue(i,0,records[i].days);
    data.setValue(i,1,records[i].counts);
    }
    var options = {
    title: '',
    hAxis: {title: 'days'},
    vAxis: {title: 'counts'},
    legend: 'none',
    trendlines: { 0: {color: 'red',} } // Draw a trendline for data series 0.
    };
    var visualization = new google.visualization.ColumnChart(document.getElementById('chart_div'));
    visualization.draw(data,options);
    }
    </script>
    </apex:page>

  • Deepak

    Member
    December 6, 2019 at 12:32 pm in reply to: How can we create workflow through apex in Salesforce?

    You can not create approval process or workflow with Apex system classes.

    These are configurable business logics which can not be created generally in Apex.

    But there is one way of creating these components is Metadata API. In metadata API you can create Approval process, workflows, workflow rules, Assignment rules and other admin and development logics.

    In apex, a record can be submit for approval, a record can be rejected and approved. You can only access already created Approval process on object and perform submit, approve and reject operations on record. Workflow rules can not be accessed in this way.

  • Deepak

    Member
    December 6, 2019 at 12:31 pm in reply to: How to cover a user in Salesforce test class?

    Create a new user and assign it a profile and role by querying and insert the user.

    You can also cover in a different way by creating an account and a related contact. Enable account as partner user then create a user, assign it a partner profile and add contactid in user.

  • By default salesforce excuete the batch class like this from my understanding because  it it will not initialise to null there is chance to exist previous data  then the batch class will fail.
    if you will not initialise to null
    Let us assume you have excueted the batch with 200 records by five batches after excuetion of one batch list having 200 records again if we excuete the batch next two hunderd records will add to batch then list will be having 400records then the batch class can not excuete four hundered records at the the same then batch will fail like that there is a chance to happen like that

  • Step 1 : Create Apex Controller : dataTableCtrl.apxc
    From Developer Console >> File >> New >> Apex Class
    /* sfdcmonkey.com || Date 01/31/2018 || API Version 41.0 */
    public class tableWithManageCtrl {
    @AuraEnabled
    public static List < account > fetchAccount() {

    List < Account > returnList = new List < Account > ();

    for (Account acc: [select id, Name, Type, Industry, Phone, Fax from account LIMIT 10]) {
    returnList.add(acc);
    }
    return returnList;
    }
    }

    Step 2 : Create Child Lightning Component  : auraIfContains.cmp
    The purpose to create this child component is, create a Alternate/Workaround for contains() function in ‘aura:if’ Condition in Lightning Component.

    check following post on this step 2 workaround :

    Alternate/Workaround for contains() function in aura:if Condition in Lightning Component

    <aura:component >
    <aura:handler name="init" value="{!this}" access="global" action="{!c.doInit}" />
    <aura:attribute name="list" type="string[]" />
    <aura:attribute name="element" type="String" />
    <aura:attribute name="condition" type="Boolean" />
    <aura:handler name="change" value="{!v.list}" action="{!c.doInit}"/>

    <aura:if isTrue="{!v.condition}">
    {!v.body}
    </aura:if>
    </aura:component>

    auraIfContainsController.js

    ({
    doInit: function(component, event, helper) {
    var getList = component.get('v.list');
    var getElement = component.get('v.element');
    var getElementIndex = getList.indexOf(getElement);

    if(getElementIndex != -1){
    component.set('v.condition',true);
    }else{
    component.set('v.condition',false);
    }
    },
    })

    Step 3 : Create Parent Lightning Component  : dataTableWithDynamicCol.cmp

    <!-- sfdcmonkey.com || Date 01/31/2017 || API Version 41.0 || Parent Component-->
    <aura:component controller="tableWithManageCtrl" implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global" >
    <aura:handler name="init" value="this" action="{!c.doInit}"/>
    <aura:attribute name="searchResult" type="List" description="use for store and display account list return from server"/>
    <aura:attribute name="options"
    type="List"
    default="[
    {'label': 'Type', 'value': 'Type'},
    {'label': 'Industry', 'value': 'Industry'},
    {'label': 'Phone', 'value': 'Phone'},
    {'label': 'Fax', 'value': 'Fax'},
    ]"/>

    <aura:attribute name="selectedValues" type="List" default="Name"/>
    <aura:attribute name="isOpen" type="boolean" default="false"/>

    <!--Use aura:if tag to display Model Box, on the bese of conditions. [isOpen boolean attribute] -->
    <aura:if isTrue="{!v.isOpen}">
    <!--###### MODAL BOX Start From Here ######-->
    <div role="dialog" tabindex="-1" aria-labelledby="header99" class="slds-modal slds-fade-in-open ">
    <div class="slds-modal__container">
    <!-- ###### MODAL BOX HEADER Part Start From Here ######-->
    <div class="slds-modal__header">
    <button class="slds-button slds-modal__close slds-button--icon-inverse" title="Close" onclick="{!c.closeModel}">
    X
    <span class="slds-assistive-text">Close</span>
    </button>
    <h2 id="header99" class="slds-text-heading--medium">Manage Table Columns</h2>
    </div>
    <!--###### MODAL BOX BODY Part Start From Here ######-->
    <div class="slds-modal__content slds-p-around--medium">
    <div class="slds-p-around_medium">
    <lightning:checkboxGroup aura:id="mygroup"
    name="checkboxGroup"
    label="Manage Cloumn"
    options="{! v.options }"
    value="{! v.selectedValues }"
    />
    </div>
    </div>
    <!--###### MODAL BOX FOOTER Part Start From Here ######-->
    <div class="slds-modal__footer">
    <button class="slds-button slds-button--neutral" onclick="{!c.closeModel}" >Done</button>
    </div>
    </div>
    </div>
    <div class="slds-backdrop slds-backdrop--open"></div>
    <!--###### MODAL BOX Part END Here ######-->
    </aura:if>

    <div class="slds-m-around--large">
    <!--###### lightning button icon for show/hide columns popup ######-->
    <div class="slds-clearfix">
    <div class="slds-float_right">
    <lightning:buttonIcon size="large" onclick="{!c.openModel}" iconName="utility:matrix" variant="bare" title="manage table columns" alternativeText="Settings" iconClass="dark"/>
    </div>
    </div>

    <br/><br/>
    <!--###### lightning data table start ######-->
    <table class="slds-table slds-table_bordered slds-table_cell-buffer">
    <thead>
    <tr class="slds-text-title_caps">
    <th scope="col">
    <div class="slds-truncate" title="Account Name">Account Name</div>
    </th>
    <!--###### the value of element attribute in child component must be same as checkboxGroup value  ######-->
    <c:auraIfContains list="{!v.selectedValues}"  element="Type">
    <th scope="col"><div class="slds-truncate" title="Type">Type</div></th>
    </c:auraIfContains>
    <c:auraIfContains list="{!v.selectedValues}"  element="Industry">
    <th scope="col"><div class="slds-truncate" title="Industry">Industry</div></th>
    </c:auraIfContains>
    <c:auraIfContains list="{!v.selectedValues}"  element="Phone">
    <th scope="col"><div class="slds-truncate" title="Phone">Phone</div></th>
    </c:auraIfContains>
    <c:auraIfContains list="{!v.selectedValues}"  element="Fax">
    <th scope="col"><div class="slds-truncate" title="Fax">Fax</div></th>
    </c:auraIfContains>
    </tr>
    </thead>
    <tbody>

    <!--### display all records of searchResult attribute by aura:iteration ###-->
    <aura:iteration items="{!v.searchResult}" var="acc">
    <tr>

    <td><div class="slds-truncate">{!acc.Name}</div></td>
    <c:auraIfContains list="{!v.selectedValues}"  element="Type">
    <td><div class="slds-truncate">{!acc.Type}</div></td>
    </c:auraIfContains>
    <c:auraIfContains list="{!v.selectedValues}"  element="Industry">
    <td><div class="slds-truncate">{!acc.Industry}</div></td>
    </c:auraIfContains>
    <c:auraIfContains list="{!v.selectedValues}"  element="Phone">
    <td><div class="slds-truncate">{!acc.Phone}</div></td>
    </c:auraIfContains>
    <c:auraIfContains list="{!v.selectedValues}"  element="Fax">
    <td><div class="slds-truncate">{!acc.Fax}</div></td>
    </c:auraIfContains>
    </tr>
    </aura:iteration>
    </tbody>
    </table>
    </div>

    </aura:component>

    check code comments.
    dataTableWithDynamicColController.js

    ({
    doInit: function(component, event, helper) {
    var action = component.get("c.fetchAccount");
    action.setCallback(this, function(response) {
    var state = response.getState();
    if (state === "SUCCESS") {
    var storeResponse = response.getReturnValue();
    // set searchResult list with return value from server.
    component.set("v.searchResult", storeResponse);
    }

    });
    $A.enqueueAction(action);
    },
    openModel: function(component, event, helper) {
    // for Display Model,set the "isOpen" attribute to "true"
    component.set("v.isOpen", true);
    },

    closeModel: function(component, event, helper) {
    // for Hide/Close Model,set the "isOpen" attribute to "Fasle"
    component.set("v.isOpen", false);
    },
    })

    Step 4 : Create Lightning Application for Testing: demo.app
    From Developer Console >> File >> New >> Lightning Application

    <aura:application extends="force:slds">
    <c:dataTableWithDynamicCol/>
    <!-- here c: is org. default namespace prefix-->
    </aura:application>

    Output :

  • This is a simple example to validate lightning input fields in a lightning component.

    Three main seeded functions are used for the custom validation in input components.

    reportValidity
    setCustomValidity
    checkValidity
    The report validity uses to displays the error message on the invalid fields. The error message are defined based on the pattern mismatch, required, max length, min length, etc. attributes. The custom error message for the mentioned attributes can be defined in the corresponding messageWhenPatternMismatch, messageWhenTypeMismatch, messageWhenValueMissing, etc error message attributes.

    REPORT THIS AD
    All input component type has a validity attribute which is a readonly object with the following attributes.

    badInput: Indicates that the value is invalid.
    customError: Indicates that a custom error has been set. See Custom Validity Error Messages.
    patternMismatch: Indicates that the value doesn’t match the specified pattern.
    rangeOverflow: Indicates that the value is greater than the specified max attribute.
    rangeUnderflow: Indicates that the value is less than the specified min attribute.
    stepMismatch: Indicates that the value doesn’t match the specified step attribute.
    tooLong: Indicates that the value exceeds the specified maxlength attribute.
    tooShort: Indicates that the value is less than the specified minlength attribute.
    typeMismatch: Indicates that the value doesn’t match the required syntax for an email or url input type.
    valueMissing: Indicates that an empty value is provided when required attribute is set to true
    valid: True if none of the preceding properties are true.
    The report validity function throws the corresponding error message based on the v.validity attribute value.

    handleBlur: function (cmp, event) {
    var validity = cmp.find("myinput").get("v.validity");
    console.log(validity.valid); //returns true
    }
    SetCustomValidity method can be used to set the custom error message dynamically from the code based on certain conditions.

    ({
    register : function(component, event) {
    var inputCmp = component.find("inputCmp");
    var value = inputCmp.get("v.value");
    // is input valid text?
    if (value === "John Doe") {
    inputCmp.setCustomValidity("John Doe is already registered");
    } else {
    inputCmp.setCustomValidity(""); // if there was a custom error before, reset it
    }
    inputCmp.reportValidity(); // Tells lightning:input to show the error right away without needing interaction
    }
    })

    REPORT THIS AD
    CheckValidity is the another seeded method which returns a boolean value based on the valid property in the validity attribute. The value only be true if the none of the error conditions are met.

    https://developer.salesforce.com/docs/component-library/bundle/lightning:input/specification

    Go through the link for more details on the custom error message attributes in input component.
    In the below example, I have included the best options to use the standard validations and the custom validations by separating the layout into different sections.

    The first section contains three input components for first name , last name and email with same aura id. The submit button handler checks the validity of each component registered in the aura id named ‘field’. Reduce is standard Javascript array function that reduces the array values into a single output values based on the defined callback. Also, the function has two parameters, one is a callback (reducer) which execute over each array element and other is an initial value.

    <aura:component implements="force:appHostable,flexipage:availableForAllPageTypes" access="global" >
    <div class="c-container">
    <lightning:layout multipleRows="true">
    <lightning:layoutItem padding="around-small" size="5">
    <lightning:layout multipleRows="true">
    <lightning:layoutItem padding="around-small" size="12">
    <lightning:input aura:id="field" label="First name" placeholder="First name" required="true" messageWhenValueMissing="Enter First Name" />
    </lightning:layoutItem>
    <lightning:layoutItem padding="around-small" size="12">
    <lightning:input aura:id="field" label="Last name" placeholder="Last name" required="true"  />
    </lightning:layoutItem>
    <lightning:layoutItem padding="around-small" size="12">
    <lightning:input aura:id="field" type="email" label="Email Address" placeholder="Email Address" required="true"  messageWhenTypeMismatch="Enter a valid email address"/>
    </lightning:layoutItem>
    <lightning:layoutItem padding="around-small" >
    <lightning:button aura:id="submit" type="submit" label="Submit" onclick="{! c.onClick }" />
    </lightning:layoutItem>
    </lightning:layout>
    </lightning:layoutItem>
    <lightning:layoutItem padding="around-small" size="1">
    </lightning:layoutItem>
    <lightning:layoutItem padding="around-small" size="5">
    <lightning:layout multipleRows="true">
    <lightning:layoutItem padding="around-small" size="12">
    <lightning:input aura:id="firstName" label="First name" placeholder="First name"/>
    </lightning:layoutItem>
    <lightning:layoutItem padding="around-small" size="12">
    <lightning:input aura:id="lastName" label="Last name" placeholder="Last name" required="true"  />
    </lightning:layoutItem>
    <lightning:layoutItem padding="around-small" size="12">
    <lightning:input aura:id="email" type="text" label="Email Address" placeholder="Email Address" required="true"  messageWhenPatternMismatch="Enter a valid email address" pattern="^w+([.-]?w+)*@w+([.-]?w+)*(.w{2,3})+$"/>
    </lightning:layoutItem>
    <lightning:layoutItem padding="around-small" size="12">
    <lightning:input aura:id="phone" type="text" label="Phone Number" placeholder="Phone Number" required="true"/>
    </lightning:layoutItem>
    <lightning:layoutItem padding="around-small" >
    <lightning:button aura:id="submit" type="submit" label="Submit Custom Validation" onclick="{! c.onCustomValidationClick }" />
    </lightning:layoutItem>
    </lightning:layout>
    </lightning:layoutItem>
    </lightning:layout>

    </div>
    </aura:component>

    REPORT THIS AD
    Here, In the onClick handler method, the reduce function iterates over components which is having id value as field. The initial value of the function is set as true and the callback accumulate all components validity into a single boolean output. More details on reduce function is provided on the last.

    ({
    onClick : function(component, event, helper) {
    //Validating all input fields together by providing the same aureid 'field'
    let isAllValid = component.find('field').reduce(function(isValidSoFar, inputCmp){
    //display the error messages
    inputCmp.reportValidity();
    //check if the validity condition are met or not.
    return isValidSoFar && inputCmp.checkValidity();
    },true);
    },

    onCustomValidationClick : function(component, event, helper) {
    //Explicitly checking the custom validation:
    var phoneCmp = component.find('phone');
    var phoneCmpValue = phoneCmp.get("v.value");
    //Custom regular expression for phone number
    var phoneRegexFormat = /^d{10}$/;
    //Check for regular expression match with the field value
    if(!phoneCmpValue.match(phoneRegexFormat)) {
    //set the custom error message
    phoneCmp.setCustomValidity("Enter valid phone number");
    }else{
    //reset the error message
    phoneCmp.setCustomValidity("");
    }
    //Group all the fields ids into a JS array
    var controlAuraIds = ["firstName","lastName","email","phone"];
    //reducer function iterates over the array and return false if any of the field is invalid otherwise true.
    let isAllValid = controlAuraIds.reduce(function(isValidSoFar, controlAuraId){
    //fetches the component details from the auraId
    var inputCmp = component.find(controlAuraId);
    //displays the error messages associated with field if any
    inputCmp.reportValidity();
    //form will be invalid if any of the field's valid property provides false value.
    return isValidSoFar && inputCmp.checkValidity();
    },true);

    }
    })

    REPORT THIS AD
    onCustomValidationClick handler method checks the validity of fields those are having different aura Id. Also, included a custom phone number validity check using regular expression in the controller side which is not configurable in the html side.

    As you can see in the below image, the errors are shown based on the validation defined in the standard validation and the custom validation in the JS side.

     

    https://github.com/anilsomasundaran/Lightning-Input-Field-Validation/tree/master/CustomValidation
    How reduce() works

    [0, 1, 2, 3, 4].reduce(function(accumulator, currentValue, currentIndex, array) {
    return accumulator + currentValue;
    });

  • Deepak

    Member
    December 4, 2019 at 2:34 pm in reply to: How to get know the OwnerType of a case is Queue in Salesforce apex?

    Query the case owner as it is a user then query usertype of that user.

  • Deepak

    Member
    December 4, 2019 at 2:33 pm in reply to: what is the use of a case component event in Salesforce lightning?

    The client-side controller for ceNotifier.cmp sets a message in a component event and fires the event. The handler component, ceHandler.cmp, contains the notifier component, and handles the fired event. The client-side controller for ceHandler.cmp sets an attribute in ceHandler.cmp based on the data sent in the event. A user clicks a button in the notifier component, ceNotifier.cmp.

  • Deepak

    Member
    December 4, 2019 at 2:31 pm in reply to: what is the use case of application event in Salesforce lightning?

    The client-side controller for aeNotifier.cmp sets a message in a component event and fires the event. A user clicks a button in the notifier component, aeNotifier.cmp. The client-side controller for aeHandler.cmp sets an attribute in aeHandler.cmp based on the data sent in the event.The handler component, aeHandler.cmp, handles the fired event

  • Create a wrapper class in the controller that includes the button and checkbox and display the wrapper class as list or variable in vf page.

  • Deepak

    Member
    December 4, 2019 at 2:09 pm in reply to: How can a salesforce community user download salesforce files?

    Are these documents actually being saved to the record using Chatter Files or "Notes & Attachments" or are you wanting to render a visualforce page as a PDF and let the user view, print and/or download?
    If you're just rendering the documents and not saving to the record, two things have to happen for Community user to see a Visualforce page. You'll want to Enable Visualforce Page Access to the Community, by going to Communities > Manage Communities > Force.com > Public Access Settings > Enable Visualforce Page Access. Next, is adding the page to the profile(s) of the community user(s), by going to Setup > Manage Users > Profile > Profile Name > Visualforce Page Access > Edit then move the page from the left column to the right.
    If you've enabled Chatter Files, Community users can only see files that were uploaded INTO that community. (i.e., when an internal user with a full SFDC license uploads/creates a file and adds it to a record, the community users can't see it, eventhough you've shared the file with "The Entire Company" AND the community users have access to view the record.)
    If you're using Chatter Files, you'll want to use a Trigger on ContentDocumentLink to share it wih Community users. (This will add it directly into both the Files AND Notes & Attachments related list and not post to the Chatter Feed at the top of the record.) You'd want to include this line of code so when internal users create and attach the PDF, community users can see it: UpdateContentDocumentLinkVisibilityOnInsert on ContentDocumentLink (before insert) { for(ContentDocumentLink. l:Trigger.new)l.Visibility='AllUsers'; }
    If you're still using "Notes & Attachments" here's some additional info if community users still can't view them: "For the Customer Community license, access to Notes and Attachments for most objects is enabled by default. If your users with a Customer Community license can’t access Notes and Attachments on accounts and contacts, contact Salesforce." from https://help.salesforce.com/articleView?id=users_license_types_communities.htm&type=0#fntarg_8

  • Setting Quotas for Customizable Forecasting
    Users with the appropriate permission can set their individual quota. Salesforce admins and users with the appropriate permission can edit any quota. And managers can change the quotas of users who report directly to them in the role hierarchy.

    REQUIRED EDITIONS AND USER PERMISSIONS
    Available in: Salesforce Classic
    Available in: Professional, Enterprise, Performance, Unlimited, and Developer Editions

    USER PERMISSIONS NEEDED
    To set your quota:
    Edit Personal Quota
    To set any user’s quota:
    Manage Internal Users

    AND

    Modify All Data
    Do one of the following:To set your personal quota, access your personal information in your personal settings.
    To change the quota of a user that reports to you, from Setup, enter Users in the Quick Find box, then select Users, and click the full name of the appropriate user.
    Click Edit in the Quotas related list.
    Select the appropriate range start and range length. If available, select a territory and product family.
    NOTE If your organization uses custom fiscal years, you cannot set quotas for a period that does not have a defined fiscal year.
    Enter the quota amounts for revenue and/or quantity.
    Select the appropriate currency if you work with more than one currency.
    Click Save to save the quota and return to the user detail page, or click Quick Save to save the values and continue to edit the quota.
    TIP Using Quick Save allows you to quickly set a different quota for each product family.

    NOTE If these options are not available to you, you may not have customizable forecasting. To determine if your organization has enabled customizable forecasting, see How Do I Make Sure That Customizable Forecasting Is Enabled?. Delegated administrators won’t see the quotas related list on user records.
    You can also use tools like the Data Loader to do mass updates on quotas. When updating quotas, set the quota field value on the RevenueForecast or QuantityForecast objects.

  • From Setup, enter Mass Transfer Records in the Quick Find box, then select Mass Transfer Records.
    Click the link for the type of record to transfer.
    Optionally, fill in the name of the existing record owner in the Transfer from field. For leads, you can transfer from users or queues.
    In the Transfer to field, fill in the name of new record owner. For leads, you can transfer to users or queues.
    If your organization uses divisions, select the Change division.... checkbox to set the division of all transferred records to the new owner’s default division.
    When transferring accounts, you can:Select Transfer open opportunities not owned by the existing account owner to transfer open opportunities owned by other users that are associated with the account.
    Select Transfer closed opportunities to transfer closed opportunities associated with the account. This option applies only to closed opportunities owned by the account owner; closed opportunities owned by other users are not changed.
    Select Transfer open cases owned by the existing account owner to transfer open cases that are owned by the existing account owner and associated with the account.
    Select Transfer closed cases to transfer closed cases that are owned by the existing account owner and associated with the account.
    Select Keep Account Team to maintain the existing account team associated with the account. Deselect this checkbox if you want to remove the existing account team associated with the account.
    Select Keep Opportunity Team on all opportunities to maintain the existing team on opportunities associated with this account. Any opportunity splits are preserved, and split percentages assigned to the previous owner transfer to the new one. If this box is unchecked, all opportunity team members and splits are deleted when the opportunity is transferred.
    NOTE If you transfer closed opportunities, the opportunity team is maintained, regardless of this setting.
    Enter search criteria that the records you are transferring must match. For example, you could search accounts in California by specifying Billing State/Province equals CA.
    Click Find.
    Select the checkbox next to the records you want to transfer. To select all currently displayed items, check the box in the column header.
    NOTE If duplicate records are found, you must select only one of the records to transfer. Transferring duplicate records results in an error.Duplicate records may display if you filter leads based on Campaign Member Status and a matching lead has the same campaign member status on multiple campaigns. For example, if you specify Campaign Member Status equals Sent, and a matching lead named John Smith has the status Sent on two campaigns, his record will display twice.
    Click Transfer.
    Transfer of Associated Items
    When you change record ownership, some associated items that are owned by the current record owner are also transferred to the new owner.

    RECORD
    ASSOCIATED ITEMS THAT ARE ALSO TRANSFERRED
    Accounts
    Contacts (on business accounts only), attachments, notes, open activities, open opportunities owned by the current account owner, and optionally, closed opportunities and open opportunities owned by other users.
    Leads
    Open activities. When transferring leads to a queue, open activities are not transferred.
    Access to Transferred Items
    When transferring accounts and their related data in Professional, Enterprise, Unlimited, Performance, and Developer Editions, all previous access granted by manual sharing, Apex managed sharing, or sharing rules is removed. New sharing rules are then applied to the data based on the new owner. The new owner may need to manually share the transferred accounts and opportunities as necessary to grant access to certain users.

  • Deepak

    Member
    December 3, 2019 at 1:08 pm in reply to: How to prepopulate EventWhoids in Salesforce lightning component?

    recordForm may not work with your use case, and the better approach here would be to use recordEditForm. This is only after discussing this with my team in our internal forum.

    You had a concern that why it doesn't work with recordForm- to which I have mentioned that it will not work with recordForm, and would be better to use recordEditForm.

    Currently, the doc does not mention anything about pre-populating fields. Like any other salesforce doc, it outlines facts, and customizations depend on the person developing the solution. Your use case is a customization.

    I am absolutely not questioning your right to put forward this question. In fact, I understand why do you have this question in the first place. However, what matters here is you having a solution - and recordEditForm would be your best bet here. R&D will not consider changing the doc, as there is nothing mentioned about pre-populating fields there. Pre-populating fields would be a custom use case, and our doc gives general facts of how a recordEditForm works.

  • Create a pricebook and pricebookentry and add products in pricebookentry. Create a trigger on order to add pricebook to the order object.

Page 2 of 8