Wednesday, 15 August 2018

Apex Basics

Apex is a strongly typed,object -oriented programming language that allows developers
to execute flow and transaction control statements on the Force.com platform.

Apex enables developers to add business logic to most system events,including button clicks,
related record updates and visualforce pages.

Data Types :
============
1.primitives
2.sObjects
3.Collections

Apex primitive data types include :

1.Boolean : can only be assigned true,false or null
2.Decimal : A number that includes a decimal points.
3.Double : A 64-bit number that includes a decimal point
4.ID : Any Valid salesforce.com ID
5.Integer : A 32bit number that does not include a decimal point.
6.Long : A 64-bit number that does not include a decimal point.
7.String : Any set of characters surrounded by single quotes.
8.Date : A value that indicates a particular day.
9.DateTime : A value that indicates a particular day and time
10.Time : A value that indicates a particular time.

sObjects :
=============
the term sObject refers to any object that can be stored in the Force.com platform database.

An sObject variable represents a row of data and can only be declared in Apex.

ex :
Contact c= new Contact(FirstName='raj';LastName='kiran';
Email ='test@gmail.com');

Account a =new Account(Name='TCS');
insert a;

Account a1=[select Name from Account
where ID='857598jh'];
a1.Name='new  Name';
update a1;

Collection :
============
collection of primitives or sObjects.

A LIST is an ordered collection.so use
list when you wnat to identify list element
based on INDEX NUMBER.
List can contain duplicates.

List<string> colors =new List<string>('red','purple','green');

List<Account> accts=[select Name,Type from Account
where Industry='Energy'];

List<Contact> email_contacts=
[select FirstName,LastName from Contact where
Email!=Null];

1. Set
2. List
3. Map

A set is a collection of unique,unordered elements.it can contain primitive data types or sObjects.

A set is an unordered collection of primitives or sObjects that do not contain any duplicate elements.so use SET if you want to make sure that your collection should not conatin Duplicates.

ex :
Set<String> s = new Set<String>();
Set<String> s = new Set<String>{'Jon', 'Quinton', 'Reid'};

commonly you'll see developers construct a set of IDs from a query,trigger context,etc.
and the use it as part of WHERE clause in their SOQL query.

ex :

Set<ID> ids = new Set<ID>{'0017000000cBlbwAAC','0017000000cBXCWAA4'};
List<Account> accounts = [Select Name From Account Where Id = :ids];


Map :
=====
A MAP is a collection of key-value pairs where each unique key maps to a single value.
Keys can be any primitive data type,while values can be a primitive,sObject,Collection
types or an Apex Object.

Use a map when you want to quickly find something by a key.Each key must be unique
but you can have duplicate values in your MAP.

Map<Integer, String> m = new Map<Integer, String>{5 => 'Jon', 6 => 'Quinton', 1 => 'Reid'};
Map<ID, Set<String>> m = new Map<ID, Set<String>>();
// creates a map where the key is the ID of the record
Map<Id,Account> aMap = new Map<Id, Account>([Select Id, Name From Account LIMIT 2]);


Tuesday, 14 August 2018

Triggers in Salesforce


Trigger is piece of code that is executes before and after record is Insert/update/Deleted from the force.com database.

There are two types of Triggers:

1.Before trigger are used to update or validate record values before they're saved to the
database.

2.After triggers are used to access field values that are set by the system and to effect changes in other records.The records that fire the after trigger are read-only.

syntax:
========

trigger triggerName on ObjectName(trigger_events)
{

  //code_block

}

where trigger_events can be a comma-separated list of one or more of the following events :

before insert
before update
before delete
after insert
after update
after delete
after undelete

ex :
========
check email null or not before insert update
record


