anusha(salesforce developer)

Tuesday 24 January 2017

Schema.DescribeSObjectResult in Apex and its usage in visualforce.

Schema.DescribeSObjectResult in Apex and its usage in visualforce.


This Describes SObject methods returns an array of DecribeSobjectResult objects. Where each object has the following properties.

String Name : This is the name of the object.

String Label :  Label text for the tab or an objct.

String LabelPlural : Label text for an object that represents plural version of object name.

String keyPrefix :  Object id's are prefixed with 3 character quotes that specify the type of the object.

Ex: - Account obj as 001, Opportunity object has 006.

When we call the keyPrefix it will return 3 character prefix code for the object which we are called.


Field[] fields: This will return array of the fields associated with an object.

Boolean Custom: Indicated whether the object is a custom object or not.

Boolean Creatable: Indicates whether the object can be created via created method.

Boolean deletable: Indicates whether the object can be deleted or not.

Boolean Mergable: Indicates whether the object can be merged with objects of its type.

Replicatable: Indicates whether the object can be replicatable via getUpdate function or getDeleted.

Boolean Retrievable : Indicates whether the object can be retrieved using retrieve method or not.

Boolean Searchable:- Indicates whether object can be searched via Search method .


Boolean updatable : Checks whether the object can be updatable or not.

To fetch the properties of an object

Schema.DescribeSobjectResult resultObj = Account.SobjectType.getDescribe();

                                              Or
Schema.DescribeSobjectResult result =  Schema.SobjectType.Account();

Example:

Field Example:

 Public class FieldExample{

   public String result {get;set;}

  Public FieldExample() {

 Schema.DescribeSobjectResult resultObj =          Account.SobjectType.getDescribe();
 result = ' ' +resultObj ;

}

}

In the above program 'resultObj' cibtaubs description about the object Account. If you want to know the properties individually we can use.

String getLabel();
String getKeyPrefix();
String getLabelPlural(); etc...



Child Relationship methods for given Object:


List <Schema.ChilRelationship> getChildRelationShips(); 

If an sobject is a parent object we can access the child relationships as well as the child objects using ChildRelationShip object.  This method returns the list of child objects for the given Sobject.


List of Child Records:

Program to display the List of Child objects for a given object

EX:-
public class ChildRelationshipExample {

public List<SelectOption> options;

public List<SelectOption> getOptions(){
 return options;
}

public ChildRelationshipExample(){

options = new List<SelectOption>();
Schema.DescribeSobjectResult r = Account.SobjectType.getDescribe();
List<Schema.childRelationship> c = r.getChildRelationShips();

for(schema.childRelationship x:c){
 String name = ' '+x.getChildSObject();
 SelectOption op = new SelectOption(name,name);
 options.add(op);
}

}


}

VF Page:

<apex:page controller="ChildRelationshipExample">
  <apex:form >
   <apex:selectlist size="1">
     <apex:selectoptions value="{!options}"></apex:selectoptions>
   </apex:selectlist>
  </apex:form>
</apex:page>



Thursday 19 January 2017

How To Create Dynamic Dependent Picklist Of Objects in Salesforce

Apex Code:

public class sample
{
    public String state {get;set;}
    public String city {get;set;}

    public List<SelectOption> getStates()
    {
        List<SelectOption> options = new List<SelectOption>();
        options.add(new SelectOption('None','--- None ---'));       
        options.add(new SelectOption('TN','Tamil Nadu'));
        options.add(new SelectOption('KL','Kerala'));
        return options;
    }
   
    public List<SelectOption> getCities()
    {
        List<SelectOption> options = new List<SelectOption>();
        if(state == 'TN')
        {      
            options.add(new SelectOption('CHE','Chennai'));
            options.add(new SelectOption('CBE','Coimbatore'));
        }
        else if(state == 'KL')
        {      
            options.add(new SelectOption('COA','Coachin'));
            options.add(new SelectOption('MVL','Mavelikara'));
        }
        else
        {
            options.add(new SelectOption('None','--- None ---'));
        }     
        return options;
    }      
}


Visualforce page:

<apex:page controller="sample">
   
    <apex:form >
   
    <apex:pageBlock>
        <apex:pageBlockSection columns="2">
            <apex:pageblockSectionItem>
                <apex:outputLabel value="State"/>
            </apex:pageblockSectionItem>       
            <apex:pageblockSectionItem>               
                <apex:selectList size="1" value="{!state}">
                    <apex:selectOptions value="{!states}"/>
                    <apex:actionSupport event="onchange" reRender="a"/>
                </apex:selectList>               
            </apex:pageblockSectionItem>
            <apex:pageblockSectionItem>
                <apex:outputLabel value="City"/>
            </apex:pageblockSectionItem>           
            <apex:pageblockSectionItem>
                <apex:selectList size="1" value="{!city}" id="a">
                    <apex:selectOptions value="{!cities}"/>
                </apex:selectList>
            </apex:pageblockSectionItem>           
        </apex:pageBlockSection>       
    </apex:pageBlock>

    </apex:form>

