• KrishHari
  • NEWBIE
  • 55 Points
  • Member since 2013

  • Chatter
    Feed
  • 2
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 1
    Questions
  • 13
    Replies

I am trying to execute this custom handler for my object, and its related child records.  For some reason (probably an obvious one) I cannot seem to get this to work correctly and keep getting errors when I go to save.  Is there any assistance that could be given?

 

public with sharing class CustomSPAPartyMasterHandler {
    public static final String relRegexName = '[<][a-zA-Z0-9\\s="^#!{}_.]*';
    public static final String endChild = '</';
    public static final String endNode = '>';
    public static final String firstMatchedChild = '(.)*?';
    public static final String regexObjField = '[{][!][\\w.]+[}]';
    public static final String emptyString = '';
    
    //Empty Constructor
    public CustomSPAPartyMasterHandler() {
        
    }
    
    //Generate XML for multiple SPA Discounts
    public static String handleSPADiscount() {
        String relName = 'relationName="#SPA_Discount__r:SPA_Discount__c#"';
        String message = '<?xml version="1.0"?><ProcessSPA><SPA><SPA_Discount relationName="#SPA_Discount__r:SPA_Discount__c#"><Name>{!SPA_Discount__r.Name}</Name><Catalog>{!SPA_Discount__r.Catalog__c}</Catalog><AWC Free Freight>{!SPA_Discount__r.AWC_F_Frt__c}</AWC Free Freight><Reason>{!SPA_Discount__r.Reason__c}</Reason><CompetitorName>{!SPA_Discount__r.Competitor_Name__c}</CompetitorName><SalesCommisionSplit>{!SPA_Discount__r.Sales_Commision_Split__c}</SalesCommisionSplit></Optionforsplitchoice>{!SPA_Discount__r.Option_For_SPlit_Choice__c}</Optionforsplitchoice><Shiptorepfirstname>{!SPA_Discount__r.Ship_To_Rep_First_Name__c}</Shiptorepfirstname><Shiptolastname>{!SPA_Discount__r.Ship_To_Rep_Last_Name__c}</Shiptolastname><Discounttype>{!SPA_Discount__r.Discount_Type__c}</Discounttype><Netprice>{!SPA_Discount__r.Net_Price__c}</Netprice><Discountlevel>{!SPA_Discount__r.Discount_Level__c}</Discountlevel><Spiff>{!SPA_Discount__r.Spiff__c}</Spiff><Netexpectedordervalue>{!SPA_Discount__r.Net_Expected_Order_Value__c}</Netexpectedordervalue><Minimumorderquantity>{!SPA_Discount__r.Minimum_Order_Quantity}</Minimumorderquantity><PartNumber>{!SPA_Discount__r.Part_Number__c}</PartNumber></SPAdiscount></ProcessSPA>';
        String SPADiscountXML = getChildXml(message, relName);
        List<SPA_Discount__c> SPADiscountLst = null;
    
        String spQuery= 'Select  sp.Id, ' +
                    ' (Select Name, SPA_Agreement__c,Catalog__c, Reason__c, Competitor_Name__c, Sales_Commision_Split__c, Option_For_Split_Choice__c, Ship_To_Rep_First_Name__c, Ship_To_Rep_Last_Name__c, AWC_F_Frt__c, Part_Number__c,Minimum_Order_Quantity,Net_Expected_Order_Value__c,Spiff__c,Discount_Level__c,Net_Price__c,Discount_Type__c,Ship_To_Rep_Last_Name__c' + 
                    ' From SPA_Discount__r) From SPA__c sp';
        list<SPA__c> lstSPA = database.query(spQuery);
        if(lstSPA != null && lstSPA .size()  > 0 ){
            SPA__c SPA= lstSPA [0];
            SPADiscountLst = lstSPA[0].SPA_Discount__r; 
        }
        if(SPADiscountLst !=null && !SPADiscountLst.isEmpty()) {
            List<String> fields = getFieldsFromXmlPart(SPADiscountXML);
            if(fields != null && !fields.isEmpty()) {
                String childXml;
                String allChildXml = '';
                for(SPA_Discount__c spadiscount: SPADiscountLst){
                    childXml = SPADiscountXML;
                    for(Integer cnt=0;cnt<fields.size();cnt++){
                        String objName = fields[cnt].split('\\.')[0];
                        string fldname = fields[cnt].split('\\.')[1];       
                        childXml = childXml.replace('{!'+fields[cnt]+'}',
                            htmlEncode(String.valueOf(personBillingAddress.get(fldname))));
                    }
                    allChildXml = allChildXml + childXml;
                }
                
                if(allChildXml!='')
                {
                    allChildXml = allChildXml.replace(' ' + relName, emptyString);
                    message = message.replace(SPADiscountXML, allChildXml);
                }
            }
        }
        return message;
    }
    
    //get SPA_Discount from the main XML
    public static String getChildXml(String message, String searchString) {
        Pattern patt;
        Matcher mat;
        string regex = relRegexName+searchString+endNode;
        patt =Pattern.compile(regex);
        system.debug('--- search string>>' + regex);
        mat=patt.matcher(message);
        String elm;
        if(mat.find()){
            elm = mat.group(0);
        }
        System.debug('mat.grp>> '+ elm);
        if(elm!=null && elm!=''){
            elm=elm.replace('>','/>');
            DOM.Document domDoc = new DOM.Document();
            domDoc.load(elm);
            Dom.XmlNode rootXmlNode = domDoc.getRootElement();
            String rootNodeName = rootXmlNode.getName();
            System.debug(rootNodeName);
            String endTag = endChild + rootNodeName + endNode;
            regex = relRegexName+searchString+endNode+firstMatchedChild+endTag;
            System.debug('>>>full regex: '+regex);
            patt =Pattern.compile(regex);
            mat=patt.matcher(message);
            if(mat.find()){
                elm = mat.group(0);
            }
            System.debug('mat.grp>> '+ elm);
        }
        return elm;
    }
    
    //get fields from xml
    public static List<String> getFieldsFromXmlPart(String xml) {
        Pattern patt;
        Matcher mat;
        List<String> fields = new List<String>();
        patt = Pattern.compile(regexObjField);
        System.debug('xml>>>>' + xml);
        if(xml != '' && xml != null) {
            mat = patt.matcher(xml);
            while(mat.find()){
                String fieldName =  mat.group();
                fieldName = fieldName.replace('{!','');
                fieldName = fieldName.replace('}','');
                fields.add(fieldName);
            }
        } 
        return fields;
    }
    
    public static string htmlEncode(String str) {
        if(!StringUtil.isNull(str))
            return str.Replace('&', '&amp;').Replace('<', '&lt;').Replace('>', '&gt;').Replace('\"', '&quot;').Replace('\'', '&apos;');
        else return str;
    }
}

 

 

I haven't dealt with writing code for Visualforce pages yet. We have a search function for contacts that allows you to search by Zipcode and City. We want to add the ability to search by State and by contact Owner. I have adjusted most of the code so far, but I'm getting a 

 

Line 84: "Method Does Not Exist or Incorrect Signature: getContactsByState(LIST<String>)" error.

 

Do I have to define this method in the visualforce page as well with a Script? If code is needed:

