Forum Replies Created

Page 3 of 5
  • shradha jain

    Member
    August 21, 2018 at 9:50 am in reply to: Is apex trigger similar to validation rule in Salesforce?

    Hello Anurag,

    Validation Rule : Validation rules verify that the data a user enters in a record meets the standards you specify before the user can save the record. Validation rules also include an error message to display to the user when the rule returns a value of “True” due to an invalid value.
    Eg : A very basic validation for start date and end date, a start date cannot be greater than the end date, this can be handled using the validation rule, where you specify the formulae as (StartDate > EndDate) - Display Error ("Start Date cannot be greater than End Date"). Your record will not be saved unless you your formulae becomes false.
    Validation rules apply to new and updated records.
    You cannot perform  DML operation and many other things that a trigger can do.

    Trigger : Apex triggers enable you to perform custom actions before or after changes to Salesforce records, such as insertions, updates, or deletions. A trigger can be used to perform some update on the same record or a related record based on some business criteria, can be used to perform DML operation on other records that meet some business criteria, can be used to send email, invoke a future HTTP callout etc.
    Eg : A typical use of trigger would be to say update a contact field on Account, whenever a new Contact is inserted. To meet this requirement, you will write a trigger on contact, which will perform an update on the associated Account.

    At the end it would depend on your actual requirement, just to check if the data entered is valid, use validation rule, to perform other complex business operations, use trigger.

    Thanks.

  • shradha jain

    Member
    August 21, 2018 at 9:32 am in reply to: How can we implement a test class on map in Salesforce apex?

    Hello Anurag,

    You can refer the following example to implement a test class of Map:

    Apex Class:

    public class Task14 {

    public static void beforeupdate(Map<id,Account> oldmap,Map<id,Account> newmap){
    list<id> accid=new list<id>();
    for(id key:oldmap.keySet()){
    Account old=oldmap.get(key);
    Account newmp=newmap.get(key);
    if(old.Phone!=newmp.Phone){
    accid.add(key);
    }
    }
    list<Contact> con=[select lastname,firstname,phone,accountid from Contact where accountid in:accid];
    for(Contact c:con){
    Account a=newmap.get(c.accountid);
    Account b=oldmap.get(c.accountid);
    c.Phone=a.Phone;
    c.OtherPhone=b.phone;

    }
    update con;
    }
    }
    Trigger:

    trigger Task14Trigger on Account (before update) {
    if(trigger.isbefore && trigger.isupdate){
    Task14.beforeupdate(Trigger.oldmap, Trigger.newmap);
    }
    }

    Test Class:

    @isTest
    private class Task14_Test {

    @isTest static void beforeupdateTest() {
    Map<id,Account> oldmap = new Map<id,Account>();
    Map<id,Account> newmap = new Map<id,Account>();
    Account acct = new Account(Name='Test Account',phone='123456789');
    insert acct;
    oldmap.put(acct.id, acct);

    contact con = new contact();
    con.accountid = acct.id;
    con.LastName = 'TestContact';
    insert con;

    // Perform test
    Test.startTest();
    acct.Phone = '987654321';
    update acct;
    newmap.put(acct.id, acct);

    Task14.beforeupdate(oldmap,newmap);
    Test.stopTest();

    system.assertEquals('987654321', acct.Phone);
    }

    }

    Thanks.

  • shradha jain

    Member
    August 21, 2018 at 7:42 am in reply to: Why do we sell Salesforce opportunity as a team?

    Hello Anurag,

    Salesforce Opportunity Teams can be beneficial for you. Companies can use it to allow multiple people work on an opportunity, set their roles and grant individual access rights to each team member. By enabling Salesforce Opportunity Teams, companies can clearly define responsibilities for each sales rep as well as eliminate duplicate opportunity records.

    Using Salesforce Opportunity Team doesn’t guarantee that a company will be able to build a team sales culture. A company may need to bring in Salesforce consulting experience to effectively use advantages brought by a team. For example, some Salesforce consultants offer to replace the concept of “owner” inside the Opportunity Team with words like “primary” or “lead”. Though this update will require very little Salesforce customization, it may increase your team’s enthusiasm and their willingness to provide input into an Opportunity.

    Thanks.

  • shradha jain

    Member
    August 20, 2018 at 7:32 am in reply to: Can we use SOSL statements in Salesforce triggers?

    Hello Sanjana,

    Yes, you can write SOSL inside triggers.You can test using the following Code in your Org.
    trigger trg_AccountSOSL on Account (before insert, before update) {
    List<List<SObject>> searchList = [FIND ‘map*’ IN ALL FIELDS RETURNING Account (Id, Name), Contact, Opportunity, Lead];
    List<account> myAcc = ((List<Account>)searchList[0]);
    system.debug(myAcc[0].name);
    }

    Thanks.

  • shradha jain

    Member
    August 20, 2018 at 7:21 am in reply to: What is Salesforce DreamHouse Sample App for?

    Hello Anurag,

    DreamHouse is a sample application that demonstrates the unique value proposition of the Salesforce App Cloud for building Employee Productivity and Customer Engagement apps.

    Whether you get hundreds or millions of hits per day, App Cloud provides the deployment option that fits your needs and allows you to scale precisely to meet demand. For example, the DreamHouse sample application can be deployed using different deployment models: Force.com or Force.com + Heroku.

    For more information , you can refer the following link:

    http://www.dreamhouseapp.io/

    Thanks.

  • Hello Suniti,

    Various  Considerations while implementing triggers in Salesforce are:

    • upsert triggers fire both before and after insert or before and after update triggers as appropriate.
    • merge triggers fire both before and after delete for the losing records, and both before and after update triggers for the winning record. See Triggers and Merge Statements.
    • Triggers that execute after a record has been undeleted only work with specific objects. See Triggers and Recovered Records.
    • Field history is not recorded until the end of a trigger. If you query field history in a trigger, you don’t see any history for the current transaction.
    • Field history tracking honors the permissions of the current user. If the current user doesn’t have permission to directly edit an object or field, but the user activates a trigger that changes an object or field with history tracking enabled, no history of the change is recorded.
    • Callouts must be made asynchronously from a trigger so that the trigger process isn’t blocked while waiting for the external service's response. The asynchronous callout is made in a background process, and the response is received when the external service returns it. To make an asynchronous callout, use asynchronous Apex such as a future method. See Invoking Callouts Using Apex for more information.
    • In API version 20.0 and earlier, if a Bulk API request causes a trigger to fire, each chunk of 200 records for the trigger to process is split into chunks of 100 records. In Salesforce API version 21.0 and later, no further splits of API chunks occur. If a Bulk API request causes a trigger to fire multiple times for chunks of 200 records, governor limits are reset between these trigger invocations for the same HTTP request.

    Thanks.

  • shradha jain

    Member
    August 17, 2018 at 8:47 am in reply to: Why we use remoteaction function in Salesforce?

    Hello Parul,
    Remote action function in salesforce allows user to access any method from any class through javasrcipt methods, and get the result as a javascript object for further manipulation.The RemoteAction annotation provides support for Apex methods used in Visualforce to be called via JavaScript. This process is often referred to as JavaScript remoting.

    Thanks.

  • Hello Madhulika,

    Customers can have validation on custom fields via validation rules and triggers, so handling that in your unit tests without customer intervention is next to impossible. The first step to reducing issues is to have your test data populate all standard fields and ensure the data uses the most common formatting for your customer base (US style phone numbers and addresses for the US for example).

    Beyond that you can use the new Reflection features added to Salesforce in Summer '12 to allow customers to create unit test data classes that can be used by your managed package. Basically you define a test data generation interface and the customer creates an Apex class to generate data for you. Here's an example of using Reflection in a similar manner on the DeveloperForce blog: http://blogs.developerforce.com/developer-relations/2012/05/dynamic-apex-class-instantiation-in-summer-12.html.

    Using the method for unit tests run on install might be problematic as you'd have to have the customer create the class before they install your package and your package could only look for the class by name (or iterate through all default namespace classes and check for the correct interface). However, it's no longer necessary for unit tests to run during installation for managed packages and by default they do not.

    The Reflection method requires some coding knowledge on the customer side, but you could add a tool in your application to generate the custom unit test data class for the customer.

    FYI, it's no longer necessary for managed package unit tests to succeed in customer orgs. They're not required on install, they will no longer prevent deployment to production and they don't count as part of the customers unit test coverage percentage for purposes of deployment. The only exception to that is if the customer uses ANT and sets the runAllTests parameter to true.

    Thanks.

  • shradha jain

    Member
    August 16, 2018 at 9:08 am in reply to: What is an Escalation Rule in Salesforce?

    Hello Avnish,

    Escalation rules automatically escalate cases when the case meets the criteria defined in the rule entry. You can create rule entries, which define criteria for escalating a case, and escalation actions, which define what happens when a case escalates.

    When Salesforce applies an escalation rule to a case, it inspects the case and compares the case to the criteria in the rule entry. If the case matches the criteria defined in the rule entry, Salesforce runs the escalation actions.Orgs typically use one escalation rule that consists of multiple rule entries.

    You can setup Escalation Rule by following  the steps :

    1. From Setup, enter Escalation Rules in the Quick Find box, then select Escalation Rules.
    2.  Create the escalation rule.
      a. Click New and name the rule. Specify whether you want this rule to be the active escalation rule.
      You can have only one active escalation rule at a time.
      b. Click Save.
    3. On the Case Escalation Rules page, select the rule that you want to work with.
      The rule detail page is displayed.
    4. Create the rule entries. Rule entries define the criteria used to escalate the case.
      a. In the Rule Entries section, click New. Specify Order in which rule entries are evaluated,criteria for escalating a  case,  how business hours affect when cases escalate, how escalation times are determined.
      b. Click Save.
      The Escalation Actions page is displayed.
    5. Define the escalation actions. Escalation actions specify when the case escalates and what happens when the case escalates. You can add up to five actions for each rule entry to escalate the case over increasing periods of time.
      a.  In the Escalation Actions section, click New. For each escalation action, you can:
      Specify when the case escalates: In the Age Over field, enter the number of hours after which a case escalates if it hasn’t been closed. You can enter the number of hours and either 0 minutes or 30 minutes. For example, 1 hour and 0 minutes or 1 hour and 30 minutes.
      Reassign the case to another user or queue, and select an email template that sends the new assignee (the new case owner) a notification email.
      Send notification emails to other users, the current case owner, or other recipients.
      b. Click Save.

    Thanks.

  • shradha jain

    Member
    August 16, 2018 at 8:53 am in reply to: Do person accounts and Salesforce contacts have same IDs?

    Hello Chanchal,
    No,person accounts and Salesforce contacts do not  have same IDs.

    Thanks.

  • shradha jain

    Member
    August 16, 2018 at 5:41 am in reply to: What are Territories in Salesforce?

    Hello Anurag,

    A territory is a flexible collection of accounts and users where the users have at least read access to the accounts, regardless of who owns the account. By configuring territory settings, users in a territory can be granted read, read/write, or owner-like access (that is, the ability to view, edit, transfer, and delete records) to the accounts in that territory. Both accounts and users can exist in multiple territories. You can manually add accounts to territories, or you can define account assignment rules that assign accounts to territories for you.

    Thanks.

  • Hello Anurag,

    A lightning:tab keeps related content in a single container. The tab content displays when a user clicks the tab. Lightning:tab is intended to be used with lightning:tabset. This component creates its body during runtime. You won’t be able to reference the component during initialization. You can set your content using value binding with component attributes instead.

    Thanks.

  • Hello Anurag,

    In the column field of datatable we define the column label,fieldname and type.The columns are set using column field.

    In the Data field of datatable , the data returned from controller is set.

    Thanks.

  • shradha jain

    Member
    August 14, 2018 at 8:13 am in reply to: What is Salesforce Apex test coverage?

     

    Hello Shhanu,

    Apex Code coverage indicates how many executable lines of code in your classes and triggers have been exercised by test methods. Write test methods to test your triggers and classes, and then run those tests to generate code coverage information.To deploy Apex or package it for the Salesforce AppExchange, unit tests must cover at least 75% of your Apex code, and those tests must pass.

    Thanks.

  • Hello Avnish,

    The difference between Action support and Action function is:

    Action function :

    1.Using Action Function, we can invoke AJAX using Java script .

    2.  It provides support for invoking controller action methods directly from JavaScript code using an AJAXrequest

    3. It is used when we need to perform similar action on various events. Even though you can use it in place of      actionSupport as well where only event is related to only one control.

    Action support:

    1. Using Action Function,we can directly invoke method from controller.
    2. A component that adds AJAX support to another component, allowing the component to be refreshed asynchronously by the server when a particular event occurs, such as a button click or mouseover.
    3. It is used when we want to perform an action on a particular event of any control like onchange of any text box or picklist.
  • shradha jain

    Member
    August 14, 2018 at 4:54 am in reply to: How to make a picklist in Salesforce lightning component?

    Hello Anurag,

    tag can be used to make a picklist in lightning component.
    You can refer the following example(displaying a picklist of all the accounts):

    <aura:component controller="fetchPicklist" 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:handler>
    <aura:attribute name="accounts" type="account[]"></aura:attribute>
    <aura:attribute name="Contact" type="Contact[]"></aura:attribute>
    <aura:attribute name="recordId" type="ID"></aura:attribute>
    <aura:attribute name="columns" type="List"></aura:attribute>
    <aura:attribute name="ContactList" type="Contact[]"></aura:attribute></aura:component>

    <lightning:select label="Choose Account" name="acc" aura:id="acc"> <aura:iteration items="{!v.accounts}" var="account">
    <option value="{!account.Id}">{!account.Name}</option></aura:iteration>
    </lightning:select>

    &nbsp;

    <strong>Javascript for doInit method:</strong>

    ({
    doInit: function(component, event, helper) {

    var action = component.get("c.getAccountList");
    console.log("@@@action",action);
    action.setCallback(this, function(result){
    var accounts = result.getReturnValue();
    console.log("@@@@accounts",accounts);
    component.set("v.accounts", accounts);
    window.setTimeout(
    $A.getCallback( function() {
    component.find("acc").set("v.value", accounts[4].Id);
    }));
    });
    $A.enqueueAction(action);
    }
    })
    Apex Controller:
    global class fetchPicklist {
    public List selectedContacts{get;set;}
    @AuraEnabled global static Account[] getAccountList() {
    return [SELECT id, Name FROM Account];
    }
    }
    Thanks.

    {!account.Name}

     

    Javascript for doInit method:

    ({
    doInit: function(component, event, helper) {

    var action = component.get("c.getAccountList");
    console.log("@@@action",action);
    action.setCallback(this, function(result){
    var accounts = result.getReturnValue();
    console.log("@@@@accounts",accounts);
    component.set("v.accounts", accounts);
    window.setTimeout(
    $A.getCallback( function() {
    component.find("acc").set("v.value", accounts[4].Id);
    }));
    });
    $A.enqueueAction(action);
    }
    })
    Apex Controller:
    global class fetchPicklist {
    public List selectedContacts{get;set;}
    @AuraEnabled global static Account[] getAccountList() {
    return [SELECT id, Name FROM Account];
    }
    }
    Thanks.

    • This reply was modified 5 years, 9 months ago by  shradha jain.
  • shradha jain

    Member
    August 10, 2018 at 11:38 am in reply to: what is matrix type in a tabular Salesforce Report Format?

    Hello Chanchal,
    Matrix reports allow you to group records both by row and by column. These reports are the most time-consuming to set up, but they also provide the most detailed view of our data. Like summary reports, matrix reports can have graphs and be used in dashboards.They can be used as the source report for dashboard components. Use this type for comparing related totals, especially if you have large amounts of data to summarize and you need to compare values in several different fields, or you want to look at data by date and by product, person, or geography. Matrix reports without at least one row and one column grouping show as summary reports on the report run page.
    Thanks.

  • shradha jain

    Member
    August 10, 2018 at 11:33 am in reply to: Who are the live agent users in Salesforce?

    Hello Prachi,
    Live Agent users are support agents and supervisors who have the Salesforce permissions to assist customers with chat.
    All Live Agent users need the API Enabled administrative permission enabled on their associated profile before they can use Live Agent.

    1. From Setup in Salesforce Classic, enter Users in the Quick Find box, then select Users.
    2. Click Edit next to a user’s name.
    3. Select Live Agent User. If you don’t see this checkbox, verify that your support organization has purchased enough Live Agent feature licenses.
    4. Click Save.
    After creating users, make sure that you assign them a Live Agent configuration and associate them with the appropriate skills.

    Permissions for Live Agent Support Agents:
    Enable a few specific permissions for Live Agent support agents so that they have access to the tools that they need to provide help to customers.
    Permissions for Live Agent Support Supervisors:
    You must enable certain permissions for Live Agent support supervisors so that they have all the tools they need to monitor agents’ activities and review customers’ information.
    Thanks.

  • Hello Anjali,
    Yes, it is possible to make restriction during the approval process so that approvers cannot submit a request.
    To make this possible you can do the following:
    You could create Public Groups, one for record submitter and other for approvers . And in the Select Assigned Approver screen you will assign user or queue who can approve this(Make sure, same users should not be listed in submitter and approver groups).
    Thanks.

  • shradha jain

    Member
    August 10, 2018 at 11:24 am in reply to: What is the need for Territory Management in Salesforce?

    Hello Prachi,
    Territory Management is a tool that provides specific and flexible security control for accounts and children of accounts. Security control for Territory Management can be based on any field within accounts. With the Veeva CRM application you will likely use Territory Management to control security to your accounts and use the Role Hierarchy to control security to other objects.Particularly if your organization has a private sharing model, you may need to grant users access to accounts based on criteria such as postal code, industry, revenue, or a custom field that is relevant to your business. You may also need to generate forecasts for these diverse categories of accounts. Territory management solves these business needs and provides a powerful solution for structuring your users, accounts, and their associated contacts, opportunities, and cases.

    Salesforce Handles Territory Management allows you to manage the roll-up of information among your company's territories. The hierarchy structure is not based on traditional titles, but rather on a hierarchy of roles. Multiple people with different titles can be assigned to the same role. Users always have access to the data that is owned by or shared with users assigned to roles below them in the hierarchy. A user’s role also determines which data is accessible to him or her in forecasts.
    You can refer the following link for more information:
    https://help.salesforce.com/articleView?id=faq_getstart_how_does_salesforce.htm&type=5
    Thanks.

  • shradha jain

    Member
    August 9, 2018 at 11:58 am in reply to: How can we add a field in object using Salesforce trigger?

    Hello Madhulika,
    You can refer the following example:

    1. Account (Parent Object)
    2. Contact (Child Object).
    3. Contact_Recs__c (Roll up summary field/Custom Field).
    4. accountid (Lookup field).

    Trigger Code:

    trigger CountContactsnew on Contact (after insert, after delete, after undelete) {

    List accIdList = new List();
    if(Trigger.isInsert || Trigger.isUndelete){
    For(Contact con1 : Trigger.new){
    accIdList.add(con1.accountid);
    }
    }
    if(Trigger.isDelete){
    For(Contact con1 : Trigger.old){
    accIdList.add(con1.accountid);
    }
    }
    List accUpdateList = new List();
    For(Account acc : [SELECT Contact_Recs__c,(SELECT id FROM Contacts) FROM Account WHERE id =: accIdList]){
    acc.Contact_Recs__c = acc.Contacts.size();
    accUpdateList.add(acc);
    }
    try{
    update accUpdateList;
    }Catch(Exception e){
    System.debug('Exception :'+e.getMessage());
    }
    }
    Thanks.

  • shradha jain

    Member
    August 9, 2018 at 5:23 am in reply to: How to decide which Salesforce automation tool to use?

    Hello Chanchal,

    The best automation tool for your needs depends on the type of business process that you’re automating.

    • Approval Process: Use approval process when a record needs approval.
    • For Example: Managers approve their direct reports’ requests for vacation.

    • Process Builder: Use Process Builder when you need to start a behind-the-scenes business process automatically. Processes can start when:

    1. A record is created
    2.  A record is updated
    3.  A platform event occurs

    • Cloud Flow Designer: Use Cloud Flow Designer to automate a guided visual experience.Add more functionality for a behind-the-scenes process than is available in Process Builder. Build the more complex functionality in the Cloud Flow Designer. Then call the resulting flow from the process.Start a behind-the-scenes business process when a user clicks something, like a button.

    For example, when an opportunity is won, your company wants a renewal opportunity to be created automatically.As you see later in this module, you can build parts of that use case as a process, but the rest has to be built in a flow.

    • Apex: Use Apex when you need more functionality than is available in Process Builder or Cloud Flow Designer. Build the more complex functionality as invocable Apex methods. Then call the resulting Apex as an Apex action in the process or as an Apex element in the flow.
    • WorkFlow Rules: Process Builder includes almost all the functionality that’s available in workflow rules, and more. In fact, a single process can do what it would normally take multiple workflow rules to do. The only thing you can do with workflow that you can’t do with processes is send outbound messages without code.

    Thanks.

  • shradha jain

    Member
    August 8, 2018 at 7:27 am in reply to: How to create a Chatter post from Apex in Salesforce?

    Hello Avnish,

    You can refer the following example to add Salesforce Chatter posts with links, urls and mentions:
    public with sharing class ChatterUtils {
    // makes a simple chatter text post to the specified user from the running user
    public static void simpleTextPost(Id userId, String postText) {
    ConnectApi.FeedType feedType = ConnectApi.FeedType.UserProfile;
    ConnectApi.MessageBodyInput messageInput = new ConnectApi.MessageBodyInput();
    messageInput.messageSegments = new List<ConnectApi.MessageSegmentInput>();

    // add the text segment
    ConnectApi.TextSegmentInput textSegment = new ConnectApi.TextSegmentInput();
    textSegment.text = postText;
    messageInput.messageSegments.add(textSegment);
    ConnectApi.FeedItemInput feedItemInput = new ConnectApi.FeedItemInput();
    feedItemInput.body = messageInput;

    // post it
    ConnectApi.ChatterFeeds.postFeedItem(null, feedType, userId, feedItemInput, null)

    }

    // makes a chatter post with some text and a link
    public static void simpleLinkPost(Id userId, String postText, String url, String urlName) {
    ConnectApi.FeedItemInput feedItemInput = new ConnectApi.FeedItemInput();
    feedItemInput.body = new ConnectApi.MessageBodyInput();

    // add the text segment
    ConnectApi.TextSegmentInput textSegment = new ConnectApi.TextSegmentInput();
    feedItemInput.body.messageSegments = new List<ConnectApi.MessageSegmentInput>();
    textSegment.text = postText;
    feedItemInput.body.messageSegments.add(textSegment);

    // add the attachment
    ConnectApi.LinkAttachmentInput linkIn = new ConnectApi.LinkAttachmentInput();
    linkIn.urlName = urlName;
    linkIn.url = url;
    feedItemInput.attachment = linkIn;

    // post it!
    ConnectApi.ChatterFeeds.postFeedItem(null, ConnectApi.FeedType.News, userId, feedItemInput, null);

    }

    // makes a simple chatter text post to the specified user from the running user
    public static void mentionTextPost(Id userId, Id userToMentionId, String postText) {
    ConnectApi.MessageBodyInput messageInput = new ConnectApi.MessageBodyInput();
    messageInput.messageSegments = new List<ConnectApi.MessageSegmentInput>();

    // add some text before the mention
    ConnectApi.TextSegmentInput textSegment = new ConnectApi.TextSegmentInput();
    textSegment.text = 'Hey ';
    messageInput.messageSegments.add(textSegment);

    // add the mention
    ConnectApi.MentionSegmentInput mentionSegment = new ConnectApi.MentionSegmentInput();
    mentionSegment.id = userToMentionId;
    messageInput.messageSegments.add(mentionSegment);

    // add the text that was passed
    textSegment = new ConnectApi.TextSegmentInput();
    textSegment.text = postText;
    messageInput.messageSegments.add(textSegment);

    ConnectApi.FeedItemInput input = new ConnectApi.FeedItemInput();
    input.body = messageInput;

    // post it
    ConnectApi.ChatterFeeds.postFeedItem(null, ConnectApi.FeedType.UserProfile, userId, input, null);

    }

    // pass the user's id or 'me' to get current running user's news
    public static ConnectApi.FeedItemPage getNewsFeed(String userId) {
    return ConnectApi.ChatterFeeds.getFeedItemsFromFeed(null, ConnectApi.FeedType.News, userId);
    }

    }

  • shradha jain

    Member
    August 8, 2018 at 6:36 am in reply to: What is the reason for “Object cannot be Deleted” error?

    Hello Avnish,

    The error “Object cannot be Deleted”  means you are using it somewhere else For e.g Active Trigger on Object or Using in Workflow. You can check its usage and then delete it.

    Thanks.

  • shradha jain

    Member
    August 8, 2018 at 5:14 am in reply to: Why we use "System.runAs" in test class in Salesforce?

    Hello Chanchal,

    Generally, all Apex code runs in system mode, where the permissions and record sharing of the current user are not taken into account. The system method runAs enables you to write test methods that change the user context to an existing user or a new user so that the user’s record sharing is enforced. The runAs method doesn’t enforce user permissions or field-level permissions, only record sharing. You can create new users with runAs even if your organization has no additional user licenses.

    You can refer the following example:

    @isTest
    private class TestRunAs {
    public static testMethod void testRunAs() {
    // Setup test data
    // Create a unique UserName
    String uniqueUserName = 'standarduser' + DateTime.now().getTime() + '@testorg.com';
    // This code runs as the system user
    Profile p = [SELECT Id FROM Profile WHERE Name='Standard User'];
    User u = new User(Alias = 'standt', Email='[email protected]',
    EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US',
    LocaleSidKey='en_US', ProfileId = p.Id,
    TimeZoneSidKey='America/Los_Angeles',
    UserName=uniqueUserName);

    System.runAs(u) {
    // The following code runs as user 'u'
    System.debug('Current User: ' + UserInfo.getUserName());
    System.debug('Current Profile: ' + UserInfo.getProfileId());
    }
    }
    }

    Thanks.

Page 3 of 5