Thursday 30 August 2012

Adding Action Methods to an Apex Controller

In this lesson, you’ll add action method to your controller to allow it to handle clicking a new Add to Cart button, as well as a new method that outputs the contents of a shopping cart. You’ll see how Visualforce transparently passes data back to your controller where it can be processed. On the Visualforce side you’ll add that button to the page, as well as form fields for shoppers to fill in.
  1. Click StoreFrontController to edit your page’s controller code.
  2. Add the following shopping cart code to the definition of StoreFrontController, immediately after the products instance variable, and then click Quick Save.
    List<DisplayMerchandise> shoppingCart = new List<DisplayMerchandise>();
    
    // Action method to handle purchasing process  
        
    public PageReference addToCart() {
        for(DisplayMerchandise p : products) {
            if(0 < p.qtyToBuy) {
                shoppingCart.add(p);
            }
        }
        return null; // stay on the same page  
        
    }
    
    public String getCartContents() {
        if(0 == shoppingCart.size()) {
            return '(empty)';
        }
        String msg = '<ul>\n';
        for(DisplayMerchandise p : shoppingCart) {
            msg += '<li>';
            msg += p.name + ' (' + p.qtyToBuy + ')';
            msg += '</li>\n';
        }
        msg += '</ul>';
        return msg;
    }
    
    Now you’re ready to add a user interface for purchasing to your product catalog.
  3. Click Catalog to edit your page’s Visualforce code.
  4. Wrap the product catalog in a form tag, so that the page structure looks like this code.
    <apex:page controller="StoreFrontController">
        <apex:form>
            <!-- rest of page code --> 
         
        </apex:form>
    </apex:page>
    The <apex:form> component enables your page to send user-submitted data back to its controller.
  5. Add a fourth column to the products listing table using this code.
    <apex:column headerValue="Qty to Buy">
        <apex:inputText value="{!pitem.qtyToBuy}" rendered="{! pitem.inStock}"/>
        <apex:outputText value="Out of Stock" rendered="{! NOT(pitem.inStock)}"/>
    </apex:column>
    
    This column will be a form field for entering a quantity to buy, or an out-of-stock notice, based on the value of theDisplayMerchandise.inStock() method for each product.
  6. Click Save and reload the page.There is a new column for customers to enter a number of units to buy for each product.
  7. Add a shopping cart button by placing the following code just before the </apex:pageBlock> tag.
    <apex:pageBlockSection>
        <apex:commandButton action="{!addToCart}" value="Add to Cart"/>
    </apex:pageBlockSection>
    If you click Save and try the form now, everything works…except you can’t see any effect, because the shopping cart isn’t visible.
  8. Add the following code to your page, right above the terminating </apex:form> tag.
    <apex:pageBlock title="Your Cart" id="shopping_cart">
        <apex:outputText value="{!cartContents}" escape="false"/>
    </apex:pageBlock>
    
  9. Click Save, and give the form a try now. You should be able to add items to your shopping cart! In this case, it’s just a simple text display. In a real-world scenario, you can imagine emailing the order, invoking a Web service, updating the database, and so on.
  10. For a bonus effect, modify the code on the Add to CartcommandButton.
    <apex:commandButton action="{!addToCart}" value="Add to Cart" reRender="shopping_cart"/>
    If you click Save and use the form now, the shopping cart is updated via Ajax, instead of by reloading the page.
    Product catalog page with custom controller, with cart

Tell Me More...

  • As you saw in this lesson, Visualforce automatically mirrored the data changes on the form back to the products variable. This functionality is extremely powerful, and lets you quickly build forms and other complex input pages.
  • When you click the Add to Cart button, the shopping cart panel updates without updating the entire screen. The Ajax effect that does this, which typically requires complex JavaScript manipulation, was accomplished with a simple reRender attribute.
  • If you click Add to Cart multiple times with different values in the Qty to Buy fields, you’ll notice a bug, where products are duplicated in the shopping cart. Knowing what you now know about Apex, can you find and fix the bug? One way might be to change a certain List to a Map, so you can record and check for duplicate IDs. Where would you go to learn the necessary Map methods…?

No comments:

Post a Comment