Saturday 17 November 2018

                                             Design Attribute In Salesforce:


Community1:
<aura:component implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes" access="global" >
 
    <aura:attribute name = "Name" type = "String"/>
    <aura:attribute name = "Phone" type = "String" />
    <aura:attribute name = "Position" type ="String"/>
    <p>
        Name: {!v.Name}
    </p>
    <p>
        Number: {!v.Phone}
    </p>
    <p>
        Position: {!v.Position}
    </p>
</aura:component>

Design Attributes:

<design:component  >
   <design:attribute name ="Name" label="Name"></design:attribute>
    <design:attribute name ="Phone" label="Phone Number"></design:attribute>
    <design:attribute name ="Position" label="Position" datasource = "CEO, President, Manager"></design:attribute>
</design:component>


 Design Attribute value  Specification:


If we add label for design attributes,component will change to design attribute name

<design:component label="design Practise" >
   <design:attribute name ="Name" label="Name"></design:attribute>
    <design:attribute name ="Phone" label="Phone Number"></design:attribute>
    <design:attribute name ="Position" label="Position" datasource = "CEO, President, Manager"></design:attribute>
</design:component>




Saturday 10 November 2018


How to find the field data type of particular Object:

In this example,I had taken account as a example

String objType='Account';
Map<String, Schema.SObjectType> schemaMap = Schema.getGlobalDescribe();
Schema.SObjectType leadSchema = schemaMap.get(objType);
Map<String, Schema.SObjectField> fieldMap = leadSchema.getDescribe().fields.getMap();
system.debug('field map keyset'+fieldMap.keyset());
system.debug('values###'+fieldMap.values());
for (String fieldName: fieldMap.keySet()) {
//for finding name of the field 
String fieldLabel = fieldMap.get(fieldName).getDescribe().getLabel();
 system.debug('fieldLabel>>>>>'+fieldLabel);
//get data types for each fields like string,datetime etc..
Schema.DisplayType fielddataType = fieldMap.get(fieldName).getDescribe().getType();
    //system.debug('fieldtype>>>'+fielddataType);
    if(fielddataType == Schema.DisplayType.DateTime) {
system.debug('field type*********'+fielddataType);
}
}

Friday 9 November 2018


$Browser in Lightning Component:


The $Browser global value provider returns information about the hardware and operating system of the browser accessing the application.

<aura:component>
    {!$Browser.isTablet}
    {!$Browser.isPhone}
    {!$Browser.isAndroid}
    {!$Browser.formFactor}
</aura:component>

Browser.App
<aura:application extends="force:slds">
    <c:BrowserComponent/>
</aura:application>

I am accessing application through desktop.

Output:
falsefalsefalseDESKTOP


LINK:

https://developer.salesforce.com/docs/atlas.en-us.lightning.meta/lightning/expr_browser_value_provider.htm

Thursday 1 November 2018

How Get record in in lightning component in communities


force:hasRecordId is meant only for the Lightning experience and App builder and not the community builder .

<design:component>
   <design:attribute name="recordId" label="recordId" description="Salesforce Id of the record" />
 </design:component>

Create an attribute mapping to the design variable
<aura:component implements="forceCommunity:availableForAllPageTypes,force:appHostable,flexipage:availableForAllPageTypes">

 <!--ATTRIBUTES DECLARATION -->

 <aura:attribute name="recordId" type="String" default="{!recordId}"/>
   <aura:handler name="init" value="{!this}" action="{!c.getrecord}" />
 </aura:component>
Lets get the Id now in our JS controller
({
   getresults: function(component, event, helper) {
    console.log(component.get("v.recordId"));//print the Id 

  }
})

Saturday 20 October 2018

Permission Subscribe to Dashboards: Add Recipients depends on permission(s): Subscribe to Dashboards

I am creating custom standard Admin profile using clone Option, I try to change field access on  custom standard Admin profile I have received the following error.

While saving:

Permission Subscribe to Dashboards: Add Recipients depends on permission(s): Subscribe to Dashboards

workaround:

1) Go to Manage Users --> User Management Settings
2) Disable the Enhanced Profile User Interface setting
3) Go back to the Profile and Save it