public with sharing class TerritorySearchController  
{
    public String searchType { public get; public set; }  
    public String searchValue { public get; public set; }
    public String zipcode { public get; public set; }  
    public String contactType { public get; public set; }  //Contact_Type__c
    public String statusType { public get; public set; } //Producer_Status__c / Prospect_Status__c
    
    public String citySearch { public get; public set; }
    public String citySearchResults { public get; public set; }
    public String citySearchSelected { public get; public set; }
    
    public String stateSearch { public get; public set; }
    public String stateSearchResults { public get; public set; }
    public String stateSearchSelected { public get; public set; }
    
    public String ownerSearch { public get; public set; }
    public String ownerSearchResults { public get; public set; }
    public String ownerSearchSelected { public get; public set; }
    
    public List<Contact> reps { public get; private set; }
    public List<Contact> repl {public get; private set; }
    public List<Contact> repo {public get; private set; }
    public Boolean mapView { public get; private set; }
    
    public TerritorySearchController()
    {
        this.reps=new List<Contact>();
        this.searchType = getParam('searchType', 'zipcode');
        this.searchValue = getParam('searchValue', '');
        this.zipcode = getParam('zipcode', '');
        this.contactType = getParam('contactType', '');
        this.statusType = getParam('statusType', '');
        this.citySearch = getParam('citySearch', '');
        this.citySearchResults = '';
        this.citySearchSelected = '';
        this.stateSearch = getParam('stateSearch', '');
        this.stateSearchResults = '';
        this.stateSearchSelected = '';
        this.ownerSearch = getParam('ownerSearch', '');
        this.ownerSearchResults = '';
        this.ownerSearchSelected = '';
        this.mapView = getBooleanParam('mapView', false);
    }
    
    public String getParam(String name, String defaultValue) {
        String value = ApexPages.currentPage().getParameters().get(name);
        return value == null ? defaultValue : value;
    }
    
    public Boolean getBooleanParam(String name, Boolean defaultValue) {
        String value = ApexPages.currentPage().getParameters().get(name);
        return value == null ? defaultValue : 'true'.equalsIgnoreCase(value);
    }
    
    public PageReference processSearch()
    {
        PageReference p=null;
        
        if (this.searchType=='city')
            p=searchCities();
        else if(this.searchType=='state')
                p=searchStates();
        else if(this.searchType=='zipcode')
                p=searchZips();
        else if(this.searchType=='owner')
                p=searchOwners();
            
        return p;
    }
    
    public PageReference searchZips()
    {
        List<String > lZips=new List<String>();
        lZips.add(this.searchValue);
        this.reps=getContactsByZip(lZips);
        return null;
    }
    
    public PageReference searchStates()
    {
        List<String> lStates=new List<String>();
        lStates.add(this.searchValue);
        this.reps=getContactsByState(lStates);
        return null;
    }
    
    public PageReference searchOwners()
    {
        List<String > lOwners=new List<String>();
        lOwners.add(this.searchValue);
        this.reps=getContactsByOwner(lOwners);
        return null;
    }
    
        public PageReference searchForCities()
    {
        String str='';
        this.citySearchResults='[';
        String strCity=this.citySearch; //Apexpages.currentPage().getParameters().get('citySearch');
        String strSOQL='SELECT Id, Name, City__c, State__c FROM Zip_Codes__c WHERE City__c LIKE \''+strCity+'%\' ORDER BY State__c LIMIT 10';
        System.debug(strSOQL);
        List<Zip_Codes__c> lZ=Database.query(strSOQL);
        Set<String> sZ=new Set<String>();
        
        for(Zip_Codes__c z : lZ)
        {
            str=z.City__c+', '+z.State__c;
            
            if(!sZ.contains(str))
            {
                if(sZ.size()>0)
                  this.citySearchResults=this.citySearchResults+',';
                  
                this.citySearchResults=this.citySearchResults+' { value: \''+z.Id+'\', label: \''+str.replace('\'', '\\\'')+'\'} ';
                sZ.add(str);
            }
        }
                    
        this.citySearchResults=this.citySearchResults+']';
        return null;
    }
    
    public PageReference searchCities()
    {
        this.reps=getContactsByCity(this.searchValue);
        return null;
    }

    public PageReference searchForStates()
    {
        String str='';
        this.stateSearchResults='[';
        String strState=this.stateSearch; //Apexpages.currentPage().getParameters().get('stateSearch');
        String strSOQL='SELECT Id, Name, City__c, State__c FROM Zip_Codes__c WHERE State__c LIKE \''+strState+'%\' ORDER BY City__c LIMIT 10';
        System.debug(strSOQL);
        List<Zip_Codes__c> lS=Database.query(strSOQL);
        Set<String> sS=new Set<String>();
        
        for(Zip_Codes__c s : ls)
        {
            str=s.City__c+', '+s.State__c;
            
            if(!stS.contains(str))
            {
                if(stS.size()>0)
                  this.stateSearchResults=this.stateSearchResults+',';
                  
                this.stateSearchResults=this.stateSearchResults+' { value: \''+s.Id+'\', label: \''+str.replace('\'', '\\\'')+'\'} ';
                stS.add(str);
            }
        }
                    
        this.stateSearchResults=this.stateSearchResults+']';
        return null;
    }

        public PageReference searchForOwners()
    {
        String str='';
        this.ownerSearchResults='[';
        String strOwner=this.ownerSearch; //Apexpages.currentPage().getParameters().get('ownerSearch');
        String strSOQL='SELECT Id, Name, City__c, State__c FROM Zip_Codes__c WHERE Owner__c LIKE \''+strOwner+'%\' ORDER BY Owner__c LIMIT 10';
        System.debug(strSOQL);
        List<Zip_Codes__c> lO=Database.query(strSOQL);
        Set<String> sO=new Set<String>();
        
        for(Zip_Codes__c o : lO)
        {
            str=o.City__c+', '+o.State__c+', '+o.Owner__c;
            
            if(!sO.contains(str))
            {
                if(sO.size()>0)
                  this.ownerSearchResults=this.ownerSearchResults+',';
                  
                this.ownerSearchResults=this.ownerSearchResults+' { value: \''+o.Id+'\', label: \''+str.replace('\'', '\\\'')+'\'} ';
                sO.add(str);
            }
        }
                    
        this.ownerSearchResults=this.ownerSearchResults+']';
        return null;
    }

    public Integer getRepCount()
    {
        return this.reps.size();
    }
    
    private List<Contact> getContactsByZip(List<String> lZips)
    {   
        List<Contact> lContacts=new List<Contact>();
        
        if(contactType==null)
            contactType=''; 
        
        String strZipCodes=' \'0\'';
        String strSOQL='SELECT ID, Name, MailingStreet, MailingCity, MailingState, MailingPostalCode, MailingCountry, Phone, Email, Contact_Type__c, Prospect_Status__c, Producer_Status__c, Broker_Dealer_Name__c FROM Contact ';
        
        for(String s: lZips)
        {
            if(s.trim()!='')
            {
                strZipCodes=strZipCodes+' OR mailingpostalcode like \''+s+'%\' ';
                this.zipcode=s;
            }
        }
         
        strSOQL=strSOQL+' WHERE (MailingPostalCode like' + strZipCodes + ') ';
      //strSOQL=strSOQL+' AND SA_Status__c = \'NS REIT - Signed Selling Agreement\' ';
        strSOQL=strSOQL+' AND ( NS_Income_II_SA_Status__c = \'NS I2 - Signed Selling Agreement\' OR NS_HI_SA_Status__c = \'NS HI - Signed Selling Agreement\' )';
        strSOQL=strSOQL+' AND Contact_Type__c != \'POND List\' ';
        strSOQL=strSOQL+' AND Contact_Type__c != null ';
        strSOQL=strSOQL+' AND OWNER__c !=null ';
        
        //
        // Handle producer/prospect types.
        //
        
        if ('Un-Profiled'.equalsIgnoreCase(contactType)) {
            strSOQL += ' AND Contact_Type__c = \'Un-Profiled\' ';
        } else if ('All Producers'.equalsIgnoreCase(contactType)) {
            strSOQL += ' AND Contact_Type__c = \'Producer\'';
        } else if ('A Producers'.equalsIgnoreCase(contactType)) {
            strSOQL += ' AND Contact_Type__c = \'Producer\' AND Producer_Status__c like \'Producer A-%\'';
        } else if ('B Producers'.equalsIgnoreCase(contactType)) {
            strSOQL += ' AND Contact_Type__c = \'Producer\' AND Producer_Status__c like \'Producer B-%\'';
        } else if ('C Producers'.equalsIgnoreCase(contactType)) {
            strSOQL += ' AND Contact_Type__c = \'Producer\' AND Producer_Status__c like \'Producer C-%\'';
        } else if ('Sphere Of Influence Producers'.equalsIgnoreCase(contactType)) {
            strSOQL += ' AND Contact_Type__c = \'Producer\' AND Producer_Status__c like \'Sphere of Influence%\'';
        } else if ('All Prospects'.equalsIgnoreCase(contactType)) {
            strSOQL += ' AND Contact_Type__c = \'Prospect\'';
        } else if ('A Prospects'.equalsIgnoreCase(contactType)) {
            strSOQL += ' AND Contact_Type__c = \'Prospect\' AND Prospect_Status__c like \'Prospect A-%\'';
        } else if ('B Prospects'.equalsIgnoreCase(contactType)) {
            strSOQL += ' AND Contact_Type__c = \'Prospect\' AND Prospect_Status__c like \'Prospect B-%\'';
        } else if ('C Prospects'.equalsIgnoreCase(contactType)) {
            strSOQL += ' AND Contact_Type__c = \'Prospect\' AND Prospect_Status__c like \'Prospect C-%\'';
        } else if ('Sphere Of Influence Prospects'.equalsIgnoreCase(contactType)) {
            strSOQL += ' AND Contact_Type__c = \'Prospect\' AND Prospect_Status__c like \'Sphere of Influence%\'';
        }
        
        System.debug(strSOQL);
        lContacts=Database.query(strSOQL);
        return lContacts;
    }
    
    private List<Contact> getContactsByCity(String strCityState)
    {
        List<Contact> lContacts=new List<Contact>();
        Integer i=strCityState.lastIndexOf(',');
        
        if(i<1)
            return lContacts;
            
        String strCity=strCityState.substring(0, i).trim();
        String strState=strCityState.substring(i+1).trim().toUpperCase();
        
        System.debug('SELECT Id,Name FROM Zip_Codes__c WHERE City__c =\''+strCity+'\' AND State__c=\''+strState+'\' ORDER BY longitude__c');
        List<Zip_Codes__c> lZ=[SELECT Id,Name FROM Zip_Codes__c WHERE City__c=:strCity AND State__c=:strState ORDER BY longitude__c];
        List<String> lZips=new List<String>();  
        
        for(Zip_Codes__c z : lZ)
        {
            lZips.add(z.Name);    
        }
        
        lContacts=getContactsByZip(lZips);
        return lContacts;       
    }
    
    private List<Contact> getContactsByState(String strCityState)
    {
        list<Contact> llContacts=new List<Contact>();
        Integer i=strCityState.lastIndexOf(',');
        
        if(i<1)
            return llContacts;
            
        String strCity=strCityState.substring(0, i).trim();
        String strState=strCityState.substring(i+1).trim().toUpperCase();
        
        System.debug('SELECT Id,Name FROM Zip_Codes__c WHERE City__c =\''+strCity+'\' AND State__c=\''+strState+'\' ORDER BY longitude__c');
        List<Zip_Codes__c> lS=[SELECT Id, Name, City__c, State__c FROM Zip_Codes__c WHERE City__c=:strCity AND State__c=:strState ORDER BY City__c LIMIT 10];
        List<String> lStates=new List<String>();  
        
        for(Zip_Codes__c s : lS)
        {
            lStates.add(s.Name);    
        }
        
        llContacts=getContactsByState(lStates);
        return llContacts;       
    }
    
    private List<Contact> getContactsByOwner(String strOwner)
    {
        List<Contact> lllContacts=new List<Contact>();
        List<Zip_Codes__c> lO=[select Id, Name, longitude__c, latitude__c, Territory__c, Owner__c, City__c, State__c from Zip_Codes__c WHERE Owner__r.Name=:strOwner];
        List<String> lOwners=new List<String>();  
        
        for(Zip_Codes__c o : lO)
        {
            lOwners.add(o.Name);    
        }
        
        lllContacts=getContactsByOwner(lOwners);
        return lllContacts;   
    }
    
    public Boolean getIsDisabledDownloadCSV() {
        return reps == null || reps.size() == 0;
    }
    
    public PageReference redirectToCSV() {
        processSearch();
        
        String documentData = '';
        documentData += '"Name",';
        documentData += '"Broker_Dealer_Name__c",';
        documentData += '"MailingStreet",';
        documentData += '"MailingCity",';
        documentData += '"MailingState",';
        documentData += '"MailingPostalCode",';
        documentData += '"Phone",';
        documentData += '"Email",';
        documentData += '"Last Completed Event",';
        documentData += '"Contact_Type__c"\r\n';
        
        for(Contact contact : reps) {
            documentData += '"' + contact.Name + '",';
            documentData += '"' + contact.Broker_Dealer_Name__c + '",';
            documentData += '"' + contact.MailingStreet + '",';
            documentData += '"' + contact.MailingCity + '",';
            documentData += '"' + contact.MailingState + '",';
            documentData += '"' + contact.MailingPostalCode + '",';
            documentData += '"' + contact.Phone + '",';
            documentData += '"' + contact.Email + '",';
            documentData += '"' + contact.Last_Event_Date__c + '",';
            documentData += '"' + contact.Contact_Type__c + '"\r\n';
        }
        
        Document document = new Document();
        document.Body = Blob.valueOf(documentData);
        document.ContentType = 'text/csv';
        document.FolderId = UserInfo.getUserId();
        document.Name = 'Territory Search - CSV Export - ' + DateTime.now().format() + '.csv';
        insert document;
        
        PageReference pageReference = new PageReference('/servlet/servlet.FileDownload?file=' + document.Id);
        pageReference.setRedirect(true);
        return pageReference;
    }
    
    public String getMapViewUrl() {
        PageReference pageReference = System.Page.TerritorySearch;
        pageReference.getParameters().put('searchType', searchType);
        pageReference.getParameters().put('searchValue', searchValue);
        pageReference.getParameters().put('zipcode', zipcode);
        pageReference.getParameters().put('contactType', contactType);
        pageReference.getParameters().put('statusType', statusType);
        pageReference.getParameters().put('citySearch', citySearch);
        pageReference.getParameters().put('stateSearch', stateSearch);
        pageReference.getParameters().put('ownerSearch', ownerSearch);
        pageReference.getParameters().put('mapView', 'true');
        return pageReference.getUrl();
    }
}

 