</apex:page>

What is web services?

web service is a piece of software that makes itself available over the internet and uses a standardized XML messaging system. XML is used to encode all communications to a web service. For example, a client invokes a web service by sending an XML message, then waits for the corresponding XML response.

There are mainly two types of web services.

    1. SOAP web services.
    2. RESTful web services.

Components of Web Services

    • SOAP (Simple Object Access Protocol)
    • UDDI (Universal Description, Discovery and Integration)
    • WSDL (Web Services Description Language)

Soap web services: – SOAP is XML based protocol. It is platform and language independent. By using SOAP, you will be able to interact with other applications designed in different programming languages.
Rest web services: – REST stands for Representational State Transfer, which is an architectural style for networked hypermedia applications, it is primarily used to build Web services that are lightweight, maintainable, and scalable. A service based on REST is called a RESTful service.

Difference between SOAP and REST

No.SOAPREST
SOAP stands for Simple Object Access Protocol.REST stands for Representational State Transfer.
SOAP is a XML based messaging protocol.REST is an architectural style.
SOAP permits XML data format only.REST permits different data format such as Plain text, HTML, XML, JSON etc.
SOAP defines standards to be strictly followed.REST does not define too much standards like SOAP.
JAX-WS is the java API for SOAP web services.JAX-RS is the java API for RESTful web services.
SOAP is distributed computing style.REST is web style (web is also a distributed computing model).

REST Web Service

REST stands for Representational State Transfer. REST was a term coined by Roy Fielding.
REST is not dependent on any protocol, but almost every RESTful service uses HTTP as its underlying protocol.
Using HTTP Methods for RESTful Services
HTTP VerbCRUD
GETRead
PUTUpdate/Replace
PATCHUpdate/Modify
DELETEDelete

Features of a RESTful Services: – A Restful web service should have following features.
    • Representations
    • Messages
    • URIs
    • Uniform interface
    • Stateless
    • Links between resources
    • Caching

Representations
“The focus of a RESTful service is on resources and how to provide access to these resources. A resource can easily be thought of as an object as in OOP. A resource can consist of other resources. While designing a system, the first thing to do is identify the resources and determine how they are related to each other. This is similar to the first step of designing a database: Identify entities and relations”.
In Rest we can use any format for representing our resources, as Rest does not put a restriction on the format of representation.
We can use either JSON format or XML format to represent our resource.
If you are building Web services that will be used by Web pages for AJAX calls, then JSON is a good choice. XML can be used to represent more complex resources.
Example 1
JSON representation of a resource
 




{ "ID": "001",
"Name": "Anil Singh",
"Email": "xxx.anil354@gmail.com",
"Country": "India"
}
Example 2
XML representation of a resource
<Person><ID>001</ID><Name>Anil Singh</Name><Email>xxx.anil354@gmail.com </Email><Country>India</Country></Person>

Note:-“The representation should be capable of linking resources to each other. This can be done by placing the URI or unique ID of the related resource in a representation”.

Message
“The client and service talk to each other via messages. Clients send requests to the server, and the server replies with a response. Apart from the actual data, these messages also contain some metadata about the message”.

Caching
“Caching is the concept of storing the generated results and using the stored results instead of generating them repeatedly if the same request arrives in the near future. This can be done on the client, the server, or on any other component between them, such as a proxy server. Caching is a great way of enhancing the service performance, but if not managed properly, it can result in client being served stale results”.

Statelessness
“A RESTful service is stateless and does not maintain the application state for any client. A request cannot be dependent on a past request and a service treats each request independently”.

Uniform Interface
“The uniform interface constraint is fundamental to the design of any REST service. The uniform interface simplifies and decouples the architecture, which enables each part to evolve independently”.

Links between resources
“A resource representation can contain links to other resources like an HTML page contains links to other pages. The representations returned by the service should drive the process flow as in case of a website. When you visit any website, you are presented with an index page. You click one of the links and move to another page and so on. Here, the representation is in the HTML documents and the user is driven through the website by these HTML documents themselves. The user does not need a map before coming to a website. A service can be (and should be) designed in the same manner”.

what is View State and how can we avoid these View State error?