Wednesday 10 October 2018


Trigger to prevent creation of duplicate accounts


trigger AccountDuplicateTrigger on Account (before update) {
//For fetching existing account names
     map<Id,Account> existingAccountMap = new  map<Id,Account>([Select Id, Name, Rating From Account]);
 for(Account a : Trigger.new){
        if(a.name = existingAccountMap.get(a.Id).Name){
          a.adderror('You cannot create a dulplicate account');
        }
     }
}

Monday 17 September 2018

Unable to find process builder processes in change set :


You need to select Flow Definition in Component Type. Also you need to activate process builder in production after deployment.



Thursday 13 September 2018

                             Queueable Apex:


Queueable Apex is similar to future methods, but provide additional job chaining and allow more complex data types to be used.

Queueable Apex allows you to submit jobs for asynchronous processing similar to future methods with the following additional benefits:
  • Non-primitive types: Your Queueable class can contain member variables of non-primitive data types, such as sObjects or custom Apex types. Those objects can be accessed when the job executes.
  • Monitoring: When you submit your job by invoking the System.enqueueJob method, the method returns the ID of the AsyncApexJob record. You can use this ID to identify your job and monitor its progress, either through the Salesforce user interface in the Apex Jobs page, or programmatically by querying your record from AsyncApexJob.
  • Chaining jobs: You can chain one job to another job by starting a second job from a running job. Chaining jobs is useful if you need to do some sequential processing.
---------------------------------------------------------------------------------------------------------------------
Queueable Apex:

public class QueueableExample implements Queueable {
public void execute(QueueableContext context) {
        Account a = new Account(Name='Annappa',Phone='11111111');
       insert a;     
    }
}
----------------------------------------------------------------------------------------------------------------------
Execute:

ID jobID = System.enqueueJob(new QueueableExample());
system.debug(jobId);

-------------------------------------------------------------------------------------------------------------------------

Eliminate bad code coverage data for Apex classes:


Issue: There may be times where we see a different code coverage value than the actual value. This might be caused due to bad code coverage data or aggregate results from previous test runs.

Solution: To eliminate any bad code coverage data in your organization you can follow the steps mentioned below.

For Classic:
---------------------------------------------------------------------------------
First re-run all tests in your organization: 
---------------------------------------------------------------------------------
1a) Setup | Develop | Apex Test Execution
  b) View Test History
  c) Clear test data.

2 a) Setup | Develop | Apex Classes
  b) Compile all classes

3 a) Setup | Develop | Apex Test Execution
 b) Select tests | "My Namespace" | Select all
 c) Click run

4 a) Setup | Develop | Apex Classes
  b) Estimate your organization's code coverage

  ---------------------------------------------------------------------------------
To Remove Bad data:
---------------------------------------------------------------------------------
1 a) Open Developer console
  b) Execute the following query in "Query Editor" with "Tooling API" checked.

SELECT Id, NumLinesUncovered FROM ApexCodeCoverageAggregate WHERE NumLinesUncovered = NULL

c) Select all the returned rows and hit "Delete Row"
d) Try to estimate the code coverage again
---------------------------------------------------------------------------------

                        Error while updating debug log trace flag


Some times we will receive below error while setting  debug log trace flag for user

"Having an active trace flag triggers debug logging. You have 259 MB of the maximum 250 MB of debug logs. Before you can edit trace flags, delete some debug logs."

Solution:

  • In dev console, Select tab "Query Editor" at the bottom of the console
  • Select check box "Use Tooling API"
  • Use this query: SELECT Id FROM ApexLog
  • Delete all rows

Once all rows are deleted you will be able to save new debug logs.

Monday 3 September 2018

Replacing the Picklist old values into new values


Suppose we have a picklist (Test) which contains A,B,C values. For example A belongs to 100 records,B belongs to 200 records and C belongs to 300 records respectively.

Picklist Name: Test

A---- 100
B-----200
C-----300

Now we have new requirement: Instead of "A",we need to update with "D".This means all 100 records belongs to "A" replace with "D"



How to do it?

Using "Replace" option we can do it




Will the updated record fire Apex Triggers, Workflow Rules, etc.?