I'm using visual force dynamic bindings with the dynamic visual force components and I'm not able to get it work. Here is the situation.

 

Requirement:

  • The user logs in feedback which is a single large text stored in a text area field in a custom object named Feedback. Later, the user can split them into multiple feedbacks and all these multiple feedbacks are stored as child records of the master feedback.

Design: 

I have a visual force page with two output panels: One panel is to display the parent feedback (the 2nd panel is not rendered at this time). The user can edit this text and uses a delimiter (For e.g. '###') to indicate the text to be split into multiple feedbacks and clicks 'Split' button. This posts back to a controller where the 1st panel is set to not to render and the 2nd panel is set to render. The code looks like below:

 

<apex:page controller="MykController1" >
<apex:form>
  <!-- 1st panel -->
  <apex:outputPanel rendered="{!showSplitFeedback">
     <apex:inputtextarea value="{!feedback.Client_Remarks__c}" rows="25" cols="160"> 
<apex:commandButton id="nextConfirmButton" value="Next: Confirm Split" action="{!nextConfirmSplit}" disabled="false" />
</apex:outputPanel> <!-- 2nd panel --> <apex:outputPanel rendered="{!showConfirmSplitFeedback}"> <apex:dynamicComponent componentValue="{!feedbackTabs}"/> </apex:outputPanel> </apex:form>

 