View State:  As the name suggests, is an error of View State. “Maximum view state size limit (135KB) exceeded” is the error message pertaining to “View State” error and here follows a brief detailing of the issue.
View state holds the state/size of the visual force page that includes the components, field values and controller state. This is important in the light that salesforce provides only a standard size of 135kb for any individual page. If the size of a particular page exceeds 135kb, the page will throw a view state error.
To check the view state of a visual force page you have to make sure that ‘’Show View State in Development Mode’’ checkbox in the User Layout is checked.
You can access this setting from: Setup-> Manage User-> User-> Edit (on a particular user)-> Show View State in Development Mode
How to reduce View state:
1 :  Use the transient keyword : The simplest and the most logical way is to keep the size of the VF page as small as possible. For this purpose, Transient Variables are used as these do not store the values permanently, these variables just hold the values temporarily and therefore not stored in View State.
Declaring variables as transient reduces view state size.
An Example showing how a transient variable is declared:
transient String name;
2: Refine your SOQL: Reduce the number of records displayed on a page by refining SOQL. The use of AND statements, WHERE clause in SOQL, removing NULL results can help assure that only required data comes back from SOQL.
3: Minimize the Number of Forms on a Page: We should use <apex:actionReagion> instead of using two <apex:forms>.
Each form on your page will have its own copy of view state. Instead of having multiple forms on a page, have a single form and use <apex:actionRegion> to submit portions of the form.
This will make sure only a single copy of the view state is associated with that VF page instead of two copies.
Eg:
// Using two <apex:form>
<apex:page controller=”ApexController”>
      <apex:form>
         <apex:commandButton action=”{!objectFirstMethod}” value=”First Object”/> </apex:form>
      <apex:form>
      <apex:commandButton action=”{!objectSecondMethod}” value=”Second Object”/>
      </apex:form>
</apex:page>
// Using <apex:actionRegion>
<apex:page controller=”ApexController”>
      <apex:form>
       <apex:commandButton action=”{!objectFirstMethod}” value=”First Object”/>
       <apex:actionRegion>
        <apex:commandButton action=”{!objectSecondMethod}” value=”Second Object”/>
       </apex:actionRegion>
      </apex:form>
</apex:page>
4: Use Custom Setting: Use custom setting to store large quantities of read-only data instead of custom objects. Accessing custom settings is faster than accessing custom objects since custom settings are part of application’s cache and does not require a database query to retrieve the data unlike custom objects.
5: Use <apex:outputLink> : Instead of using <apex:commandLink> or <apex:commandButton> components, Use <apex:outputLink> because <apex:commandLink> or <apex:commandButton> requires to be included inside a <apex:form> component unlike <apex:outputLink>

Thursday 5 January 2017

Deletion of account record should fail it has any contact records

 Deletion of account record should fail it has any contact records


trigger example6 on Account (before delete) {
    List<Account> accs=[select id,(Select id from Contacts) from Account where Id In:Trigger.Old];
    for(Account a:accs){
        if(a.contacts.size() > 0){
            a.addError('Account Record with contact can not be deleted');
        }
    }
}

1. Create a Custom Field No_Of_Contats on Account Object 2. When ever new Contact is created or deleted update the no_of_contacts fields with no of contacts that exits for the parent records

1. Create a Custom Field No_Of_Contats on Account Object 

2. When ever new Contact is created  or deleted update the 
 no_of_contacts fields with no of contacts that exits for the parent records


trigger contactsTriggers on Contact (after insert,after delete) {
    if(Trigger.isInsert && Trigger.isAfter)
        TriggerContact.increment(Trigger.New);
    else
        TriggerContact.increment(Trigger.Old);

}


public class TriggerContact {
    public static void increment(List<Contact> cons){
        set<Id> accid=new Set<id>();
        for(Contact c:cons){
           accId.add(c.AccountId); 
        }
       List<Account> accs=[select id,No_of_contacts__c ,(select id from Contacts ) from Account where id in:accId];
        for(Account a:accs){
            a.no_of_contacts__c=a.contacts.size();
        }
        update accs;
    }

}

Sunday 1 January 2017

Adding lightning application in vf page

Adding lightning application in vf page:

<aura:application access="GLOBAL" extends="ltng:outApp"> 
    <aura:dependency resource="ui:button"/>
</aura:application>

VF Page :

<apex:page>
    <apex:includeLightning />

    <div id="lightning" />

    <script>
        $Lightning.use("c:app15", function() {
        $Lightning.createComponent("ui:button",{ label : "Press Me!" },
                                   "lightning",function(cmp) {});
        });
    </script>
</apex:page>