wrapper class example

37
} } if(acc.contacts.size()>1) } } } Here is the output: Account Name Bhalla_123 Edge Communications Express Logistics and Transport Grand Hotels & Resorts Ltd public with sharing class wrapper2cls { public class accwrapper { public Account acc{get; set;} public List<Contact> lstcon{get; set;} public List<Case> lstcases{get; set;} public accwrapper(Account a, List<Contact> lst, List<case> lstcase){ acc = a; lstcon = lst; lstcases = lstcase; public List<accwrapper> lstwrap{get; set;} public wrapper2cls(){ lstwrap = new List<accwrapper>(); List<account> lst = [Select id, name,(Select id, name from Contacts), (Select id,CaseNumber from cases) from account order by name]; for(Account acc : lst){ lstwrap.add(new accwrapper(acc,acc.contacts,acc.cases));

Upload: muneesh-bhalla

Post on 22-Nov-2015

75 views

Category:

Documents


1 download

DESCRIPTION

SFDC Examples

TRANSCRIPT

Sheet1publicwithsharingclasswrapper2cls{Page Name : Wrapper_class_3

publicclassaccwrapper {publicAccountacc{get;set;}publicListlstcon{get;set;}publicListlstcases{get;set;}publicaccwrapper(Accounta,Listlst,Listlstcase){acc=a;lstcon=lst;lstcases=lstcase;{!c.name}
}}publicListlstwrap{get;set;}{!c.casenumber}
publicwrapper2cls(){lstwrap=newList();Listlst=[Selectid,name,(Selectid,namefromContacts),(Selectid,CaseNumberfromcases)fromaccountorderbyname];for(Accountacc:lst){if(acc.contacts.size()>1)lstwrap.add(newaccwrapper(acc,acc.contacts,acc.cases));}}

}Here is the output:

Account NameBhalla_123Ritu BhallaBhalla_123Edge CommunicationsSean Forbes1018Rose Gonzalez10171000Express Logistics and TransportJosh Davis1005Babara Levy10041003Grand Hotels & Resorts LtdJohn Bond1026Tim Barr1014101310081007

Sheet2Page Name : Wrapper_class_3

publicwithsharingclasswrapperActOptycls{publicclassActOptywrapper{publicAccountacc{get;set;}publicListlstcons{get;set;}publicListlstOptys{get;set;}publicActOptywrapper(Accounta,Listlst,ListlstOpty){!c.name}
{acc=a;lstcons=lst;lstOptys=lstOpty;}{!c.name} {!c.StageName}
}publicListlstwrap{get;set;}publicwrapperActOptycls(){lstwrap=newList();Listlst=[Selectid,name,(Selectid,namefromContacts),(Selectid,name,StageName,amountfromOpportunities)fromaccountorderbyname];

for(Accountacc:lst){if(acc.contacts.size()>1)lstwrap.add(newActOptywrapper(acc,acc.contacts,acc.Opportunities));}}

}

Sheet3 .activeTab {background-color: #236FBD; color:white; background-image:none} .inactiveTab { background-color: lightgrey; color:black; background-image:none} Click to add topics

DetailsContactsOpportunitiesOpen ActivitiesNotes and Attachments

OpportunitiesActionOpportunity NameStageAmountClose DateEdit|DelExpress Logistics Standby GeneratorClosed Won$220,000.007/4/12Edit|DelExpress Logistics Portable Truck GeneratorsValue Proposition$80,000.007/4/12Edit|DelExpress Logistics SLAPerception Analysis$120,000.007/4/12

Sheet4

For buttons or links that navigate a user to a standard tab, you can redirect the content to present a list of standard objects.Create aVisualforcepage with the following markup:The user will see a page that resembles the following:Overriding the Account Detail Page

TheVisualforcepage can also refer to other standard objects, such as contacts, by changing the reference to the standard object. For example:TheVisualforcepage can also refer to other standard objects, such as contacts, by changing the reference to the standard object. For example:The only fields that thetag cannot display are those defined as member variables of a custom controller class written inApex. To gather data for these variables, use the,,,, ortags instead. You are viewing the {!account.name} account. Change Account Name:

Sheet5

Sheet6 To fully understand the order of execution of elements on aVisualforcepage, you must first understand the page'slifecyclethat is, how the page is created and destroyed during the course of a user session. The lifecycle of a page is determined not just by the content of the page, but also by how the page was requested. There are two types ofVisualforcepage requests:Aget requestis an initial request for a page either made when a user enters an URL or when a link or button is clicked that takes the user to a new page.Apostback requestis made when user interaction requires a page update, such as when a user clicks on aSavebutton and triggers a save action.Visualforcepages that use theStandard Controllercant be used in dashboards. To be included in a dashboard, aVisualforcepage must have either no controller, use acustom controller, or reference a page bound to theStandardSetController Class. If aVisualforcepage does not meet these requirements, it does not appear as an option in the dashboard componentVisualforcePagedrop-down list.

Sheet7 {!c.subject} apex:selectListApex:selectListA list of options that allows users to select only one value or multiple values at a time, depending on the value of its multiselect attribute.This page is associated with the standard account controller and thecomponent is populated by{!listviewoptions}, which evaluates to the list views the user can see. When the user chooses a value from the drop-down list, it is bound to thefilterIdproperty for the controller. When thefilterIdis changed, the records available to the page changes, so, when theis updated, that value is used to update the list of records available to the page.Visualforce page and controller that demonstrate partial pagerefresh.A commandButton is defined to increment an integer value in the controller whenAssociating a Standard List Controller with a Visualforce Pageclicked, via the increment method.The amount to be incremented is passed from theUsing a standard list controller is very similar to using a standard controller. First you set thestandardControllerattribute on thecomponent, then you set therecordSetVarattribute on the same component.page to controller during the click, using the param component.The increment methodreturns a null PageReference to remain on the current Visualforce page rather than navigatingFor example, to associate a page with the standard list controller for accounts, use the following markup:to a new page.This is a requirement for partial page refreshes.An outputPanel displays the current value of the integer.The reRender attribute isset on the commandButton to refresh only the outputPanel rather than the entire page.The view state size of yourVisualforcepages must be under135KB. By reducing your view state size, your pages can load quicker and stall less often.If you notice that a large percentage of your view state comes from objects used in controllers or controller extensions, consider refining your SOQL calls to return only data that's relevant to theVisualforcepage.1. List acs = [SELECT ID FROM Account LIMIT 20];If your view state is affected by a large component tree, try reducing the number of components your page depends on.2. for (Integer i = 0; i < acs.size(); i++) {3. System.debug(acs[i]);Large page sizes directly affects load times. To improveVisualforcepage load times:4. }Cache any data that is frequently accessed, such as icon graphics.Avoid SOQL queries in yourApexcontroller getter methods.StandardController objects reference the pre-builtVisualforcecontrollers provided bysalesforce.com. The only time it is necessary to refer to a StandardController object is when defining an extension for a standard controller. StandardController is the data type of the single argument in the extension class constructor.Reduce the number of records displayed on a page by:public class myControllerExtension {Limiting the data coming back from SOQL calls in yourApexcontrollers. For example,usingANDstatements in yourWHEREclause, orremovingnullresults private final Account acct;Taking advantage ofpagination with a list controllerto present fewer records per page // The extension constructor initializes the private member // variable acct by using the getRecord method from the standard controller.By using thewith sharingkeyword when creating yourApexcontrollers, you have the possibility ofimproving your SOQL queries by only viewing a data set for a single user. public myControllerExtension(ApexPages.StandardController stdController) { this.acct = (Account)stdController.getRecord();By encapsulating the input fields within and components, Visualforce }automatically inserts field labels (Account Name, Industry) as well as indicators of whether values are required for the public String getGreeting() {fields, all using the platform styles. return 'Hello ' + acct.name + ' (' + acct.id + ')'; }The component displays all information, warning or error messages that were generated for all}components on the current pageUse the component (the singular, not the plural) to create custom messages.List ls = [select Id,Name from Account];Map m = new Map(ls);To declare a map, use theMapkeyword followed by the data types of the key and the value withincharacters. For example:

Map country_currencies = new Map();Map m = new Map();

SendEmailFill out the fields below to test how you might send an email to a user.
Name{!contact.Name}Email{!contact.Email}

:


:



publicclass sendEmail { publicString subject { get; set; } publicString body { get; set; }

privatefinal Account account;

// Create a constructor that populates the Account object public sendEmail() { account = [select Name, (SELECT Contact.Name, Contact.Email FROM Account.Contacts) from Account where id = :ApexPages.currentPage().getParameters().get('id')]; }

public Account getAccount() { return account; }

public PageReference send() { // Define the email Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();

String addresses; if (account.Contacts[0].Email != null) { addresses = account.Contacts[0].Email; // Loop through the whole list of contacts and their emailsfor (Integer i = 1; i < account.Contacts.size(); i++) { if (account.Contacts[i].Email != null) { addresses += ':' + account.Contacts[i].Email; } } }

String[] toAddresses = addresses.split(':', 0);

// Sets the paramaters of the email email.setSubject( subject ); email.setToAddresses( toAddresses ); email.setPlainTextBody( body ); // Sends the email Messaging.SendEmailResult [] r = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email}); returnnull; }}Notice in the controller that:The subject and body of the email are set through a separateVisualforcepage and passed into the controller.The method that sends the email is calledsend(). This name must match the name of the action for theVisualforcebutton that sends the email.The recipients of the email, that is, the email addresses stored intoAddresses[], come from the addresses of the contacts available in an associated account. When compiling a list of recipients from contacts, leads, or other records, it is a good practice to loop through all the records to verify that an email address is defined for each. The account ID is retrieved from the URL of the page.

Sheet9 {!greeting} Here's the owner of this account: {! account.Owner.Name} You are viewing the {!account.name} account. Here's theindustry of this account: {! account.industry} Change Account Name: publicclassmyControllerExtension{privatefinalAccountacct;publicclassMyController{//TheextensionconstructorinitializestheprivatememberAccountaccount;//variableacctbyusingthegetRecordmethodfromthestandardpublicStringgetName(){//controller.return'MyController';publicmyControllerExtension(ApexPages.StandardControllerstdController){}this.acct=(Account)stdController.getRecord();publicPageReferencesave(){}updateaccount;publicStringgetGreeting(){PageReferencesecondPage=Page.mysecondpage;return'Hello'+acct.name+'('+acct.id+')';secondPage.setRedirect(true);}secondPage.getParameters().put('id',account.id);}returnsecondpage;}publicAccountgetAccount(){account=[selectid,namefromAccountwhereid=:ApexPages.currentPage().getParameters().get('id')];returnaccount;}}

ShoppingCart

This connects your page to your Merchandise__c custom object on the platform, using a built-in controller that provides a lot of basic functionality, like reading, writing, and creating new Merchandise__c objects.

This configures your controller to work with lists of Merchandise__c records all at once, for example, to display a list of products in your catalog. Exactly what we want to do!However, because youve set the page to use a controller, and defined the variableproducts, the variable will be available to you in the body of the page, and it will represent a list of Merchandise__c records.

Thevalueattribute indicates which list of items thepageBlockTablecomponent should iterate over. Thevarattribute assigns each item of that list, for one single iteration, to thepitemvariable. Add these attributes to the tag

With three columns, the listing is compressed because the table is narrow. Make it wider by changing thetag.This changes the section from two columns to one, letting the single column be wider.Controllers typically retrieve the data to be displayed in aVisualforcepage, and contain code that will be executed in response to page actions, such as a command button being clicked.New Controller

publicclass StoreFrontController {publicclass StoreFrontController { List products; List products; public List getProducts() { public List getProducts() { if(products == null) { if(products == null) products = [SELECT Id, Name, Description__c, Price__c FROM Merchandise__c]; { products = new List(); } for(Merchandise__c item : [ return products;SELECT Id, Name, Description__c, Price__c, Total_Inventory__c } FROM Merchandise__c]) } { products.add(new DisplayMerchandise(item));} }You also remove therecordSetVarattribute, because its only used with standard controllers. return products; }1. Make the following addition to set the application tab style back to Merchandise. // Inner class to hold online store details for itempublicclass DisplayMerchandise {the value attribute of thepageBlockTableis set to{!products}, indicating that the table component should iterate over a list calledproducts. Because you are using a custom controller, whenVisualforceevaluates the{!products}expression, it automatically looks for a methodgetProducts()in yourApexcontroller. private Merchandise__c merchandise; public DisplayMerchandise(Merchandise__c item) {The combination of a public instance variable (here,products) with a getter method (getProducts()) to initialize and provide access to it is a common pattern inVisualforcecontrollers written inApex. this.merchandise = item; }TheoutputFieldcomponent works automatically with sObject fields, but doesnt work at all with custom classes.outputTextworks with any value. // Properties for use in the Visualforce viewpublicString name { get { return merchandise.Name; } } publicString description { get { return merchandise.Description__c; } } publicDecimal price { get { return merchandise.Price__c; } } publicBoolean inStock { get { return (0 < merchandise.Total_Inventory__c); } } publicInteger qtyToBuy { get; set; } }}Change the column definitions to work with the property names of the new inner class. Replace the existing column definitions with the following code. 1. Youll notice that the price column is no longer formatted as currency.2. Change the priceoutputTexttag to the following code.

TheoutputTextcomponent can be used to automatically format different data types.

Sheet11publicwithsharingclassclsController{publicListcontacts{get;set;}publicclsController() {contacts=[selectid,name,email,accountid,phone,nominate__cfromcontactlimit10]; } publicvoidsave() { updatecontacts; } } publicclassmyControllerExtension{ {!greeting} privatefinalAccountacct; //Theextensionconstructorinitializestheprivatemember//variableacctbyusingthegetRecordmethodfromthestandard //controller.publicmyControllerExtension(ApexPages.StandardControllerstdController){this.acct=(Account)stdController.getRecord();} publicStringgetGreeting(){ return'Hello'+acct.name+'('+acct.id+')'; } }

ClassesUse the following syntax for defining classes:

private | public | global [virtual | abstract | with sharing | without sharing | (none)] class ClassName [implements InterfaceNameList | (none)] [extends ClassName | (none)] { // The body of the class}

Theprivateaccess modifier declares that this class is only known locally, that is, only by this section of code. This is the default access for inner classesthat is, if you don't specify an access modifier for an inner class, it is consideredprivate. This keyword can only be used with inner classes.Thepublicaccess modifier declares that this class is visible in your application or namespace.Theglobalaccess modifier declares that this class is known by allApexcode everywhere.All classes that contain methods defined with thewebServicekeyword must be declared asglobal. If a method or inner class is declared asglobal, the outer, top-level class must also be defined asglobal.Thewith sharingandwithout sharingkeywords specify the sharing mode for this class. For more information, seeUsing thewith sharingorwithout sharingKeywords.Thevirtualdefinition modifier declares that this class allows extension and overrides. You cannot override a method with theoverridekeyword unless the class has been defined asvirtual.Theabstractdefinition modifier declares that this class contains abstract methods, that is, methods that only have their signature declared and no body defined.Note

You cannot add an abstract method to a global class after the class has been uploaded in aManaged - Releasedpackage version.If the class in theManaged - Releasedpackage is virtual, the method that you can add to it must also be virtual and must have an implementation.You cannot override a public or protected virtual method of a global class of an installed manageUse the following syntax when defining a variable:[public | private | protected | global | final] [static] data_type variable_name [= value] For example: privatestaticfinalInteger MY_INT; privatefinalInteger i = 1;

(public | private | protected | global ) [override] [static] data_type method_name (input parameters) {// The body of the method}NoteYou can only useoverrideto override methods in clasAconstructoris code that is invoked when an object is created from the class blueprint. You do not need to write a constructor for every class. If a class does not have a user-defined constructor, an implicit, no-argument, public one is used.The syntax for a constructor is similar to a method, but it differs from a method definition in that it never has an explicit return type and it is not inherited by the object created from it.After you write the constructor for a class, you must use thenewkeyword in order to instantiate an object from that class, using that constructor. For example, using the following class:

publicclass TestObject {

// The no argument constructor public TestObject() { // more code here }}A new object of this type can be instantiated with the following code:TestObject myTest = new TestObject();If you write a constructor that takes arguments, you can then use that constructor to create an object using those arguments. If you create a constructor that takes arguments, and you still want to use a no-argument constructor, you must include one in your code. Once you create a constructor for a class, you no longer have access to the default, no-argument public constructor. You must create your own.InApex, a constructor can beoverloaded, that is, there can be more than one constructor for a class, each having different parameters. The following example illustrates a class with two constructors: one with no arguments and one that takes a simple Integer argument. It also illustrates how one constructor calls another constructor using thethis(...)syntax, also know asconstructor chaining.

publicclass TestObject2 {

privatestaticfinalInteger DEFAULT_SIZE = 10;

Integer size;

//Constructor with no argumentspublic TestObject2() { this(DEFAULT_SIZE); // Using this(...) calls the one argument constructor }

// Constructor with one argument public TestObject2(Integer ObjectSize) { size = ObjectSize; }}New objects of this type can be instantiated with the following code: TestObject2 myObject1 = new TestObject2(42); TestObject2 myObject2 = new TestObject2();Every constructor that you create for a class must have a different argument list. In the following example, all of the constructors are possible:

publicclass Leads {

// First a no-argument constructor public Leads () {}

// A constructor with one argumentpublic Leads (Boolean call) {}

// A constructor with two argumentspublic Leads (String email, Boolean call) {}

// Though this constructor has the same arguments as the // one above, they are in a different order, so this is legalpublic Leads (Boolean call, String email) {}}When you define a new class, you are defining a new data type. You can use class name in any place you can use other data type names, such as String, Boolean, or Account. If you define a variable whose type is a class, any object you assign to it must be an instance of that class or subclass.1. Trigger1calls a method ofClass1and another method ofClass2. For example:trigger Trigger1 on Account (before insert) { Class1.someMethod(); Class2.anotherMethod();}

2. Class1calls a method ofClass3, which in turn calls a method of a utility class. For example:publicclass Class1 { publicstaticvoid someMethod() { Class3.thirdMethod(); }}

publicclass Class3 { publicstaticvoid thirdMethod() { UtilityClass.doSomething(); }}

3. Class2causes a trigger,Trigger2, to be executed. For example:publicclass Class2 { publicstaticvoid anotherMethod() { // Some code that causes Trigger2 to be fired. }}To set log filters:1. From a class or trigger detail page, clickLog Filters.2. ClickOverride Log Filters.The log filters are set to the default log levels.3. Choose the log level desired for each log category.