trigger CheckEmail on contact(before Insert,before update)
{
   for(Contact c:Trigger.new)
   {
     if(c.Email ==Null)
      {
        c.Email.addError('Please insert Emil ID);
      }
   } 
}

Trigger Context Variables :
=====================
All triggers define implicit variables that allow developers to access run-time context.


Trigger.isInsert : Returns true if this trigger was fired due to an insert operation.

Trigger.isUpdate : Returns true if this trigger was fired due to an update operation

Trigger.isDelete : Returns true if this trigger was fired due to delete operation.

Trigger.isBefore : Returns true if this trigger was fired before any record was saved.

Trigger.isAfter : Returns true if this trigger was fired after all records were saved.

Trigger.isUndelete : Returns true if this trigger was fired after a record is recovered from the
Recycle Bin.

Trigger.new : Returns a list of the new versions of the sObject records.Note that this sObject list
is only available in insert and update triggers,and the records can only be modified
in before triggers.

Trigger.newMap : A map of IDs to the new versions of the sObject records.Note that this map
is only available in before update,after insert and after update triggers.

Trigger.old : Returns a list of the old versions of the sObject records.Note that this sObject
list is only available in update and delete triggers.

Trigger.oldMap : A map of IDs to the old versions of the sObject records.Note that this map
is only available in update and delete triggers.

Trigger.size: The total number of records in a trigger invocation,both old and new.

Trigger.isExecuting : Returns true if the current apex code is a trigger.


ex :


trigger Opportunity_trigger on Opportunity(before insert,before update){

  for(Opportunity p : Trigger.new)
  {
    if(Trigger.isInsert && p.amount<10000)
      {
       p.addError("amount is less than 10000');
      }
    else if(Trigger.IsUpdate && p.Amount<20000)
         {
           p.addError('Amount is less than 20000');
         }

  }

}

ex :

  public class trigger_class{
    public static void trigger_method(List<Opportunity> oppt){

        Double Total_amount=0;
      for(Opportunity o : Select Amount from opportunity where createddate=Today()
                               and CreatedById= : UserInfo.getUserID()]){
         
           Total_amount=Total_Amount +o.Amount;
       
           }

        for(Opportunity o1 : oppt){
         
           Total_amount=Total_Amount +o1.Amount;
       
              if(Total_amount>100000)
                {
                  01.addError('you have exceeded your daily limit');
                }
            }

    }

  }


trigger t1 on Opportunity(before Insert){
trigger_class.trigger_method(Trigger.new);
}

Transaction Control using Database savepoint and rollback in Apex

SavePoint and Rollback will help us to maintain transaction for DML statement.

suppose you have written multiple lines of DML statements in a try block,if any error
occurs during DML Operations,the operation will be rolled back to the most recent
save point and the entire tranasction will not be aborted.

ex :

savepoint sp=Database.setsavepoint();

try
{
// create account

Account a=new Account();
a.Name='Test';
insert a;

// create contact

Contact c=new contact();
a.accountid=a.id;
insert c;

}
catch(DMLException exc)
{

Database.rollback(sp);

}

In this example, if any error occurs while inserting the Account ‘a’ or Contact ‘c’, then the entire transaction will be rolled back to SavePoint ‘sp’, as specified in the catch section by Database.

Friday, 27 July 2018

Relationships available in Salesforce

A relationship is an association among the objects. We can categorize the relationships into three kinds
1. One-to-One, 2. One-to-Many, and 3. Many-to-Many. But Salesforce supports only One-to-Many relationship in 2 flavors among the sObjects.
Salesforce offers One-to-Many relationship as following types,
1. Master-Detail relationship
2. Lookup relationship

In addition to those, Salesforce offers two more Special relationships called Self relationship, and Hierarchical relationships.

Though, Salesforce doesn't offer Many-to-Many relationship, we can achieve this using two One-to-Many relationships(We discuss it later).

1. Master-Detail relationship
            An association which tightly couples the Parent(Master) object and Child(Detail)  object [and Sub Detail object] is called Master-Detail relationship. What does Tight coupling means is,
     i. When a record in Parent is deleted, the corresponding related record in the Child and Sub Detail 
        are also deleted (Cascading delete).
    ii. Security settings for the Child record are inherited from Parent i.e., the same security settings 
        specified for Parent are applied to Child records.
   iii. Records in Child objects don't have Owner field, as these records are tightly coupled with Parent 
        record. So the Custom objects on Detail and SubDetail side cannot have Sharing Rules, Manual 
       Sharing, and Queues which require Owner field.

By default we cannot reparent the records in Detail and SubDetail objects. If we want to allow Reparenting the Detail and SubDetail records, we should specify it when we defining the Master-Detail relationship by checking the "Allow Reparenting" checkbox.

Reparenting: Changing the Parent of a Child record is called Reparenting.
Ex: Suppose Parent object have ABC, XYZ records, and we created a child record for ABC record, changing the parent from ABC to XYZ in child object is called Reparenting. So the child record now associated with XYZ not ABC.

Roll-Up Summary fields:
      Fields which rolls up the data in child records are called Roll-Up summary fields. These are created on Parent object. We can roll up child's data in four ways, and we can apply roll up on all records or only a set of records that match the criteria you define.
          i. COUNT - counts the number of records that match a specific criteria or all records
         ii. SUM - Sum's up the data in child records which meet the specified condition or all records
        iii. MIN - returns the Minimum value among all records or specified records
        iv. MAX - return the Maximum value among all records or specified records

Other features:
   i. It is defined on Detail or SubDetail object
  ii. Master-Detail relationship is a required field, hence always included in Edit page of detail object.
 iii. Cannot be removed from page layout
 iv. At most two Master-Detail relationships are allowed per object
  v. Standard object cannot be at Detail side when Custom object is on Master side.

2. LookUp Relationship
        An association which loosely couples two objects (Parent and Child) or an Object to itself is called a LookUp relationship.
Loose Coupling: 
    i. No Cascading delete,
   ii. Parent and Child can have different security settings,
  iii. Child objects can have Sharing Rules, Manual Sharing, and Queues.

Differences between LookUp and Master-Detail relationship:
   i. LookUp relationship do not support Roll-Up summary fields
  ii. It is optional

Other features: 
  i. We can make a lookup field required on pagelayout,
 ii. We can make lookup field required when defining it,
iii. If the field is optional, you can specify one of the following 3 actions to occur when parent record
    is deleted.
     i). Clear the value in lookup field (default)
    ii). Don't allow deletion of lookup record that's part of lookup relationship,
   iii). Cascade delete (this is available only by contacting Salesforce, and also only if the custom
         object contains the lookup relationship, however the lookup object can be either Standard or 
         Custom).
 iv. We can create a maximum of 25 lookup relationship fields per object.