Since the number of child feedbacks is dynamic, I can't have static form, so I went with visual force dynamic components, where I programmatically create the tabs and associate each tab to each of those child feedbacks. Now the user can edit the text in each of these child feedbacks and clicks submit which then should create child feedback records. The problem here is that I'm not able to bind the strings that I split to these text area. Here is the code for the controller. 

 

public class MyController {
  private String delimiter = '###';
  public List<FeedbackWrapper> listFeedbackWrapper;
  public Boolean showSplitFeedback { get; set; }
  public Boolean showConfirmSplitFeedback { get; set; }

  public Component.Apex.TabPanel getFeedbackTabs() {
		listFeedbackWrapper = splitFeedback();
		
		Component.Apex.TabPanel dynTabPanel = new Component.Apex.TabPanel(switchType = 'Ajax', tabClass='activeTab', inactiveTabClass='inactiveTab', value='activeTab');
		Integer index = 0;
		tabCount = listFeedbackWrapper.size();
		for (FeedbackWrapper fbWrapper: listFeedbackWrapper) {
			dynTabPanel.childComponents.add(createChildFeedbackTab(index++, fbWrapper));
		} 
		return dynTabPanel;
  }

  private Component.Apex.Tab createChildFeedbackTab(Integer index, FeedbackWrapper feedbackWrapper) {
		
		Component.Apex.Tab tab = new Component.Apex.Tab(Id = 'tab' + index, Label = 'Feedack' + string.valueOf((index-1)));
		createTabFields(index, tab, feedbackWrapper);
	   	Component.Apex.CommandButton prev = new Component.Apex.CommandButton(value = 'Previous');
	   	tab.childComponents.add(prev);
	    	Component.Apex.CommandButton next = new Component.Apex.CommandButton(value = 'Next');
	    	tab.childComponents.add(next);
		return tab;		    
	}
	
	private List<FeedbackWrapper> splitFeedback() {
		String clientRemarks = feedback.Client_Remarks__c;
		String[] strRemarksList = clientRemarks.split(delimiter, 0);
		listFeedbackWrapper = new List<FeedbackWrapper>();
		for (String remark : strRemarksList) {
			FeedbackWrapper fbWrapper = new FeedbackWrapper(remark);
			listFeedbackWrapper.add(fbWrapper);
		}
		return listFeedbackWrapper; 
	}
	
	private void createTabFields(Integer index, Component.Apex.Tab tab, FeedbackWrapper feedbackWrapper) {
		Component.Apex.PageBlock dynPageBlock = new Component.Apex.PageBlock();
		Component.Apex.PageBlockSection pgBlockSection = new Component.Apex.PageBlockSection(columns=2);
		
		Component.Apex.PageBlockSectionItem pgBlockSectionItem1 = new Component.Apex.PageBlockSectionItem();
		Component.Apex.OutputLabel lblIssueRemarks = new Component.Apex.OutputLabel(Id = tab.Id + 'lblIssueRemarks', value = 'Issue Remarks: ' );
		
		Component.Apex.PageBlockSectionItem pgBlockSectionItem2 = new Component.Apex.PageBlockSectionItem();
		Component.Apex.InputTextArea txtAreaIssueRemarks = new Component.Apex.InputTextArea(Id = tab.Id + 'txtIssueRemarks', cols = 160, rows = 10);
		txtAreaIssueRemarks.expressions.value = '{!getFeedbackWrapperList[index].issueRemarks}';
		
		pgBlockSectionItem1.childComponents.add(lblIssueRemarks);
		pgBlockSectionItem2.childComponents.add(txtAreaIssueRemarks);
		
		pgBlockSection.childComponents.add(pgBlockSectionItem1);
		pgBlockSection.childComponents.add(pgBlockSectionItem2);
		
		dynPageBlock.childComponents.add(pgBlockSection);
		
		tab.childComponents.add(dynPageBlock);
		
	}
   // inner class
   class FeedbackWrapper {
		String title;
		String issueRemarks;
		public FeedbackWrapper(String remark) {
			issueRemarks = remark;
		}
	}
}

 

I have removed some code in order to reduce the clutter.

 

I think I followed as prescribed in this link for dynamic bindings. Another one here.

 

So, how can I bind a list dynamically to a dynamic visual force component? I need to bind it because, I need to get the updated text in the post back in order to save the updated text to the database. Any help is much appreciated.

 

I am trying to execute this custom handler for my object, and its related child records.  For some reason (probably an obvious one) I cannot seem to get this to work correctly and keep getting errors when I go to save.  Is there any assistance that could be given?

 

