+ Start a Discussion
iKnowSFDCiKnowSFDC 

problems adding line items on custom visualforce product selector

I'm having an issue with some code - this code was written by a previous contractor but I'm updating it to support a larger data set and to provide a more usable interface.  Currently, the list of products is displayed and the user can select the product they are registering and the quantity. The list is very large, over 1000 which is a problem in and of itself.

The change I'm trying to make is to provide the user a product group (in this case a custom field on the product2 object called Forecast__c) and to give the user a smaller list of products associated with that category. 

The solution is adding records to a custom object (Registration_Product__c) that is linked via a master-detail relationship to a Parent object (Deal_Registration__c). 

The issue I"m having is when a second line item is added, the product group is defaulted to the first line item's group. 

Here is controller: 
 
public with sharing class ProductController {
    public Deal_Registration__c dealReg { get; private set; }
    private Integer nextId = 0;
    private String selectedId;
    public Boolean error {get; private set;}
    public Boolean testLimit {get; set;}

    public List<ProductRow> productRows { get; private set; } 
    private List<Registration_Product__c> deleted = new List<Registration_Product__c>();
    private List<SelectOption> productOptions = null;
    private List<SelectOption> productCapacities = null;
    
    
    Public String currentProduct {get;set;}
    Public String currentProductFamily {get;set;}


    public ProductController(ApexPages.StandardController controller) {
    	this.testLimit = false;
        final String dealRegProductId = ApexPages.currentPage().getParameters().get('id');
        final String dealRegId = ApexPages.currentPage().getParameters().get('dealRegId');
        System.debug('dealRegProductId:' + dealRegProductId);
        System.debug('dealRegId:' + dealRegId);
        if (dealRegProductId != null) {
            Registration_Product__c dealRegProduct = [Select Product__c, Storage_Capacity__c, 
                                                      Deal_Registration__c, Product__r.Forecast__c
                                                      from Registration_Product__c 
                                                      where Id = :dealRegProductId order by CreatedDate ];
            this.dealReg = [SELECT Name, Registration_Status__c FROM Deal_Registration__c WHERE Id = :dealRegProduct.Deal_Registration__c];         
        } else if (dealRegId != null) {
            this.dealReg = [Select Name, Registration_Status__c from Deal_Registration__c where Id =:dealRegId];
        } else {
            Registration_Product__c dealRegProduct = (Registration_Product__c) controller.getRecord();
            this.dealReg = [Select Name, Registration_Status__c from Deal_Registration__c where Id = :dealRegProduct.Deal_Registration__c];
        }
       
        productRows = new List<ProductRow>();
        productCapacities = new List<SelectOption>();
        error = false;
    }

    
    public PageReference onLoad() {
        System.debug('dealreg:' + dealReg);
        String status = this.dealReg.Registration_Status__c;
        System.debug('dealreg.status:' + status);
        if (status == null) status = '';
        if (status.equals('Submitted') || 
            status.equals('Approved'))  
        {
            ApexPages.Message m =new ApexPages.Message(ApexPages.Severity.ERROR, 'Deal Registration is locked and cannot be edited.'); 
            ApexPages.addMessage(m);
            error = true;
            return null;
        }
        for (Registration_Product__c dealRegProd : [SELECT Product__c, Storage_Capacity__c, Quantity__c, 
                                                    Deal_Registration__c 
                                                    FROM Registration_Product__c 
                                                    WHERE Deal_Registration__c = :dealReg.Id order by CreatedDate]) {
            nextId++;
            productRows.add(new ProductRow(String.valueOf(nextId), dealRegProd));
        }
        
        if (productRows.size() == 0) {
            nextId++;
            productRows.add(new ProductRow(String.valueOf(nextId), new Registration_Product__c()));
        }
        
        return null;
    }
    //New method added to support new product selector: 11/17/14
    Public List<SelectOption> getListGroups(){  
        List<SelectOption> options=New List<SelectOption> {new SelectOption('','-- Choose')};
        for(Schema.pickListEntry pe:Product2.Forecast__c.getDescribe().getpickListValues()){
            options.add(new SelectOption(pe.getValue(),pe.getLabel()));
        }
        return options;
    }

    //New method added to support new product selector: 11/17/14
    Public List<SelectOption> getListProducts(){
        List<SelectOption> options=New List<SelectOption>();
        if(currentProductFamily == null || currentProductFamily == ''){
            return options;
        }
        options.add(new SelectOption('','-- Choose --'));
        for(Product2 p2:[SELECT id, Name FROM Product2 
                         WHERE Forecast__c = : currentProductFamily 
                         AND isActive = TRUE 
                         AND Visible_in_Portal__c = TRUE
                         ORDER BY Name]) {
            options.add(new SelectOption(p2.id,p2.name));
        }
        return options;
        return Null;
    }
    
	
    /* *****Old product list 
	public List<SelectOption> getProductOptions() {
        if (productOptions == null) {
            productOptions = new List<SelectOption>();
            List<Product2> productList = null;
            productList = [Select Name from Product2 where isActive = true order by name ];
            if(productList.size()>1000){
                testLimit = true;
            }
            if (this.testLimit) {
            	productList = [Select Name from Product2 where isActive = true AND Visible_in_Portal__c = true order by name limit 1000];
            } else {
            	productList =[Select Name from Product2 where isActive = true AND Visible_in_Portal__c = true order by name];
            }
            for (Product2 p : productList) {
                productOptions.add(new SelectOption(p.Id, p.Name));
            }
        }
        return productOptions;
    }*/
    
    public List<SelectOption> getProductCapacities() {
        transient Schema.DescribeFieldResult F = Registration_Product__c.Storage_Capacity__c.getDescribe();
        transient List<Schema.Picklistentry> plValues = F.getPicklistValues();
        productCapacities.add(new SelectOption('none', 'none'));
        for(Schema.Picklistentry value : plValues){
            productCapacities.add(new SelectOption(value.getValue(), value.getLabel()));
        }

        return productCapacities;
    }
    
    public PageReference onAddCondition() {
        String selectedId = ApexPages.currentPage().getParameters().get('selectedId');
        System.debug('selectedId --- onAddCondition---------->'+ selectedId);
        if (selectedId != null) {
            for (Integer i=0;i<productRows.size();i++) {
                ProductRow row = productRows.get(i);
                if (row.getId().equals(selectedId)) {
                    nextId++;
                    Registration_Product__c prod = new Registration_Product__c();
                    prod.Quantity__c = 1;
                    if (i == (productRows.size() - 1)) {
                        productRows.add(new ProductRow(String.valueOf(nextId), prod));
                    } else {
                        productRows.add(i + 1, new ProductRow(String.valueOf(nextId), prod));
                    }
                    return null;
                }
            }
        }
        return null;
    }
    
    public PageReference onRemoveCondition() {
        String selectedId = ApexPages.currentPage().getParameters().get('selectedId');
        System.debug('selectedId --- onRemoveCondition---------->'+ selectedId);
        if (selectedId != null) {
            for (Integer i = 0; i < productRows.size(); i++) {
                ProductRow row = productRows.get(i);
                if (row.getId().equals(selectedId)) {
                    productRows.remove(i);
                    if (row.getDealRegProduct().Id != null) {
                        deleted.add(row.getDealRegProduct());
                    }
                    return null;
                }
            }
        }
        return null;
    }
    
    public PageReference onSave() {
        delete deleted;
        try {
            List<Registration_Product__c> batch = new List<Registration_Product__c>();
            for (ProductRow row : productRows) {
                Registration_Product__c prod = row.getDealRegProduct();
                if (prod.Id == null) {
                    prod.Deal_Registration__c = dealReg.Id;
                }
                batch.add(prod);
            }
        	upsert batch;
        }
        catch (Exception e) {
            ApexPages.addMessages(e); 
            return null;
        }
        
        return new PageReference('/' + dealReg.Id);
    }
    
    
    public PageReference onCancel() {
        return new PageReference('/' + dealReg.Id);
    }
     
        
    public class ProductRow {
        private String id;
        private Registration_Product__c dealRegProduct;
        
        public ProductRow(String id, Registration_Product__c dealRegProduct) {
            this.id = id;
            this.dealRegProduct = dealRegProduct;
        }
        
        public String getId() {
            return id;
        }
        
        public Registration_Product__c getDealRegProduct() {
            return dealRegProduct;
        }
        
    }
}