workflow rules, triggers, validation rules, flows, Process Builders, and any other logic that would run on a normal DML operation will not run as a result of using Replace.

Dynamically Determine Calling Context:

In some cases we need to Identify the calling context  whether its called from trigger,batch,future methods  etc..

These are the steps to determine it:

Batch - System.isBatch()
@future - System.isFuture()
Queueable - System.isQueueable()
Schedulable - System.isScheduled()
Trigger - Trigger.isExecuting

For example:
Consider  batch class Example:
if(System.IsBatch() == true){
    //Its calling from batch
}

More Information:

https://salesforce.stackexchange.com/questions/131140/dynamically-determine-calling-context

Wednesday 29 August 2018

Soql Queries and Sub Queries


In the below query there are total 3 subqueries + 1 parent query. So, there are 4 queries. But, Salesforce doesn't count subqueries against governor limit of 100 SOQLs. It counts only root query which means only 1 SOQL query would be consumed.


List<Account> dd = [
    SELECT
        id,
        (SELECT Name FROM Contacts),  // <- first subquery
        (SELECT AccountID FROM Cases) // <- second subquery
    FROM
        Account
    WHERE
        id
    IN (SELECT AccountID FROM Case)   // <- not counted
];


Subqueries are counted separately as AggregateQueries. You can check those with Limits.getAggregateQueries() and Limits.getLimitAggregateQueries(). You cannot have more than 300 aggregations in a single transaction.

For example: Org contain  only 2 Account and each have 10 Contacts.

 If you execute this with sub Query like below

Select Id, Name, (Select Id, Name from Contacts) From Account

Then the total number of Query rows will be 22 (2+10+10).

 From above analogy we can understand like this:

 If your org contain 40M accounts and each have 1 contact.

Then in this scenario you can use sub query up to 25M only.

 Like this Select Id, Name, (Select Id, Name from Contacts) From Account limit 25M

Monday 20 August 2018

will System.debug, if left in production, affect performance ?


Code executed, including System.Debug and System.assert (and their variants) have the following effects:

1) They increase debug log sizes.
2) They increase script execution time (but insignificantly).
3) They count against governor limits.

The final bullet point is your most troubling concern. A loop against 1000 records with 10 debug statements will have a total of 10,000 extra script statements than the one without.

The salesforce.com best practices state that you should always remove or comment debug statements for production code

Monday 13 August 2018

Test.setup:



  • @testSetup ( Set Up Test Data for an Entire Test Class )Use test setup methods (methods that are annotated with @testSetup) to create test records once and then access them in every test method in the test class.
  • Test setup methods can reduce test execution times especially when you’re working with many records
  • Test setup methods enable you to create common test data easily and efficiently.
  • Test setup methods enable you to create common test data easily and efficiently.

@isTest
private class CommonTestSetup
{
 @testSetup
 static void setup()
 {
  Account acct = new Account();
       acct.Name = 'Salesforce.com';
       acct.Industry = 'Technology';
  insert acct;

  Contact cont = new Contact();
       cont.FirstName = 'Annappa';
       cont.LastName = 'ph';
       cont.AccountId = acct.Id;
  insert cont;
 }
 
 @isTest
 static void testMethod1()
 {
  Account acct = [SELECT Id FROM Account WHERE Name='Salesforce.com' LIMIT 1];
     acct.Phone = '555-1212';
  update acct;
 }

 @isTest
 static void testMethod2()
 {
  Account acct = [SELECT Phone FROM Account WHERE Name='Salesforce.com' LIMIT 1];
  System.assertEquals(null, acct.Phone);
 }
}

Note:

If a test class contains a test setup method, the test setup method executes first, before any test method in the class.
Multiple @testSetup methods are allowed in a test class, but the order in which they’re executed by the testing framework isn’t guaranteed
If the test class or a test method has access to organization data by using the @isTest(SeeAllData=true) annotation, test setup methods aren’t supported in this class.
 Date Formats and Date Literals
                                                 

DateTime field values are stored as Coordinated Universal Time (UTC).

When a dateTime value is returned in Salesforce, it’s adjusted for the time zone specified in your org preferences.

If you want to process these values in different time zones, your application might need to handle the conversion.