public with sharing class CustomSPAPartyMasterHandler {
    public static final String relRegexName = '[<][a-zA-Z0-9\\s="^#!{}_.]*';
    public static final String endChild = '</';
    public static final String endNode = '>';
    public static final String firstMatchedChild = '(.)*?';
    public static final String regexObjField = '[{][!][\\w.]+[}]';
    public static final String emptyString = '';
    
    //Empty Constructor
    public CustomSPAPartyMasterHandler() {
        
    }
    
    //Generate XML for multiple SPA Discounts
    public static String handleSPADiscount() {
        String relName = 'relationName="#SPA_Discount__r:SPA_Discount__c#"';
        String message = '<?xml version="1.0"?><ProcessSPA><SPA><SPA_Discount relationName="#SPA_Discount__r:SPA_Discount__c#"><Name>{!SPA_Discount__r.Name}</Name><Catalog>{!SPA_Discount__r.Catalog__c}</Catalog><AWC Free Freight>{!SPA_Discount__r.AWC_F_Frt__c}</AWC Free Freight><Reason>{!SPA_Discount__r.Reason__c}</Reason><CompetitorName>{!SPA_Discount__r.Competitor_Name__c}</CompetitorName><SalesCommisionSplit>{!SPA_Discount__r.Sales_Commision_Split__c}</SalesCommisionSplit></Optionforsplitchoice>{!SPA_Discount__r.Option_For_SPlit_Choice__c}</Optionforsplitchoice><Shiptorepfirstname>{!SPA_Discount__r.Ship_To_Rep_First_Name__c}</Shiptorepfirstname><Shiptolastname>{!SPA_Discount__r.Ship_To_Rep_Last_Name__c}</Shiptolastname><Discounttype>{!SPA_Discount__r.Discount_Type__c}</Discounttype><Netprice>{!SPA_Discount__r.Net_Price__c}</Netprice><Discountlevel>{!SPA_Discount__r.Discount_Level__c}</Discountlevel><Spiff>{!SPA_Discount__r.Spiff__c}</Spiff><Netexpectedordervalue>{!SPA_Discount__r.Net_Expected_Order_Value__c}</Netexpectedordervalue><Minimumorderquantity>{!SPA_Discount__r.Minimum_Order_Quantity}</Minimumorderquantity><PartNumber>{!SPA_Discount__r.Part_Number__c}</PartNumber></SPAdiscount></ProcessSPA>';
        String SPADiscountXML = getChildXml(message, relName);
        List<SPA_Discount__c> SPADiscountLst = null;
    
        String spQuery= 'Select  sp.Id, ' +
                    ' (Select Name, SPA_Agreement__c,Catalog__c, Reason__c, Competitor_Name__c, Sales_Commision_Split__c, Option_For_Split_Choice__c, Ship_To_Rep_First_Name__c, Ship_To_Rep_Last_Name__c, AWC_F_Frt__c, Part_Number__c,Minimum_Order_Quantity,Net_Expected_Order_Value__c,Spiff__c,Discount_Level__c,Net_Price__c,Discount_Type__c,Ship_To_Rep_Last_Name__c' + 
                    ' From SPA_Discount__r) From SPA__c sp';
        list<SPA__c> lstSPA = database.query(spQuery);
        if(lstSPA != null && lstSPA .size()  > 0 ){
            SPA__c SPA= lstSPA [0];
            SPADiscountLst = lstSPA[0].SPA_Discount__r; 
        }
        if(SPADiscountLst !=null && !SPADiscountLst.isEmpty()) {
            List<String> fields = getFieldsFromXmlPart(SPADiscountXML);
            if(fields != null && !fields.isEmpty()) {
                String childXml;
                String allChildXml = '';
                for(SPA_Discount__c spadiscount: SPADiscountLst){
                    childXml = SPADiscountXML;
                    for(Integer cnt=0;cnt<fields.size();cnt++){
                        String objName = fields[cnt].split('\\.')[0];
                        string fldname = fields[cnt].split('\\.')[1];       
                        childXml = childXml.replace('{!'+fields[cnt]+'}',
                            htmlEncode(String.valueOf(personBillingAddress.get(fldname))));
                    }
                    allChildXml = allChildXml + childXml;
                }
                
                if(allChildXml!='')
                {
                    allChildXml = allChildXml.replace(' ' + relName, emptyString);
                    message = message.replace(SPADiscountXML, allChildXml);
                }
            }
        }
        return message;
    }
    
    //get SPA_Discount from the main XML
    public static String getChildXml(String message, String searchString) {
        Pattern patt;
        Matcher mat;
        string regex = relRegexName+searchString+endNode;
        patt =Pattern.compile(regex);
        system.debug('--- search string>>' + regex);
        mat=patt.matcher(message);
        String elm;
        if(mat.find()){
            elm = mat.group(0);
        }
        System.debug('mat.grp>> '+ elm);
        if(elm!=null && elm!=''){
            elm=elm.replace('>','/>');
            DOM.Document domDoc = new DOM.Document();
            domDoc.load(elm);
            Dom.XmlNode rootXmlNode = domDoc.getRootElement();
            String rootNodeName = rootXmlNode.getName();
            System.debug(rootNodeName);
            String endTag = endChild + rootNodeName + endNode;
            regex = relRegexName+searchString+endNode+firstMatchedChild+endTag;
            System.debug('>>>full regex: '+regex);
            patt =Pattern.compile(regex);
            mat=patt.matcher(message);
            if(mat.find()){
                elm = mat.group(0);
            }
            System.debug('mat.grp>> '+ elm);
        }
        return elm;
    }
    
    //get fields from xml
    public static List<String> getFieldsFromXmlPart(String xml) {
        Pattern patt;
        Matcher mat;
        List<String> fields = new List<String>();
        patt = Pattern.compile(regexObjField);
        System.debug('xml>>>>' + xml);
        if(xml != '' && xml != null) {
            mat = patt.matcher(xml);
            while(mat.find()){
                String fieldName =  mat.group();
                fieldName = fieldName.replace('{!','');
                fieldName = fieldName.replace('}','');
                fields.add(fieldName);
            }
        } 
        return fields;
    }
    
    public static string htmlEncode(String str) {
        if(!StringUtil.isNull(str))
            return str.Replace('&', '&amp;').Replace('<', '&lt;').Replace('>', '&gt;').Replace('\"', '&quot;').Replace('\'', '&apos;');
        else return str;
    }
}

 

 

I haven't dealt with writing code for Visualforce pages yet. We have a search function for contacts that allows you to search by Zipcode and City. We want to add the ability to search by State and by contact Owner. I have adjusted most of the code so far, but I'm getting a 

 

Line 84: "Method Does Not Exist or Incorrect Signature: getContactsByState(LIST<String>)" error.

 

Do I have to define this method in the visualforce page as well with a Script? If code is needed:

public with sharing class TerritorySearchController  
{
    public String searchType { public get; public set; }  
    public String searchValue { public get; public set; }
    public String zipcode { public get; public set; }  
    public String contactType { public get; public set; }  //Contact_Type__c
    public String statusType { public get; public set; } //Producer_Status__c / Prospect_Status__c
    
    public String citySearch { public get; public set; }
    public String citySearchResults { public get; public set; }
    public String citySearchSelected { public get; public set; }
    
    public String stateSearch { public get; public set; }
    public String stateSearchResults { public get; public set; }
    public String stateSearchSelected { public get; public set; }
    
    public String ownerSearch { public get; public set; }
    public String ownerSearchResults { public get; public set; }
    public String ownerSearchSelected { public get; public set; }
    
    public List<Contact> reps { public get; private set; }
    public List<Contact> repl {public get; private set; }
    public List<Contact> repo {public get; private set; }
    public Boolean mapView { public get; private set; }
    
    public TerritorySearchController()
    {
        this.reps=new List<Contact>();
        this.searchType = getParam('searchType', 'zipcode');
        this.searchValue = getParam('searchValue', '');
        this.zipcode = getParam('zipcode', '');
        this.contactType = getParam('contactType', '');
        this.statusType = getParam('statusType', '');
        this.citySearch = getParam('citySearch', '');
        this.citySearchResults = '';
        this.citySearchSelected = '';
        this.stateSearch = getParam('stateSearch', '');
        this.stateSearchResults = '';
        this.stateSearchSelected = '';
        this.ownerSearch = getParam('ownerSearch', '');
        this.ownerSearchResults = '';
        this.ownerSearchSelected = '';
        this.mapView = getBooleanParam('mapView', false);
    }
    
    public String getParam(String name, String defaultValue) {
        String value = ApexPages.currentPage().getParameters().get(name);
        return value == null ? defaultValue : value;
    }
    
    public Boolean getBooleanParam(String name, Boolean defaultValue) {
        String value = ApexPages.currentPage().getParameters().get(name);
        return value == null ? defaultValue : 'true'.equalsIgnoreCase(value);
    }
    
    public PageReference processSearch()
    {
        PageReference p=null;
        
        if (this.searchType=='city')
            p=searchCities();
        else if(this.searchType=='state')
                p=searchStates();
        else if(this.searchType=='zipcode')
                p=searchZips();
        else if(this.searchType=='owner')
                p=searchOwners();
            
        return p;
    }
    
    public PageReference searchZips()
    {
        List<String > lZips=new List<String>();
        lZips.add(this.searchValue);
        this.reps=getContactsByZip(lZips);
        return null;
    }
    
    public PageReference searchStates()
    {
        List<String> lStates=new List<String>();
        lStates.add(this.searchValue);
        this.reps=getContactsByState(lStates);
        return null;
    }
    
    public PageReference searchOwners()
    {
        List<String > lOwners=new List<String>();
        lOwners.add(this.searchValue);
        this.reps=getContactsByOwner(lOwners);
        return null;
    }
    
        public PageReference searchForCities()
    {
        String str='';
        this.citySearchResults='[';
        String strCity=this.citySearch; //Apexpages.currentPage().getParameters().get('citySearch');
        String strSOQL='SELECT Id, Name, City__c, State__c FROM Zip_Codes__c WHERE City__c LIKE \''+strCity+'%\' ORDER BY State__c LIMIT 10';
        System.debug(strSOQL);
        List<Zip_Codes__c> lZ=Database.query(strSOQL);
        Set<String> sZ=new Set<String>();
        
        for(Zip_Codes__c z : lZ)
        {
            str=z.City__c+', '+z.State__c;
            
            if(!sZ.contains(str))
            {
                if(sZ.size()>0)
                  this.citySearchResults=this.citySearchResults+',';
                  
                this.citySearchResults=this.citySearchResults+' { value: \''+z.Id+'\', label: \''+str.replace('\'', '\\\'')+'\'} ';
                sZ.add(str);
            }
        }
                    
        this.citySearchResults=this.citySearchResults+']';
        return null;
    }
    
    public PageReference searchCities()
    {
        this.reps=getContactsByCity(this.searchValue);
        return null;
    }

    public PageReference searchForStates()
    {
        String str='';
        this.stateSearchResults='[';
        String strState=this.stateSearch; //Apexpages.currentPage().getParameters().get('stateSearch');
        String strSOQL='SELECT Id, Name, City__c, State__c FROM Zip_Codes__c WHERE State__c LIKE \''+strState+'%\' ORDER BY City__c LIMIT 10';
        System.debug(strSOQL);
        List<Zip_Codes__c> lS=Database.query(strSOQL);
        Set<String> sS=new Set<String>();
        
        for(Zip_Codes__c s : ls)
        {
            str=s.City__c+', '+s.State__c;
            
            if(!stS.contains(str))
            {
                if(stS.size()>0)
                  this.stateSearchResults=this.stateSearchResults+',';
                  
                this.stateSearchResults=this.stateSearchResults+' { value: \''+s.Id+'\', label: \''+str.replace('\'', '\\\'')+'\'} ';
                stS.add(str);
            }
        }
                    
        this.stateSearchResults=this.stateSearchResults+']';
        return null;
    }

        public PageReference searchForOwners()
    {
        String str='';
        this.ownerSearchResults='[';
        String strOwner=this.ownerSearch; //Apexpages.currentPage().getParameters().get('ownerSearch');
        String strSOQL='SELECT Id, Name, City__c, State__c FROM Zip_Codes__c WHERE Owner__c LIKE \''+strOwner+'%\' ORDER BY Owner__c LIMIT 10';
        System.debug(strSOQL);
        List<Zip_Codes__c> lO=Database.query(strSOQL);
        Set<String> sO=new Set<String>();
        
        for(Zip_Codes__c o : lO)
        {
            str=o.City__c+', '+o.State__c+', '+o.Owner__c;
            
            if(!sO.contains(str))
            {
                if(sO.size()>0)
                  this.ownerSearchResults=this.ownerSearchResults+',';
                  
                this.ownerSearchResults=this.ownerSearchResults+' { value: \''+o.Id+'\', label: \''+str.replace('\'', '\\\'')+'\'} ';
                sO.add(str);
            }
        }
                    
        this.ownerSearchResults=this.ownerSearchResults+']';
        return null;
    }

    public Integer getRepCount()
    {
        return this.reps.size();
    }
    
    private List<Contact> getContactsByZip(List<String> lZips)
    {   
        List<Contact> lContacts=new List<Contact>();
        
        if(contactType==null)
            contactType=''; 
        
        String strZipCodes=' \'0\'';
        String strSOQL='SELECT ID, Name, MailingStreet, MailingCity, MailingState, MailingPostalCode, MailingCountry, Phone, Email, Contact_Type__c, Prospect_Status__c, Producer_Status__c, Broker_Dealer_Name__c FROM Contact ';
        
        for(String s: lZips)
        {
            if(s.trim()!='')
            {
                strZipCodes=strZipCodes+' OR mailingpostalcode like \''+s+'%\' ';
                this.zipcode=s;
            }
        }
         
        strSOQL=strSOQL+' WHERE (MailingPostalCode like' + strZipCodes + ') ';
      //strSOQL=strSOQL+' AND SA_Status__c = \'NS REIT - Signed Selling Agreement\' ';
        strSOQL=strSOQL+' AND ( NS_Income_II_SA_Status__c = \'NS I2 - Signed Selling Agreement\' OR NS_HI_SA_Status__c = \'NS HI - Signed Selling Agreement\' )';
        strSOQL=strSOQL+' AND Contact_Type__c != \'POND List\' ';
        strSOQL=strSOQL+' AND Contact_Type__c != null ';
        strSOQL=strSOQL+' AND OWNER__c !=null ';
        
        //
        // Handle producer/prospect types.
        //
        
        if ('Un-Profiled'.equalsIgnoreCase(contactType)) {
            strSOQL += ' AND Contact_Type__c = \'Un-Profiled\' ';
        } else if ('All Producers'.equalsIgnoreCase(contactType)) {
            strSOQL += ' AND Contact_Type__c = \'Producer\'';
        } else if ('A Producers'.equalsIgnoreCase(contactType)) {
            strSOQL += ' AND Contact_Type__c = \'Producer\' AND Producer_Status__c like \'Producer A-%\'';
        } else if ('B Producers'.equalsIgnoreCase(contactType)) {
            strSOQL += ' AND Contact_Type__c = \'Producer\' AND Producer_Status__c like \'Producer B-%\'';
        } else if ('C Producers'.equalsIgnoreCase(contactType)) {
            strSOQL += ' AND Contact_Type__c = \'Producer\' AND Producer_Status__c like \'Producer C-%\'';
        } else if ('Sphere Of Influence Producers'.equalsIgnoreCase(contactType)) {
            strSOQL += ' AND Contact_Type__c = \'Producer\' AND Producer_Status__c like \'Sphere of Influence%\'';
        } else if ('All Prospects'.equalsIgnoreCase(contactType)) {
            strSOQL += ' AND Contact_Type__c = \'Prospect\'';
        } else if ('A Prospects'.equalsIgnoreCase(contactType)) {
            strSOQL += ' AND Contact_Type__c = \'Prospect\' AND Prospect_Status__c like \'Prospect A-%\'';
        } else if ('B Prospects'.equalsIgnoreCase(contactType)) {
            strSOQL += ' AND Contact_Type__c = \'Prospect\' AND Prospect_Status__c like \'Prospect B-%\'';
        } else if ('C Prospects'.equalsIgnoreCase(contactType)) {
            strSOQL += ' AND Contact_Type__c = \'Prospect\' AND Prospect_Status__c like \'Prospect C-%\'';
        } else if ('Sphere Of Influence Prospects'.equalsIgnoreCase(contactType)) {
            strSOQL += ' AND Contact_Type__c = \'Prospect\' AND Prospect_Status__c like \'Sphere of Influence%\'';
        }
        
        System.debug(strSOQL);
        lContacts=Database.query(strSOQL);
        return lContacts;
    }
    
    private List<Contact> getContactsByCity(String strCityState)
    {
        List<Contact> lContacts=new List<Contact>();
        Integer i=strCityState.lastIndexOf(',');
        
        if(i<1)
            return lContacts;
            
        String strCity=strCityState.substring(0, i).trim();
        String strState=strCityState.substring(i+1).trim().toUpperCase();
        
        System.debug('SELECT Id,Name FROM Zip_Codes__c WHERE City__c =\''+strCity+'\' AND State__c=\''+strState+'\' ORDER BY longitude__c');
        List<Zip_Codes__c> lZ=[SELECT Id,Name FROM Zip_Codes__c WHERE City__c=:strCity AND State__c=:strState ORDER BY longitude__c];
        List<String> lZips=new List<String>();  
        
        for(Zip_Codes__c z : lZ)
        {
            lZips.add(z.Name);    
        }
        
        lContacts=getContactsByZip(lZips);
        return lContacts;       
    }
    
    private List<Contact> getContactsByState(String strCityState)
    {
        list<Contact> llContacts=new List<Contact>();
        Integer i=strCityState.lastIndexOf(',');
        
        if(i<1)
            return llContacts;
            
        String strCity=strCityState.substring(0, i).trim();
        String strState=strCityState.substring(i+1).trim().toUpperCase();
        
        System.debug('SELECT Id,Name FROM Zip_Codes__c WHERE City__c =\''+strCity+'\' AND State__c=\''+strState+'\' ORDER BY longitude__c');
        List<Zip_Codes__c> lS=[SELECT Id, Name, City__c, State__c FROM Zip_Codes__c WHERE City__c=:strCity AND State__c=:strState ORDER BY City__c LIMIT 10];
        List<String> lStates=new List<String>();  
        
        for(Zip_Codes__c s : lS)
        {
            lStates.add(s.Name);    
        }
        
        llContacts=getContactsByState(lStates);
        return llContacts;       
    }
    
    private List<Contact> getContactsByOwner(String strOwner)
    {
        List<Contact> lllContacts=new List<Contact>();
        List<Zip_Codes__c> lO=[select Id, Name, longitude__c, latitude__c, Territory__c, Owner__c, City__c, State__c from Zip_Codes__c WHERE Owner__r.Name=:strOwner];
        List<String> lOwners=new List<String>();  
        
        for(Zip_Codes__c o : lO)
        {
            lOwners.add(o.Name);    
        }
        
        lllContacts=getContactsByOwner(lOwners);
        return lllContacts;   
    }
    
    public Boolean getIsDisabledDownloadCSV() {
        return reps == null || reps.size() == 0;
    }
    
    public PageReference redirectToCSV() {
        processSearch();
        
        String documentData = '';
        documentData += '"Name",';
        documentData += '"Broker_Dealer_Name__c",';
        documentData += '"MailingStreet",';
        documentData += '"MailingCity",';
        documentData += '"MailingState",';
        documentData += '"MailingPostalCode",';
        documentData += '"Phone",';
        documentData += '"Email",';
        documentData += '"Last Completed Event",';
        documentData += '"Contact_Type__c"\r\n';
        
        for(Contact contact : reps) {
            documentData += '"' + contact.Name + '",';
            documentData += '"' + contact.Broker_Dealer_Name__c + '",';
            documentData += '"' + contact.MailingStreet + '",';
            documentData += '"' + contact.MailingCity + '",';
            documentData += '"' + contact.MailingState + '",';
            documentData += '"' + contact.MailingPostalCode + '",';
            documentData += '"' + contact.Phone + '",';
            documentData += '"' + contact.Email + '",';
            documentData += '"' + contact.Last_Event_Date__c + '",';
            documentData += '"' + contact.Contact_Type__c + '"\r\n';
        }
        
        Document document = new Document();
        document.Body = Blob.valueOf(documentData);
        document.ContentType = 'text/csv';
        document.FolderId = UserInfo.getUserId();
        document.Name = 'Territory Search - CSV Export - ' + DateTime.now().format() + '.csv';
        insert document;
        
        PageReference pageReference = new PageReference('/servlet/servlet.FileDownload?file=' + document.Id);
        pageReference.setRedirect(true);
        return pageReference;
    }
    
    public String getMapViewUrl() {
        PageReference pageReference = System.Page.TerritorySearch;
        pageReference.getParameters().put('searchType', searchType);
        pageReference.getParameters().put('searchValue', searchValue);
        pageReference.getParameters().put('zipcode', zipcode);
        pageReference.getParameters().put('contactType', contactType);
        pageReference.getParameters().put('statusType', statusType);
        pageReference.getParameters().put('citySearch', citySearch);
        pageReference.getParameters().put('stateSearch', stateSearch);
        pageReference.getParameters().put('ownerSearch', ownerSearch);
        pageReference.getParameters().put('mapView', 'true');
        return pageReference.getUrl();
    }
}

 