VisualForce Code: 
 
<apex:page standardController="Registration_Product__c" extensions="ProductController" action="{!onLoad}" >
    
    <apex:sectionHeader title="{!$Label.addEditProds}" subtitle="{!dealReg.Name}"/>

    <apex:form >
        <apex:pageBlock >
        <apex:pageMessages />
            <apex:pageBlockButtons >
                <apex:commandButton action="{!onSave}" value="{!$Label.Save}" rendered="{!NOT(error)}" />
                <apex:commandButton action="{!onCancel}" immediate="true" value="{!$Label.Cancel}"/>
            </apex:pageBlockButtons>
            
            
            <apex:pageBlockTable id="row" value="{!productRows}" var="row" rendered="{!NOT(error)}">
                <apex:column >
                    <apex:outputPanel >
                        <apex:commandButton action="{!onAddCondition}" immediate="false" reRender="row" value="+">
                            <apex:param name="selectedId" value="{!row.id}"/>
                        </apex:commandButton>
                        <apex:commandButton action="{!onRemoveCondition}" immediate="false" reRender="row" value="-">
                            <apex:param name="selectedId" value="{!row.id}"/>
                        </apex:commandButton>
                    </apex:outputPanel>
                </apex:column>
                <apex:column headerValue="{!$Label.Quantity}">
                    <apex:inputField value="{!row.dealRegProduct.Quantity__c}" required="true"/>
                </apex:column>
                <apex:column headerValue="Product Family">
                	<apex:outputPanel>
                    	<apex:SelectList value="{!currentProductFamily}" size="1" multiselect="False" >                            
                              <apex:selectOptions value="{!ListGroups}"/>                                 
                                  <apex:actionsupport rerender="theProducts" event="onchange" status="loadingProducts" />
                         </apex:SelectList>   
                    </apex:outputPanel>
                </apex:column>
                <apex:column headerValue="{!$Label.Product}">
                    <apex:actionstatus startStyleClass="statusMessage" startText="Please Wait,Loading Products.." id="loadingProducts"/>
                    <apex:outputPanel id="theProducts">
                        <apex:SelectList value="{!row.dealRegProduct.Product__c}" size="1" multiselect="false" >
                            <apex:selectOptions value="{!listProducts}"/>
                        </apex:SelectList>
                    </apex:outputPanel>
                </apex:column>
                <!-- Old Product selection 
					<apex:column headerValue="{!$Label.Product}">
                    <apex:selectList size="1" value="{!row.dealRegProduct.Product__c}" required="true">
                        <apex:selectOptions value="{!productOptions}"/>
                    </apex:selectList>
                </apex:column>
               ****Capacity view not being utilized currently*****
                <apex:column headerValue="Capacity">
                    <apex:selectList size="1" value="{!row.dealRegProduct.Storage_Capacity__c}" required="false">
                        <apex:selectOptions value="{!productCapacities}"/>
                    </apex:selectList>
                </apex:column>-->
                
                
            </apex:pageBlockTable> 
        </apex:pageBlock>

    </apex:form>
    
</apex:page>