For a fieldExpression that uses date formats, the date is not enclosed in single quotes. Don’t use quotes around the date.

For example:

SELECT Id
FROM Account
WHERE CreatedDate > 2016-10-08T01:02:03Z

Date Literals:

Simple Queries:



 SELECT Id FROM Account WHERE CreatedDate = YESTERDAY

SELECT Id FROM Account WHERE CreatedDate > TODAY

SELECT Id FROM Opportunity WHERE CloseDate = TOMORROW

SELECT Id FROM Account WHERE CreatedDate > LAST_WEEK

SELECT Id FROM Account WHERE CreatedDate < THIS_WEEK

SELECT Id FROM Account WHERE CreatedDate < THIS_MONTH

SELECT Id FROM Account WHERE CreatedDate = LAST_90_DAYS

Saturday 11 August 2018

Salesforce Basics :



Using same List for Update:

List<Account> acList=[select id,name from account limit 2];
system.debug('>>>acList>>>>'+acList);
for(account ac:acList){
    ac.name='Test';
}
system.debug('before update List>>'+acList);
update acList;

Here "acList" contains Updated value



Will It Updates.Parents name field?

List<Contact> contactList=[select id,accountId,account.name from contact limit 2];
for(contact c:contactList){
c.account.name='Update Parent Account';
}

update contactList;

Ans: It will not








Nested usage of Map and List


Map<String, Integer> TestMap = new Map<String, Integer>();
TestMap.put('Hello', 100);
TestMap.put('World', 200);
TestMap.put('Witch', 200);
TestMap.put('Salesforce', 100);
TestMap.put('sfdcinpractice.com', 100);

Map<Integer, List<String>> TestWordMap = new Map<Integer, List<String>>();
for(String curWord: TestMap.keySet())
{
    system.debug('curWord>>>>'+curWord);
    Integer curPage = TestMap.get(curWord);
    system.debug('>>curPage>>>'+curPage);
    if(!TestWordMap.containsKey(curPage))
    {
        TestWordMap.put(curPage, new List<String>()); //We need to initialise the list
    }
    system.debug('@@@@TestWordMap@@@@'+TestWordMap);
    TestWordMap.get(curPage).add(curWord); //TestWordMap.get(curPage) is a list here
    system.debug('#####TestWordMap####'+TestWordMap);
}

Monday 30 July 2018

Apex Batch - Is execute method called if start returns 0 results?


No. Execute will not be called unless at least one non-null item is available for processing. "scope" will never be empty or null, because execute won't be called if there's nothing to do.

Saturday 21 July 2018

How to save map with List as child and Id as parent
In this following Example,I had taken case as a example
Map<Id, List<Case>> parentChildCase = new Map<Id, List<Case>>();
Map<ID, Case> childMap = new Map<ID, Case>([SELECT Id, ..., FROM Case]);

for(ID c : childMap .keySet())
{
    if(parentChildCase.containsKey(childMap .get(c).ID))
    {
        parentChildCase.get(cMap.get(c).ID).add(childMap .get(c));
    }
    else
    {
        List<Case> cases = new List<Case>();
        cases.add(childMap .get(c));
        parentChildCase.put(childMap .get(c).ID, cases);
    }
}


Thursday 19 July 2018

Apex Code Coverage Hack


Declaimer: please be aware that all things into this article are “bad practice” and should not be used constantly, it might be used for a really urgent production deployment when you have faced with a broken tests and as a result a code coverage has dropped down than 75% and you has been blocked.

As you know salesforce requires at least 75% test coverage for production deployment. You can find the following statement in documentation:

The code coverage percentage for a class or trigger displayed on the Apex Classes or the Apex Triggers page includes a fraction between parentheses with the numbers used to compute this percentage, for example, 90% (72/80). The code coverage percentage is calculated by dividing the number of lines covered by tests by the total number of lines that are part of the coverage calculation. Some lines of code are excluded from code coverage calculation, such as:


  • Comments
  • System.debug statements
  • Test methods

A code statement that is broken up into multiple lines—only the first line is counted
To generate code coverage results, you must run your Apex tests first. If no tests have been run, no code coverage data will exist and 0% (No coverage data) displays for classes (except for test classes) and triggers on the Apex Classes and Apex Triggers pages.