I have a trigger that works when adding and deleting records, it is not firing when updating a record.

 

Below is the trigger.  Thanks for your help!

 

trigger ContactsOnAccount on Contact (after insert, after delete,after undelete,after update) {

    Set<Id> aId = new Set<Id>();
    
    if(Trigger.isInsert || Trigger.isUndelete){
        for(Contact opp : Trigger.New){
            aId.add(opp.AccountId);
        }
        List<Account> acc = [select id,Total_Number_of_Contacts__c from Account where Id in:aId];
        List<Contact> con = [select id from contact where AccountId in :aId];
        
        for(Account a : acc){
            a.Total_Number_of_Contacts__c=con.size();
            
        }update acc;
    }
    
    if(Trigger.isDelete){
        for(Contact opp : Trigger.old){
            aId.add(opp.AccountId);
        }
        List<Account> acc = [select id,Total_Number_of_Contacts__c from Account where Id in:aId];
        List<Contact> con = [select id from contact where AccountId in :aId];
        
        for(Account a : acc){
            a.Total_Number_of_Contacts__c=con.size();
            
        }update acc;
    }
   
    if(Trigger.isUpdate){
       Set<Id> OldAId = new Set<Id>(); 
        for(Contact opp : Trigger.new){
        if(opp.AccountId != Trigger.oldMap.get(opp.id).AccountId || opp.Primary_Contact__c != Trigger.oldMap.get(opp.id).Primary_Contact__c)
            aId.add(opp.AccountId);
            OldAId.add(Trigger.oldMap.get(opp.id).AccountId);
        
        }
        if(!aId.isEmpty()){
        //for new Accounts
        List<Account> acc = [select id,Total_Number_of_Contacts__c from Account where Id in:aId];
        //For New Account Contacts
        List<Contact> con = [select id from contact where AccountId in :aId];
        
        /*
        This is For Old Contacts Count
                              */
        
        //for Old Accounts
        List<Account> Oldacc = [select id,Total_Number_of_Contacts__c from Account where Id in:OldAId];
        
        //For Old Account Contacts
        List<Contact> OldCon = [select id from contact where AccountId in :OldAId];
       
        //For New Accounts
        for(Account a : acc){
            a.Total_Number_of_Contacts__c=con.size();
            
            
        }update acc;
        
        //For Old Accounts
        for(Account a : Oldacc){
            a.Total_Number_of_Contacts__c=OldCon.size();
            
        }update Oldacc;
        }
    }
}

 

 

  • September 04, 2013
  • Like
  • 0

