In the last lesson, you created a custom controller for your Visualforce catalog page. But your controller passes custom objects from the database directly to the view, which is not ideal. In this lesson, you’ll refactor your controller to more correctly use the MVC design pattern, and add some additional features to your page.
Click StoreFrontController to edit your page’s controller code.
Revise the definition of the class as follows and then click Quick Save.
publicclass StoreFrontController {
List<DisplayMerchandise> products;
public List<DisplayMerchandise> getProducts() {
if(products == null) {
products = new List<DisplayMerchandise>();
for(Merchandise__c item : [
SELECT Id, Name, Description__c, Price__c, Total_Inventory__c
FROM Merchandise__c]) {
products.add(new DisplayMerchandise(item));
}
}
return products;
}
// Inner class to hold online store details for itempublicclass DisplayMerchandise {
private Merchandise__c merchandise;
public DisplayMerchandise(Merchandise__c item) {
this.merchandise = item;
}
// Properties for use in the Visualforce viewpublic String name {
get { return merchandise.Name; }
}
public String description {
get { return merchandise.Description__c; }
}
public Decimal price {
get { return merchandise.Price__c; }
}
public Boolean inStock {
get { return (0 < merchandise.Total_Inventory__c); }
}
public Integer qtyToBuy { get; set; }
}
}
Click Catalog to edit your page’s Visualforce code.
Change the column definitions to work with the property names of the new inner class. Replace the existing column definitions with the following code.
The DisplayMerchandise class “wraps” the Merchandise__c type that you already have in the database, and adds new properties and methods. The constructor lets you create a new DisplayMerchandise instance by passing in an existing Merchandise__c record. The instance variable products is now defined as a list of DisplayMerchandise instances.
The getProducts() method executes a query (the text within square brackets, also called a SOQL query) returning all Merchandise__c records. It then iterates over the records returned by the query, adding them to a list of DisplayMerchandise products, which is then returned.
No comments:
Post a Comment