Cool! The code coverage calculation is pretty simple and we can cheat the system. Just use the following code


/*
Please improve your tests and remove this class as soon as possible
*/
public class CodeCoverageHack {
    public static void hack() {
        Integer i = 0;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        // you can continue this method with i++; up to 3000 lines
        // after that you would be stoped by limit of size
        // but you can create a few such methods
 }

    public static void hack1() {
         // do the same thing ...
    }

    @isTest static void runTest() {
        CodeCoverageHack.hack();
        CodeCoverageHack.hack1();
        //...
        CodeCoverageHack.hackN();
    }
}
That’s all.   ✌

How to run future method in test class


We have to use future method inside the  startTest/stopTest:

Test.startTest();
myClass.futuremethod( someID );
Test.stopTest();

Test.stopTest() does not return until your future method has completed.

How to find in which  release my org is running?


On the Home tab, on the top right of the screen is a link to Summer 18 for Developers. This indicates our org release.


Wednesday 18 July 2018


How to add your Company Logo  in salesforce home Tab:

Login into your salesforce account,

upload the image under documents tab
  • Go to yourname --> setup -->appsetup -->Customize-->homepage component 
  • Under the custom component click New and then click next 
  • Give the Name as Logo and select the type as image, click next
  • Click the insert image button and select the image/logo file
  • Then click save
Now we are successfully uploaded logo into salesforce, next step is we need to enable the custom component in the home page layout
  • Go to yourname --> setup -->appsetup -->Customize-->homepage layout
  • Click edit the layout
  • Then select our component after that click next
  • Move our custom component in the top of the left side column
  • Then click the save button  
That's it, We are done! Company logo is added into your salesforce account click the Home button.


Custom Label

These are custom text value that can be accessed from Apex classes or Visual force pages. These values can be translated into any language Salesforce supports. 

Custom labels enable developers to create multilingual applications by automatically presenting information (for example, help text or error messages) in a user’s native language. 

Limitation

You can create up to 5,000 custom labels for your organization, and they can be up to 1,000 characters in length.

How to access custom label in visualforce page:
{!$Label.demolabel}

How to access custom label in Apex classes:

System.Label.Label__Name;

For In my example:
System.Label. demolabel

Tuesday 17 July 2018


Customize error message for trigger and display error message below the field

This Post demonstrates how to display error message in particular field level.

SObject SomeRecord;
SomeRecord.SomeField__c.addError('Custom Message');
//or
SomeRecord.someField__c.addError(someException);

Note:

We cannot add it to a field dynamically. This error mapping can only be done with a hard-coded field.


aura:method in Salesforce


  • This enables you to directly call a method in a component’s client-side controller instead of firing and handling a component event.
  • Using <aura:method> simplifies the code needed for a parent component to call a method on a child component that it contains. 
ParentComp:


<aura:component description="parentComponent" access="global" implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes">
    <c:childComponent aura:id="childQuestion"/>
    <button type="button" aura:id="saveAndReturn" class="slds-button" onclick="{!c.save}">Save and return
    </button>  
</aura:component>

Controller:

({
    save : function(component,helper,event){
 var childComponent = component.find("childQuestion");
        childComponent.getScoreMethod('aa','bb','cc');
    }
})


childComponent.cmp


<aura:component description="childComponent" access="global">
    <aura:method name="getScoreMethod" action="{!c.calcScore}" access="PUBLIC">
        <aura:attribute name="contactId" type="String" />
        <aura:attribute name="contactName" type="String"  />
        <aura:attribute name="recordId" type="String"  />
    </aura:method>

</aura:component> 


({
    calcScore : function(component,event,helper){
        var args = event.getParam("arguments");
        var contactId = args.contactId;
        var contactName = args.contactName;
        var recod=args.recordId;
       alert('Inside Calc Score: ' + contactId + ' - ' + contactName+'-'+recod);
    }
})


Application:


<aura:application >
 <c:ParentComp/>
</aura:application>


Custom setting Setting type not visible




You Can enable list custom setting schema Setting Page
Setup > schema Setting Page > List custom Setting




After Enabling,