Is there a way to create a function that can take in a varying number of parameters? 

 

I know in java to do such a thing you can have a function like this: 

 

public double average(double...values) { 

 ....function body....

}

 

Is there a simliar method to do this in APEX? 

 

Thanks in advance! 

  • September 04, 2013
  • Like
  • 0

I need the workflow to send an email, record a task event, and perform a field update on a Case.

 

The formula is:

 

OR( today() - DATEVALUE(Contact.Last_Survey_Sent_Date__c) >= 90,isBlank(Contact.Last_Survey_Sent_Date__c)&& IsClosed)

 

Please help...I have been at this for weeks! Finally got it where I want it and I exceeded my limits.

 

Thanks again!

 

Shannon

Need help with ERROR – Trigger Code and Test Code Below -Creating a "Project" Milestone1_Project__c record when an Opp custom field - Start_Project_Site_Id_Stage__c = Yes - This field is dependent upon Stage = "Closed Won" on the opportunity.

 

System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, CreateM1Project: execution of AfterInsert

caused by: System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, ProjectMilestone: execution of AfterInsert

caused by: System.DmlException: Update failed. First exception on row 0; first error: MISSING_ARGUMENT, Id not specified in an update call: []

Trigger.ProjectMilestone: line 16, column 1: []

Trigger.CreateM1Project: line 16, column 1: [] Stack Trace Class.CreateM1Project_test.myTestMethod: line 14, column 1

 

 

TRIGGER CODE

 

trigger CreateM1Project on Opportunity (after insert, after update) {

   

   

   List<Milestone1_Project__c> NewProjects = new List<Milestone1_Project__c>();

 

    for (Opportunity opp: trigger.new)  {

       

        if (opp.Start_Project_Site_Id_Stage__c == 'Yes') {

       

            Milestone1_Project__c freshProject = new Milestone1_Project__c();

            freshProject.Name = opp.Name;

            freshProject.Opportunity__c = opp.Id;

            NewProjects.add(freshProject);

        }

    }

    insert NewProjects;

       

   }

 

 

TEST CODE

 

@IsTest(SeeAllData=false)

public class CreateM1Project_test{

 

    static testMethod void myTestMethod() {

 

        Opportunity opp =

            new Opportunity(Name='Test',

            StageName='Closed Won',

            CloseDate=system.today(),

            Tower_Height__c='100',

            Start_Project_Site_Id_Stage__c='Yes');

           

        Test.startTest();

            insert opp;

        Test.stopTest();

       

    }

}

Hi, I got this error message while trying to change Cases Status even though tha case doesn't have a Setup.  --> : CaseResponseTimeTrigger: execution of BeforeUpdate caused by: System.QueryException: List has more than 1 row for assignment to SObject: Class.ServiceAvailability.GetHoursToUse: line 128, column 1


When I check that line 128 :  

 

 public Id GetHoursToUse(Case updatedCase, Setup__c relatedSetup) {
    
      // Get the default business hours
        BusinessHours defaultHours = [select Id from BusinessHours where IsDefault=true];
        
        Account costCenter = [select Id, Name, Account_Top_Parent__c from Account where Id =: relatedSetup.Cost_Center__c];
        System.Debug('CC Id: ' + costCenter.Id);
        System.Debug('CC Name: ' + costCenter.Name);
        
        Account mainAccount = [select Id, Name, V_Account_Number__c from Account where Id =: costCenter.Account_Top_Parent__c];
        System.Debug('MA Id: ' + mainAccount.Id);
        System.Debug('MA Name: ' + mainAccount.Name);
        
        Contract contract = [select Id, AccountNumber__c, Business_Hours__c, Status from Contract where AccountNumber__c =:    mainAccount.Videra_Account_Number__c];
        System.Debug('Contract Id: ' + contract.Id);
        System.Debug('Contract Business Hrs: ' + contract.Business_Hours__c);
        System.Debug('Contract Acc Number: ' + contract.AccountNumber__c);
        
         Id hoursToUse = contract.Business_Hours__c != null ? contract.Business_Hours__c : defaultHours.Id;
        return hoursToUse;
    }  

 

I can't understand why this error occurs?

  • September 03, 2013
  • Like
  • 0

Hi,

 

Can anyone help me to write the apex trigger for snding email notifcation to the customer when the new case is created using email template and email notification for assigning the case to the case team and case owner(queues)?

 

 

Please help me.

 

 

Thanks.,

Ambiga

Hello,

 

I have a trigger that is supposed to update the Contact of a case that is closed:

 

 trigger setLastSurveySentDate on Case (after insert) {
    Map<Id,Id> contactToCaseMap = new Map<Id,Id>();
    for(Case A : trigger.new)
        contactToCaseMap.put(A.ContactId,A.Id);
 
    List<Contact> contactsToUpdate = new List<Contact>{};
      
    for (Contact con: [SELECT Id,Last_Survey_Sent_Date__c FROM Contact WHERE Id IN:  contactToCaseMap.keySet()]) {
        Id caId = contactToCaseMap.get(con.Id);
        Case ca = trigger.newMap.get(caId);
        if (ca.Status=='Closed' && con.Last_Survey_Sent_Date__c < date.today()-90 ){
            con.Last_Survey_Sent_Date__c=date.today();
            contactsToUpdate.add(con);
        }
        
        else if (ca.Status=='Closed' && con.Last_Survey_Sent_Date__c == null ){
            con.Last_Survey_Sent_Date__c=date.today();
            contactsToUpdate.add(con);
        }
    }

    if(contactsToUpdate != null && !contactsToUpdate.isEmpty())
        Database.update(contactsToUpdate);
}

 

I have a workflow that sends a survey, updates the case Last Survey Sent Date case field, and records a task that the survey was sent, as long as the Contact has not received a survey within the last 90 days:

 

OR( today() - DATEVALUE(Contact.Last_Survey_Sent_Date__c) >= 90,isBlank(Contact.Last_Survey_Sent_Date__c))

 

The trigger is updating the contact field, however, it is not using the date that has been updated on the case.

 

The date of  survey sent CASE = 09/03/2013 12:15 AM

The date of survey sent CONTACT = 09/02/2013 8:00 PM

 

The date of survey sent on the contact is always the same time and the date changes depending on the real time of day (e.g. tests performed prior to 12 AM showed a date of 09/02/2013 8:00 PM)

 

Can you please help?

 

Thank you very much!

 

Shannon

 

Two objects are there object1 & object2 

 

if object1 is update then automatically object2 is updating, vice versa object2 is update automatically update object1

 

these two objects are in loop conditions.

 

My question is how u will stop the updating. 

Explain me how many ways we can stop the updating..

 

Please reply this question...

HIIII

 

Any one worked on castiron integration please help me how to deal it.

 

Thanks in advance