2.1 Self Relationship
        An association which binds the object to itself is called Self Relationship. A record in an object is linked  to another record in the same object.

2.2 Hierarchical Relationship
        An association which binds the object to itself is called Hierarchical Relationship.

Differences between Self and Hierarchical relationships are:
1. Self relationship can be used on any object,
2. Hierarchical relationship is only available for User object, to represent Employee-Manager
    association
3. In Self relationship, a record may reference itself indirectly, but in hierarchical a record should not
    reference itself directly or indirectly.

3. Many-to-Many relationship
        An association which binds two objects such a way that each record in two objects may have relationship with one or more records in other object.

      Salesforce supports this relationship through a Junction Object, which is defined as "a custom object with two master detail relationships to link two objects(custom or standard)".
Ex: Consider a situation where a Professor can teach many subjects and a Subject can be taught by many Professors.  So there exists a many-to-many relationship between Professor and Subject objects. To setup this association in Salesforce, we need to create an object called Teaches object. So the association looks like Professor-Teaches-Subject.

We know, the sharing and security settings are inherited from the parent to child in Master-Detail relationship, as we have two master detail relationships on Junction object, which master object settings are applied to junction object???

Primary Relationship: A master-detail relationship which is created first on the junction object.
Secondary Relationship: A master-detail relationship which is created second on the junction object.

The primary relationship determines the look and feel, Security and Sharing settings for the junction object. A master object to which the first relationship is created, junction object inherits that object settings. What happens if a Primary relationship is converted to a lookup or deleted??? automatically the secondary relationship becomes Primary Relationship, no manual effort required to make it Primary.

Thursday, 26 July 2018

delegated Administrator in salesforce

The delegated administrator is a concept
that extends certain privileges to non-admin
users in order to allow them to perform
admin functions.The actions that delegated
administrators can perform include the
following

1.User administration
2.Assignable profiles
3.Custom object adminsistration

Look UP relation ship in salesforce

1.You can define a lookup relationship between
any two objects, standard or custom.

2.When a parent object is being deleted,
you can configure a child object to either
clear the parent record value in the child
record or prevent deletion of the parent
record.

3.The child record may not require a
related parent record.

4.Each child record has an owner and is
not related to the parent record.

5. There is no security or inheritance
between related parent and child records.

6.To relate an object to other objects,
there is no condition on the number of records.

7.You cann't create the roll-up summary
field in the lookup relationship.

8.Does not support cross-object workflow.

How to create master-detail relationship in salesforce?

Master detail relationship is like parent
-child relationship where, master represents
a parent and detail represents a child in
which master object controls some
behaviours of the detail object.
Like whenever a master object record is
deleted then the detail object related
to it also gets deleted.


Master-detail relationship can be defined
between custom objects or between a
standard object and a custom object.
The detail object automatically gets the
security and sharing settings given to
the master object.


A child of one master detail relationship
can't become a parent of another object.
To relate an object to another object,no
records should exist in the child object.


Rollup summary fields can only be created
on Master records,which are used to
calculate the count,sum,min,max ect of
child records.

Note :
=========
we can't create a master - detail relationship
on existing records.To do that,we have to
create a lookup relationship for that
record and then convert it into master detail.

The master detail relationship does not
allow for 'orphaned' child records.


To convert a lookup relationship to a
master detail the existing record should
consist of valid lookup field values.

You can build many to many relationships
using two master details relationships in
an object, and it is called as junction object.

Standard objects can't be on a detail side
of a master detail relationship.Access to
detail is determined by the access given
for master.

supports cross-object work flow.you can
configure a field update action to
update a field in the parent record
using a value from the child record.

Limitations :
===============
1.Only upto two master detail relationships
are allowed for an object.
2.you can have only Upto three levels of
custom detail levels.
3.We can't create a master-detail relationship
when the custom object already contains data.

4.Each object is allowed to have one or two
master or upto 8 details.

5.After converting a lookup field into master-
detail relationship,test your custom reports,
whther they are usable or not.
Sometimes upon converting the custom reports
can become unusable due to different standard
report types.