• Sam27
  • NEWBIE
  • 180 Points
  • Member since 2011

  • Chatter
    Feed
  • 6
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 3
    Questions
  • 57
    Replies

I am performing a calculation and want to output the result of that calculation on a VisualForce page.

 

I have created a Controller Extension and have created a method that returns a Decimal. I'd like to display that result in my Visual Force page.

 

If I have a method called getCalculation that returns the decimal in my controller. Will that allow me to bind the variable with VisualForce or do I need to construct things differently in my controller?

I use a controller to display a list of products with a checkbox against each product value . When the end user selects few products and clicks "add quantity" button it should navigate to another VF page in which i should display the selected products and an input filed for quantity. Quite similiar to the way of adding products in opportunity. In the code below im using a single controller for 2 VF pages. Problem i m facing here is when the second page is called the wrapperList becomes null instead of holding the values of the selected products. Please give me some suggestions.

 

public with sharing class productAdd
{        
    public  List<Product2> Stdproduct{get;set;}
    public List<wrapper> wrapperList {get;set;}  
    public list<wrapper> SelectedprodList{get;set;}	
    public class wrapper
    {
        public product2 cont{get;set;}
        public Boolean selected{get;set;}
        public integer quantity{get;set;}
        public wrapper(product2 c)
        {
            cont = c;
            selected = false;
        } 
    }
	public  List<wrapper> getProdList()
    {        
        if((wrapperList == null) || (wrapperList.size() == 0))
        {                      
            wrapperList = new List<wrapper>();
            Stdproduct = [Select id, Name from product2 limit 2];           
            for(Product2 c :(List<Product2>)Stdproduct)            
            {               
                wrapperList.add(new wrapper(c));
            }
        }             
        return wrapperList;
    }
    
    public PageReference AddQuantity()
    {   
        PageReference pageRef= new PageReference('/apex/AddQuantity');
        pageRef.setredirect(true);        
        return pageRef;           
    }

    public list<wrapper> getSelectedproducts()
    {
        selectedprodList = new list<wrapper>();      
        for(wrapper cCon:getProdList())
        {            
            if(cCon.selected==true)  
            {                        
                selectedprodList.add(cCon);
            }                           
        }        
        return selectedprodList;           
    }        
}

<!-- 1st Page -->
<apex:page Controller="productAdd" sidebar="false">
    <table  width="90%">
	    <apex:form>
			<apex:repeat value="{!ProdList}" var="l" >               
				<tr>
				<td>
				<apex:inputCheckbox value="{!l.selected}"/>
				</td>
				<td class="fieldname">{!l.cont.name}</td>                       
				</tr>                
			</apex:repeat>
				<tr>
				<apex:commandButton value="Add Quantity" action="{!AddQuantity}"/>
				</tr>             
	    </apex:form> 
    </table>
</apex:page>


<!-- 2nd Page -->
<apex:page Controller="productAdd">
	<apex:form >
		<apex:pageBlock > 
			<apex:pageBlockTable value="{!Selectedproducts}" var="c" id="table"> 
				<apex:column value="{!c.cont.Name}" />                
				<apex:column >
				<apex:inputText value="{!c.quantity}"/>
				</apex:column> 
			</apex:pageBlockTable> 
		</apex:pageBlock> 
	</apex:form> 
</apex:page>

 

I need to add a inner join to my querry to fetch the master records based on the child records.

 

My Code:

order = [select name,id,Order_Printed__c, Order_Status__c, (select name, ActiveFlag__c,Item_Supplier__c,
                            from Order_Lines__r where (ActiveFlag__c = True AND item_Supplier__c = 'business') )
                            from Order__c where Order_Status__c = 'Ready for dispatch' AND Order_Printed__c = False];

This code fetches the order even if no matching Order_line is found. but i want only orders with matching orderlines.

 

Thanks in advance

Hi,

 

 

I need to find maximum date and minimum date from a list of dates.Can anyone give me solution??

 

Regards,

banu

  • September 02, 2011
  • Like
  • 0

Hello,

           I have one method which is exporting record over 2000 and when i am clicking on export all button i am facing error.i.e. too many script statement :200001.

         Now i can't optimize the lines so that i want to catch this exception and i want to show message so i thought to put try catch on that method but still i am getting that exception.

 

Here is the code of that method :-

public PageReference exportAll(){

Pagereference pg;
try{
pg = new Pagereference('/apex/TransactionExcelGenerator?accId='+ controllerAccount.Id + '&exportall=yes' + '&listview='+ selectedList + '&sortfield=' + sortFieldName + '&sortfield1=' + sortFieldName1 + '&ordertype=' + orderType );
system.debug('----page---'+pg);
return pg;
}
catch(Exception ex){
Apexpages.addMessage(new Apexpages.Message(Apexpages.Severity.INFO, 'Exporting this view is not possible due to large amount of data being accessed. Please either change view filter, select fewer rows to export or use reporting functionality to extract the data required:'+ex.getMessage()));
return null;
}


}

 

  • September 02, 2011
  • Like
  • 0

Hi

 

I'm trying to implement Jeff Douglas's dynamic search page on a custom object, its all set up and the page loads with the correct initial data, however when typing in the parameters the debug SOQL text doesn't update and the data in the table doesn't update, so i'm assuming the event isn't being triggered. How can i check if this is the case? and if so how can i resolve?

 

Thanks for any suggestions.

 

Paul

  • September 01, 2011
  • Like
  • 0

I am running a rather large soql query consisting open activity, activity history opportunity and contact as the root item with similar large where condition.....

 

Now what the problem is that the execution time of query is very inconsistent......

 

sometime the query (always for fewer data) runs in the time of one second but sometime (specially with large set of data) the query take inappropriately long time to execute (50 -200 seconds)

 

What i don't understand is the ratio between the amount of data is not proportional to the ratio between the amount of time its taking....i. e. ideally it should take little more time to execute (if any) but its something like hanging....

 

Anyone can suggest the ways to solve it , or suggestion to improve the query structure to get rid of this inconsistency....

 

or have any of you faced similar situation in dealing with soql query......??

 

Any suggestion and comment is welcome

 

Thank you

  • July 26, 2011
  • Like
  • 0

Hi,

 

I created some report through apex & visualforce and provided the inline editing for different fields through <apex:inlineEditSupport> tag on double click

 

<apex:inlineEditSupport id="apEdit" event="ondblClick" disabled="false" />

 

According to our requirement we suppressed some of ondblclick attribute from some field.

 

Yesterday I found that all the inline edit  function which were earlier attached on double click started firing on single click. And this is breaking much of the functionality.

 

Anyone have any idea as why its happening or got the similar problem ??

 

It is astonishing to see such a major change without any prior notice even when the event for inlineEditSupport tag is 'ondblclick'.

 

kindly put any information you have regarding this.

 

Thanks

 

Sam

  • July 08, 2011
  • Like
  • 0

Preface :

I really liked this <apex:inlineEditSupport> tag providing the functionality of inline edit for custom controllers.

 

I need to apply <apex:inlineEditSupport> for a table which shows matching objects. I am using Wrapper Class for getting the list of such matching objects.

 

And then showing it in the table through visualforce, Also I am rerendering the table with an ajax call.

 

Problem:

When the page loads and I double click on any item and it changes for editing according to the field type, I rerender the table and again doubleclick on any field and it again changes for editing as desired.

 

Now suppose the page is loaded and I rerender the table (without doubleclicking on any picklist field). When the table is rendered All other field works fine but picklist does not open for editing on double clicking.

 

So in short inlinEditSupport works for rerendered picklist only when any picklist field was doubleclicked when the page was loaded for the first time, Otherwise it don't.

 

Example Code :

 

Apex Class

Public class inlineEditTestController{
Public string AccSoql{get;set;}
Public integer AccCount{get;set;}
Public List<cContact> AccountVal {get;set;}
public class cContact {
  
          public Contact con {get; set;}
          public Opportunity opp {get; set;}
   
          public cContact(Contact c, Opportunity o) {
              con = c;
              opp = o;
          }
          
      }
Public pagereference inlineEditTestController(){
AccountVal = new List<cContact>();
AccSoql = 'select id, name, StageName, (select opportunitycontactrole.contact.id, opportunitycontactrole.contact.firstname, opportunitycontactrole.contact.lastname, opportunitycontactrole.contact.account.name, opportunitycontactrole.contact.Birthday__c from Opportunity.opportunitycontactroles) from opportunity order by LastModifiedDate desc';
AccCount = 10;
runQuery();
return null;
}

Public void runQuery(){
AccountVal.clear();
sObject[] newrows = Database.query(AccSoql+' LIMIT '+AccCount);
        Contact c = new Contact();
        Opportunity o = new Opportunity();
              for (SObject row : newrows){
         SObject[] childocr = row.getSObjects('OpportunityContactRoles');
      c = null;
     o = (opportunity)row;
     if(childocr != null){
     for (SObject con : childocr){
   OpportunityContactRole tempOcr = (OpportunityContactRole)con;
     c = (contact)tempOcr.contact;
     AccountVal.add(new cContact(c,o));
     }}
          }
system.debug(AccountVal.size()+'----'+AccountVal);
integer j = AccountVal.size();
if(j > 10)
{
   for(integer i=0; i<(j - 10); i++)
   {system.debug(i);
   try{
    AccountVal.remove(0);}
    catch (Exception e){}
    }
}
system.debug(AccountVal.size()+'----'+AccountVal);
}
Public pagereference moreRec(){
AccCount += 10;
runQuery();
return null;
}
Public pagereference lessRec(){
if(AccCount >= 10)
AccCount -= 10;
runQuery();
return null;
}
}

 

 

Visualforce Page

 

<apex:page controller="inlineEditTestController" action="{!inlineEditTestController}">
<apex:form >
<apex:pageBlock id="tableContainer">
<apex:pageBlockTable value="{!AccountVal}" var="Acc">
<apex:column ><apex:outputField value="{!Acc.con.LastName}"/></apex:column>
<apex:column ><apex:outputField value="{!Acc.opp.Name}"/></apex:column>
<apex:column ><apex:outputField value="{!Acc.opp.StageName}"/></apex:column>     // or any other picklist field from contact or opportunity
</apex:pageBlockTable>
</apex:pageBlock>
<apex:inlineEditSupport disabled="false" event="ondblclick"/>
<apex:commandLink action="{!moreRec}" reRender="tableContainer">More</apex:commandLink>&nbsp;&nbsp;<apex:commandLink action="{!lessRec}" reRender="tableContainer">Less</apex:commandLink>
</apex:form>
</apex:page>

 

 

Note : I am not using dependent picklist anywhere , the code provided was checked for error, without wrapperclass(i.e. for single objects) I didn't get any error and this is my first post so excuse me if I was not clear enough. Do ask me if you need some clarification.

 

Question: Is it a possible bug??

 

Anticipating quick response, Thank you.

 

Sam

  • April 21, 2011
  • Like
  • 0

Hi,

I have written a Trigger and Testclass. Im getting 59% coverage plz refer the code

* Urgent

 

Trigger -

trigger ePeople_ApartmentBlock on Opportunity (after update) {
    Map<Id,Id> opptyAppMap1 = new Map<Id,Id>();
    Map<Id,Id> opptyAppMap2 = new Map<Id,Id>();
    Map<Id,Id> opptyAppMap3 = new Map<Id,Id>();
    Map<Id,Id> opptyAppMap4 = new Map<Id,Id>();
    List<Apartment__c> testApp1 = new List<Apartment__c>();
    List<Apartment__c> testApp2 = new List<Apartment__c>();
    List<Apartment__c> testApp3 = new List<Apartment__c>();
    List<Apartment__c> testApp4 = new List<Apartment__c>();
    List<Apartment__c> testApp5 = new List<Apartment__c>();
    Set<Id> oldAppSetId = new Set<Id>();
    Set<Id> delOppAppId = new Set<Id>();
    for(Opportunity opp:Trigger.new){
        if(opp.Apartment__c != null && (opp.StageName == 'Site Visit' || opp.StageName == 'Closed Lost')){
            opptyAppMap1.put(opp.Apartment__c, opp.Id);
        }
        else if(opp.Apartment__c != null && opp.StageName == 'Booking'){
            opptyAppMap2.put(opp.Apartment__c, opp.Id);
        }
        else if(opp.Apartment__c != null && (opp.StageName == 'Blocking' || opp.StageName == 'Negotiation/Review')){
            opptyAppMap3.put(opp.Apartment__c, opp.Id);
        }
        else if(opp.Apartment__c != null && opp.StageName == 'Agreement Done'){
            opptyAppMap4.put(opp.Apartment__c, opp.Id);  
        }
        else if(System.Trigger.oldMap.get(opp.Id).Apartment__c != null && opp.Apartment__c != System.Trigger.oldMap.get(opp.Id).Apartment__c)
        {
            Opportunity oldOpp =  Trigger.oldMap.get(opp.Id);
            oldAppSetId.add(oldOpp.Apartment__c);
        }
           
    for(Apartment__c c:[select Id, Status__c from Apartment__c where Id IN:opptyAppMap1.keySet()]){
        if(c.Status__c != 'Available'){
            c.Status__c = 'Available';
        }   
        testApp1.add(c);
    }
    update testApp1;
    for(Apartment__c c:[select Id, Status__c from Apartment__c where Id IN:opptyAppMap2.keySet()]){
        if(c.Status__c != 'Booked'){
            c.Status__c = 'Booked';
        }   
        testApp2.add(c);
    }
    update testApp2;
    for(Apartment__c c:[select Id, Status__c from Apartment__c where Id IN:opptyAppMap3.keySet()]){
        if(c.Status__c != 'Blocked'){
            c.Status__c = 'Blocked';
        }    
        testApp3.add(c);
    }
    update testApp3;
    for(Apartment__c c:[select Id, Status__c from Apartment__c where Id IN:opptyAppMap4.keySet()]){
        if(c.Status__c != 'Sold'){
            c.Status__c = 'Sold';
        }    
        testApp4.add(c);
    }
     update testApp4;
     
    for(Apartment__c c : [select Id, Status__c from Apartment__c where Id IN:oldAppSetId]){
        if(c.Status__c != 'Available'){
            c.Status__c = 'Available';
        }    
        testApp5.add(c);
    }
     update testApp5;
    
    }
    for(Opportunity opp:Trigger.old){
     if(Trigger.isDelete){ 
       Opportunity oldOpp = Trigger.oldMap.get(opp.Id);
       system.debug('OpportunityMap'+oldOpp);
       delOppAppId.add(oldOpp.Apartment__c);
     } 
    }
}

 Testclass -

@isTest
private class ePeople_AptOpportunityTest{
    static testMethod void AptTest()
    {
      Account a = new Account(name='Ramesh');
      insert a;
      Project__c pr = new Project__c(Name='VV');
      insert pr;
      Block__c b = new Block__c(Name='Block 1',Project__c=pr.id);
      insert b;
      Apartment__c c = new Apartment__c(Name='A1',Block__c=b.id, Status__c = 'Blocked');
      insert c;
      Apartment__c c1 = new Apartment__c(Name='A1',Block__c=b.id, Status__c = 'Booked');
      insert c1;
      Opportunity o=new Opportunity(Name='ram test',AccountId=a.Id, CloseDate=Date.today(),StageName='Blocking', Apartment__c = c.id);
      insert o; 
      a.Name='Ramesh';
      update a;
      o.StageName ='Booking' ;
      o.StageName = 'Blocking';
      c.Status__c = 'Available';
      update c;
      update o;
    }
}q

 

  • February 29, 2012
  • Like
  • 0

Hello,

 

I am trying to count the number of child records based on a custom object of "Status_c".  My Parent is "Case" and the child records are "AIO".  On the AIO record there is the Status and a few other fields.  What I am trying to do is count the children based on the status. Once I have that count I am writing it back to another custom object in the parent "Count_of_M".   I've been looking through other posts and have been unsuccessful in adapting the examples posted to do what I need. Thank you in advance for any suggestions!!

 

Shawn.

 

 

trigger CountRelatedCallLogs_fromLog on AIO__c (after insert, after update) {


    AIO__c [] scl = Trigger.new;
    String sid = null;
//    progress = "In Progress";
    sid = scl[0].Related_Case__c;
        
         Integer i = [select count() from AIO__c where Status_c = :sid];    

        // update the master record
    Case_ID__c [] s =[select id, Count_of_Pending__c from Case_ID__c where id = :sid];
 
    s[0].Call_Count__c = i; 
        // write to database
        update s[0];

}

 

I am getting a system.assertEquals error on the following test class. Error: System.AssertException: Assertion Failed: Expected: null, Actual: 00580000001k6g1AAAClass.testReferralAssignOwner.test: line 11, column 1 Test Class: @isTest private class testReferralAssignOwner { static testMethod void test() { List testUsers = [select id from user where isactive = true limit 2]; Account a = new Account(Name='test'); insert a; List refs = new List(); refs.add(new Referral__c(Client_Name__c=a.id,Phone__c='12345',Assigned__c=testUsers[0].Id)); refs.add(new Referral__c(Client_name__c=a.id,Phone__c='12345',Assigned__c=testUsers[1].Id)); insert refs; system.assertEquals(refs[0].OwnerId,testUsers[0].Id); // OwnerId should equal Assigned__c; system.assertEquals(refs[1].OwnerId,testUsers[1].Id); // OwnerId should equal Assigned__c; refs[0].OwnerId = testUsers[1].Id; refs[1].Assigned__c = testUsers[0].Id; update refs; system.assertEquals(refs[0].Assigned__c,testUsers[1].Id); // Assigned__c should equal OwnerId now system.assertEquals(refs[1].OwnerId,testUsers[0].Id); // OwnerId should equal Assigned__c now } } It says that it is expecitng null and getting a user ID instead. It should be expecting the user ID, so I am not sure what the problem is. Any help is greatly appreciated!

I keep getting the following error message when I try to insert a new record

 

System.NullPointerException: Attempt to de-reference a null object 

 

Class.StageStations.save: line 27, column 1

 

Here is the visualforce code

 

<apex:page controller="StageStations">
 <script>
  function confirmCancel() {
      var isCancel = confirm("Are you sure you wish to cancel?");
      if (isCancel) return true;
  
     return false;
  }  
  </script>
  <apex:sectionHeader title="Add Station for {!account.name}"/>
    <apex:form >
      <apex:pageBlock title="Customer Information" mode="edit">    
        <apex:pageBlockButtons >
          <apex:commandButton action="{!save}" value="Save"/>
          <apex:commandButton action="{!cancel}" value="Cancel" onclick="return confirmCancel()" immediate="true"/>
        </apex:pageBlockButtons>
      <apex:pageBlockSection title="Asset Information for {!asset.id}">

        <!-- Within a pageBlockSection, inputFields always display with their
             corresponding output label. --> 
    
        <apex:inputField id="assetid" value="{!asset.Station_ID__c}"/>
        <apex:inputField id="assetsn" value="{!asset.SerialNumber}"/>
      </apex:pageBlockSection>
    </apex:pageBlock>
  </apex:form>
</apex:page>

 Here is the Apex Class

public class StageStations {


    Account account;
    Asset asset;
    
    public Account getAccount() {
        return [select id, name,Contracted_Stations__c from Account 
                 where id = :ApexPages.currentPage().getParameters().get('id')]; 
    } 
    
    public Asset getAsset() {
      if(asset == null) asset = new asset();
      return asset;
   }


    public PageReference cancel() {
        pageReference accountpage = new ApexPages.StandardController(account).view();
        accountpage.setRedirect(true);
        return accountpage; 
    }


    public PageReference save() {
    
      asset.AccountID = account.id;
      asset.Name = 'PES Station';
      insert asset;
        
        
      PageReference acctPage = new ApexPages.StandardController(account).view();
      acctPage.setRedirect(true);

      return acctPage;
    }
}

 I am pretty much a neophyte to Apex coding and I based this code on tutorials I found on the force.com site. Any insight would be appreciated.


I have hte following code, which works, when a product is added to a opportunityl ine item, it copies the data + some other data as free text to a hiddel field. I want to deploy this from my sandbox to our production instance, but can not since it does not have a test method and I am lost on building one for this, any help is apprciated.

 

trigger OpportunityProuctCopytoHiddenField on Opportunity (before insert, before update) {
for(Opportunity t:trigger.new)
      {
        List<String> NewList= new List<String>();

        if (t.HasOpportunityLineItem == true) 
        {
             for(OpportunityLineItem OpLine: [SELECT CreatedBy.Name, Quantity, TotalPrice, LastModifiedDate, PriceBookEntry.Name, UnitPrice, ID FROM OpportunityLineItem WHERE OpportunityId =:t.Id] ) 
            {
                NewList.add(OpLine.PriceBookEntry.Name);
                NewList.add(' serving ');
                String str = '' + opLine.Quantity;
                NewList.add(str);
                NewList.add(' units passed has been authorized by ');
                NewList.add(OpLine.CreatedBy.Name);
                NewList.add('and the transation has been logged into the record id: ');
                NewList.add(OpLine.ID);
                NewList.add(' on');
                String str1 = '' + opLine.lastModifiedDate;
                NewList.add(str1);
                NewList.add(' GMT 0');
                            }
            for(String c : NewList){
                //t.Hidden_Products__c = t.Hidden_Products__c + c + '<br>';
                t.Hidden_Products__c = t.Hidden_Products__c + c ;
                system.debug('********' +  t.Hidden_Products__c);
            }
        }
    }
}

Below is the code for my Visual Force page and APEX controller. I run a TRY block and intentionaly throw an exception.

 

I used similar code in another VisualForce/APEX Controller page combination and it works for me however on this page when I click the button and the exception is thrown the error message is not displaying.

 

VisualForce Page

<apex:page controller="PlacementPreferenceFormController" sidebar="false" showHeader="false" cache="false">
    <apex:pageMessages id="errorMessage"/>
    <apex:outputPanel >
            <apex:form >
            <apex:pageBlock title="Placement Preference Form">
            
                <apex:pageBlockSection columns="2">
                      <apex:InputField value="{!RecruitmentCycle.Allocated_Points__c}"/>
                      <apex:InputField value="{!RecruitmentCycle.Remaining_Points__c}"/>
                </apex:pageBlockSection>
            </apex:pageBlock>
            
            <apex:pageBlock title="Add Placement Preference" mode="edit" id="PPAdd">
                <apex:pageBlockSection columns="2">
                    <apex:outputLabel value="Partner Organization " for="pl"><apex:selectList id="pl" value="{!ppn.Partner_Research__c}" size="1" title="Partner Organization">
                        <apex:selectOptions value="{!PRs}"></apex:selectOptions>
                    </apex:selectList></apex:outputLabel>
                                    
                    <apex:InputField value="{!ppn.Points__c}"/>
                    <apex:commandButton value="Add Placement" action="{!newPlacementPreference}" rerender="all">
                    </apex:commandButton>
                </apex:pageBlockSection>    
            </apex:pageBlock>
            
            <apex:pageBlock title="Placement Preferences" mode="edit" id="PPList">
                <apex:pageBlockTable value="{!PlacementPreferenceList}" var="pp">
                    <apex:column value="{!pp.Partner_Research_Organization__c}"/>
                    <apex:column value="{!pp.Organization_Type__c}"/>
                    <apex:column value="{!pp.City__c}"/>
                    <apex:column value="{!pp.State__c}"/>
                    <apex:column value="{!pp.Points__c}"/>
                    <apex:column headerValue="Action">    
                        <apex:commandButton value="Del" action="{!deletePlacementPreference}" rerender="all">
                            <apex:param name="ppParam" value="{!pp.Id}" assignTo="{!ppid}"/>
                        </apex:commandButton>
                    </apex:column>                            
                </apex:pageBlockTable>
            </apex:pageBlock>
        </apex:form>
    </apex:outputPanel>
</apex:page>

 

APEX Controller

public class PlacementPreferenceFormController {

	// Declare Recruitment Cycle and Placement Preference List
	public Recruitment_Cycle__c rc;
	public LIST<Placement_Preference__c> ppl;
	public Placement_Preference__c ppn {get; set;}
	public String pl {get; set;}
	public decimal ppnPoints {get;set;}
	public string ppnPR {get;set;}	
	public string ppid {get;set;}
	
	public PlacementPreferenceFormController(){
		// Select Recruitment Cycle Record pulling ID parameter
		rc = [select id, allocated_points__c, remaining_points__c from Recruitment_Cycle__c
		where id =:ApexPages.currentPage().getParameters().get('id')]; 
		  
		// Select Placement Preference List from parent record
		ppl = [select id, Partner_Research_Organization__c, City__c, Organization_Type__c, Partner_Research__c, Points__c, Recruitment_Cycle__c, State__c
		from Placement_Preference__c Where Recruitment_Cycle__c = :ApexPages.currentPage().getParameters().get('id')];
		
		ppn = new Placement_Preference__c();		
	}
	
	// Picklist Select Option Values for Partner Research
	public List<selectOption> getPRs() {
			List<selectOption> options = new List<selectOption>(); //new list for holding all of the picklist options
			options.add(new selectOption('', '- None -')); //add the first option of '- None -' in case the user doesn't want to select a value or in case no values are returned from query below
			for (Partner_Research__c PRoption : [select id, Organization_Name__r.name from Partner_Research__c 
		Where (TBR_Partner_Year__c = '2012' AND Research_Stage__c = 'Recruiting' AND Status__c = 'Invite to submit proposal')
		  OR (TBR_Partner_Year__c = '2012' AND Research_Stage__c = 'Position Proposal') 
		  OR (TBR_Partner_Year__c = '2012' AND Research_Stage__c = 'Placement') 
		ORDER BY Organization_Name__r.name]) { //query for User records with System Admin profile
				options.add(new selectOption(PRoption.Id, PRoption.Organization_Name__r.name)); //for all records found - add them to the picklist options
			}
			return options; //return the picklist options
		}	
	
	public void refreshPlacementPreferences()
	{
		ppl = [select id, City__c, Organization_Type__c, Partner_Research__c, Points__c, Recruitment_Cycle__c, State__c
		from Placement_Preference__c Where Recruitment_Cycle__c = :ApexPages.currentPage().getParameters().get('id')];				
	}
	
    public PageReference deletePlacementPreference() {
        Placement_Preference__c pptd = [Select id from Placement_Preference__c where Id = :ppid];
		delete pptd;
		string url = 'http://broadcenter.force.com/page/PlacementPreferences?id=' + rc.Id;
		PageReference p = new PageReference(url);
    	p.setRedirect(true); 
        return p;
    }	
    
    public PageReference newPlacementPreference() {
	try{
			
			throw new cException('Residency Requirement is a required field.');
	    	Placement_Preference__c ppta = new Placement_Preference__c(Recruitment_Cycle__c = rc.id);			
			if (ppn.Points__c > 0)
			{
				ppta.Points__c = ppn.Points__c;
				ppta.Partner_Research__c = ppn.Partner_Research__c;
				insert ppta;
			}
			
			
			string url = 'http://broadcenter.force.com/page/PlacementPreferences?id=' + rc.Id;
			PageReference p = new PageReference(url);
	    	p.setRedirect(true); 
	        return p;
    }
    catch(Exception e){ApexPages.addMessages(e);return null;}          
    } 	    
	
	public Recruitment_Cycle__c getRecruitmentCycle(){
		return rc;
	}
	
	public LIST<Placement_Preference__c> getPlacementPreferenceList(){
		return ppl;
	}
	
}

 

Hi All,

 

Could anyone please suggest me the steps to reduce script statements in the application to avoid the exception "Too many script statements: 200001".

Thanks.

Hi all,

 

I have this SOQL with a child relationship (parent-to-child)

 

[SELECT Name, Birthdate, (SELECT Name_Em__c, Job_Title__c FROM Employment__r),
 (SELECT Degree__c, Name_Ed__c FROM Education__r)
FROM Contact WHERE Id IN (SELECT Candidate_Contact__c
      FROM Application__c

      WHERE Job__c =:JobOrderId)

];

 

And the following Visualforce on a pageblocktable:

 

<apex:column headerValue="Company" value="{!ed.Employment__r.Name_Em__c}"/>

 

But I cannot get the information from the two sub-select into the table. 

 

Do you have any idea on how to get it?

 

Many thanks,

 

MGA.

I'm trying to gather some information from the user with regards to a lead, and then send them back to a page with a list of leads. The page I'm referencing in my method is not linking properly to the submit button and I'm at a loss as to why.  Here is the APEX and VF code.  The submit button on the VF page at /reject?id=rep.email&flip={!flip.id} should update three fields on the Lead Record and return the users to the /registrations?id={!rep.email} page.  Instead it's not updating the lead and is resetting the page URL to be /reject?id={rep.email}.

 

I have almost identical code working in another part of this class and am completely stumped why this would be happening.  Any clues? 

 

  public Contact rep = new Contact();
  public String rejectReason{get;set;}
  public String rejectDetail{get;set;}
  public Lead flip {get;set;}

 Public leadView(){
      Rep = [SELECT id, FirstName, LastName, Email, Accountid, Account.Type, Shark_Tank_Access__c FROM Contact 
              WHERE email =:ApexPages.currentPage().getParameters().get('id') limit 1];
  }
  
  public Contact getRep(){
  	return rep;
  }

public Lead getFlip(){
        flip = [SELECT id, Company, FirstName, LastName, Title, Registered_Rep__c, Registered_Rep__r.Email, Lead_Reject_Reason__c, Reject_Reason_Details__c, Rejected_by__c 
                FROM Lead WHERE id =: ApexPages.currentPage().getParameters().get('flip')];
    return flip;
   }
	

   public pageReference rejectLead(){
   		 flip.Rejected_by__c = ptnrRep.id;
   		 flip.Lead_Reject_Reason__c = rejectReason;
   		 flip.Reject_Reason_Details__c = rejectDetail;
   		 update flip;
 
   		 pageReference goBack = new      pageReference('/apex/registrations?id='+rep.email);
		 goBack.setRedirect(true);
 
   		 return goBack;
   }

 Visual Force Code:  

<apex:form >
<apex:outputField value="{!flip.Company}"/><p/>
<apex:outputField value="{!flip.State}"/><p/>
<apex:selectList id="State" value="{!rejectReason}" multiselect="false" size="1"  required="True">
<apex:selectOption itemvalue="" itemLabel="--Please Select--"/>
<apex:selectOption itemvalue="" itemLabel="Deal In progress"/>
<apex:selectOption itemvalue="" itemLabel="End user not willing to engage"/>
<apex:selectOption itemvalue="" itemLabel="Information Request Only"/>
<apex:selectOption itemvalue="" itemLabel="Invalid contact information"/>
<apex:selectOption itemvalue="" itemLabel="Lost to competition"/>
<apex:selectOption itemvalue="" itemLabel="Not an end user"/>
<apex:selectOption itemvalue="" itemLabel="Project Delayed/Cancelled"/>
<apex:selectOption itemvalue="" itemLabel="Unreachable"/>
</apex:selectList> 
<p/>
<apex:inputText value="{!rejectDetail}"/>
<p/>
<apex:commandButton value="Submit" action="{!rejectLead}"/>
</apex:form>

 

In my apex i have serveral catches, which I can't seem to be able to get an test method to cover it durning my test

And the Exception it would throw and catch is an "QueryException" Error.

trigger Signer on Form__c (before insert, before update) {
	
	Form__c F = trigger.new[0];
            ...
	try{     
	    ...

	}catch (Exception e) {
		Trigger.new[0].Signer__c.addError('Error : Check Setting');
	}


    

 

 

Hi,

 

i have a class which reads through all appointments from my custom object appointment__c and creates an event in SF. Things work fine on the sandbox and when i move it to production i get the below error.

 

Failure Message: "System.DmlException: Insert failed. First exception on row 40; first error: FIELD_INTEGRITY_EXCEPTION, Event duration cannot be negative: [DurationInMinutes]", Failure Stack Trace: "Class.SyncWithEvents.transfer: line 31, column 7 Class.TestSyncWithEvents.TestappSyncWithEvents: line 25, column 6 External entry ...

 

Public Class SyncWithEvents
{
    List<Appointment__c> app= new List<appointment__c>();
    public Integer no_of_appts {get;set;}
    List <Event> LstEvent= new List<Event>();
    
    public SyncWithEvents()
    {
    
           
    }
    public void transfer()
    {
     app=[select StartDateTime__c,EndDateTime__c,Status__c,Client__c,OwnerId   from Appointment__c 
                    where Sync_with_events__c=false];
                    System.debug('No of records+++++++++++++++++++++'+app.size());
          for (integer i=0;i<app.size();i++)
       // for(List<Appointment__c> app:[select StartDateTime__c,EndDateTime__c,Status__c,Client__c,OwnerId  from Appointment__c 
       //             where Sync_with_events__c=false])
        {
                        Event e = new Event();
                        e.StartDateTime = app[i].StartDateTime__c;
                        e.EndDateTime = app[i].EndDateTime__c;
                        e.Subject = 'Appt - '+app[i].Status__c;
                                       
                        e.WhoId=app[i].Client__c; 
                        e.OwnerId=app[i].OwnerId ;
                        app[i].Sync_with_events__c=true;
                        LstEvent.add(e);
      }
      insert LstEvent;
      update app;
      no_of_appts=LstEvent.size();
    }
    
}

 Here is the test class

 

public with sharing class TestSyncWithEvents {
	
	static testMethod void TestappSyncWithEvents() 
    {  
    	/*appointment__c a = new appointment__c();
        string year = '2011';
        string month = '12';
        string day = '27';
        string hour = '09';
        string minute = '30';
        string second = '00';
        string stringDate = year + '-' + month + '-' + day + ' ' + hour + ':' + minute +  ':' + second;

        Datetime myDate =    datetime.valueOf(stringDate);
        a.Name='Test Name';
        a.Appointment_Type__c='Call';
        a.Start_Date__c=date.parse('12/27/2011');
        a.Start_Time__c='09:30 AM';
        a.StartDateTime__c=myDate;
        a.EndDateTime__c=myDate.addMinutes(30);
        a.status__c='Tentative';
        a.Sync_with_events__c=false;
        insert a;*/
    	SyncWithEvents sw= new SyncWithEvents();
    	sw.transfer();
    }

}

 Any ideas on what could be causing the problem

  • October 13, 2011
  • Like
  • 0

I am performing a calculation and want to output the result of that calculation on a VisualForce page.

 

I have created a Controller Extension and have created a method that returns a Decimal. I'd like to display that result in my Visual Force page.

 

If I have a method called getCalculation that returns the decimal in my controller. Will that allow me to bind the variable with VisualForce or do I need to construct things differently in my controller?

Hi,

 

I have created a template under "Personal Email Template" for sending email.

 

 

Im using the below code to send an email but showing an error

"SendEmail failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING, Missing target address (target, to, cc, bcc): []  "

 

Controller :



private final Contact con;   

public testemail(ApexPages.StandardController controller){

        this.con=(Contact)controller.getRecord();    }       

public void SendEmail(){           

 Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();                      

 

//Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();       

//mail.setTargetObjectId(con.Id);       

//mail.setTemplateId('00X90000000QHUD');           

mail.setWhatId(con.Id);              

mail.setBccSender(false);           

mail.setUseSignature(false);           

mail.setReplyTo('abc@gmail.com');           

mail.setSenderDisplayName('user123');           

mail.setSaveAsActivity(false); 

 

can any one please help me on how to fetch the email template id to set in "mail.setTemplateId( );". 

 

Thanks

 

 

 


 

 

 

Hi All,

 

There is an output link on one page.

When I click on that, it should change style of component to display:none on same page.

For that i have created a javascript function and it is working fine but after chaging the style it simply refresh the page

as I didnt specify value to navigate page.

 

Below is my logic:

 

<apex:page>
<script>
function fnCheck(input)
{
    alert("script");
    document.getElementById(input).style.display = "none";
}
</script>
<apex:form>
<apex:outputLink onclick="fnCheck('{!$Component.testId}');">Test</apex:outputLink>
<apex:inputText id="testId"/>
</apex:form>
</apex:page>

 

Is there is any way to specify empty value in outputLink or any way to do this?

 

Thanks.

 

hi can any one help  me how to replace text to number with formula field text

  • October 11, 2011
  • Like
  • 0

I am quite stuck after trying every trick I can find in the book, having done plenty of research into the classic "Too many SOQL queries" error.

 

I have, for example, made sure that there is no SELECT statement or UPDATE within a FOR loop (which seem to be the most common mistakes).

 

And yet still the error occurs!

 

Here is the error:

System.LimitException: Too many SOQL queries: 101

Class.RecordUpdate.updateInvoices: line 54, column 9 Trigger.DepartmentTrigger1: line 66, column 5

 Here is the Trigger that is causing the problem:

trigger DepartmentTrigger1 on Account (after update) {

  Set<Id> accountIds = new Set<Id>();


for (Integer i = 0; i < Trigger.new.size(); i++){
    if (
    //Changing btw two Parent Companies
        (Trigger.new[i].Parent_Company__c != Trigger.old[i].Parent_Company__c && 
        Trigger.new[i].Department__c == TRUE && Trigger.old[i].Department__c == TRUE)||
    //Changing to a Department
        (Trigger.new[i].Department__c == true && Trigger.old[i].Department__c == false)||
    // Changing from a Department
        (Trigger.new[i].Department__c == FALSE && Trigger.old[i].Department__c == TRUE)
        ) {
        accountIds.add(Trigger.new[i].Id);
    }
}
  
    //Update Contacts
    RecordUpdate.updateContacts(accountIds);
    
    //Update Deals
    RecordUpdate.updateDeals(accountIds);    

    //Update Sales Invoices
    RecordUpdate.updateInvoices(accountIds);
    
}

 And here is the Class that is referenced above:

public with sharing class RecordUpdate {

public static void updateContacts(Set<Id> contactset){
    Contact[] relatedContacts =
        [SELECT f.id, f.Accountid, f.Account.Department__c, f.Account.Parent_Company__c, f.Parent_Company__c
        FROM Contact f
        WHERE f.Accountid IN :contactset];

    for ( Contact childc : relatedContacts ) {
        if (childc.Account.Department__c == TRUE) {
            childc.Parent_Company__c = childc.Account.Parent_Company__c;
        }
        else
            childc.Parent_Company__c = childc.AccountId;
    }
    update relatedContacts;
}


public static void updateDeals(Set<Id> dealset){
    List<Opportunity> relatedDeals =
        [SELECT g.id, g.Accountid, g.Account.RecordTypeId, g.Account.Department__c, g.Account.Parent_Company__c, 
        g.Parent_Company__c, g.Agency_Client__r.id , g.Agency_Client__r.Department__c, g.Agency_Client__r.Parent_Company__c
        FROM Opportunity g
        WHERE g.Accountid IN :dealset OR g.Agency_Client__r.id IN :dealset];
    
    for ( Opportunity childo : relatedDeals ) {
        if (childo.Account.Department__c == TRUE) {
            childo.Parent_Company__c = childo.Account.Parent_Company__c;
        }
        else if (childo.Account.RecordTypeId == '01220000000Dqq6'){
            if (childo.Agency_Client__r.Department__c == TRUE){
                childo.Parent_Company__c = childo.Agency_Client__r.Parent_Company__c;
            }
            else
                childo.Parent_Company__c = childo.Agency_Client__c;
        }
        else
            childo.Parent_Company__c = childo.AccountId;
    }
    update relatedDeals;
}


public static void updateInvoices(Set<Id> invoiceset){
    Sales_Invoices__c[] relatedInvoices =
        [SELECT s.Id, s.Company__c, s.Company__r.Parent_Company__c, s.Company__r.Department__c, s.Parent_Company__c, s.Agency_Client__r.Id
        FROM Sales_Invoices__c s
        WHERE s.Company__c IN :invoiceset OR s.Agency_Client__c IN :invoiceset
        FOR UPDATE];
    
    for ( Sales_Invoices__c childs : relatedInvoices ) {
        if (childs.Company__r.Department__c == TRUE) {
            childs.Parent_Company__c = childs.Company__r.Parent_Company__c;
        }
        else
            childs.Parent_Company__c = childs.Company__c;
    }
    update relatedInvoices;
}

}

 

 There are a few other triggers that are involved, but they are tiny in comparison to the above example.

 

Thanks for any help you can offer.

I have been beating my head against the wall trying to get a dynamic reRender to work on my visualforce page. Essentially my VFPage embeds via iFrames a separate VFpage that displays a table. I want the user to be able to select from a picklist the number of tables he/she wishes to be displayed (1-5). Upon changing the # of tables the VFpage should be refreshed to display the corresponding number of iFrames. This is all working properly so far.

 

Here is my issue-the VFpage embedded via iFrames contains dynamic content as well and I would like this information to be preserved should another table be added to the page; thus, I want the onchange event on my table # picklist to cause a dynamic reRender that will only do a partial page refresh of the iFrames formerly not displayed while leaving the visible iFrames untouched. Hopefully this makes sense but I will post my VFPage and Controller extension as well for you to look at; thanks so much!

 

VFPage:

 

<apex:page standardController="Quantitativo__c" extensions="MultQuantAnal">
<div align="center">
<h1 style="font-size:16pt"><apex:outputText value="Quantitative Analysis"></apex:outputText></h1>
</div>
<apex:form >
<div align="center">
<br/>
<apex:outputText >Tabels:&nbsp;</apex:outputText>
<apex:selectList id="chooseTables" value="{!numTables}" size="1">
          <apex:selectOption itemValue="1" itemLabel="1"/>
          <apex:selectOption itemValue="2" itemLabel="2"/>
          <apex:selectOption itemValue="3" itemLabel="3"/>
          <apex:selectOption itemValue="4" itemLabel="4"/>
          <apex:selectOption itemValue="5" itemLabel="5"/>
<apex:actionSupport event="onchange" reRender="{!PanelRef}"/>
</apex:selectList>
</div>
<br/>
<apex:outputPanel id="one">
<apex:iframe height="250" rendered="{!numTables>=1}" frameborder="false" src="/apex/QuantAnal"/>
</apex:outputPanel>
<apex:outputPanel id="two">
<apex:iframe height="250" rendered="{!numTables>=2}" frameborder="false" src="/apex/QuantAnal"/>
</apex:outputPanel>
<apex:outputPanel id="three">
<apex:iframe height="250" rendered="{!numTables>=3}" frameborder="false" src="/apex/QuantAnal"/>
</apex:outputPanel>
<apex:outputPanel id="four">
<apex:iframe height="250" rendered="{!numTables>=4}" frameborder="false" src="/apex/QuantAnal"/>
</apex:outputPanel>
<apex:outputPanel id="five">
<apex:iframe height="250" rendered="{!numTables==5}" frameborder="false" src="/apex/QuantAnal"/>
</apex:outputPanel>
</apex:form>
</apex:page>

 

Controller Extension:

 

public class MultQuantAnal {

    public Integer numTables{get;set;}
    
    public void setnumTables(String numVar) {
        this.numTables = Integer.valueOf(numVar);
    }

    public MultQuantAnal(ApexPages.StandardController controller) {
        this.numTables=1;
    }

    public String getPanelRef(){
        if (numTables==1){
            return 'one,two,three,four,five';
        }
        else if (numTables==2){
            return 'two,three,four,five';
        }
        else if (numTables==3){
            return 'three,four,five';
        }
        else if (numTables==4){
            return 'four,five';
        }
        else {
            return 'five';
        }
    }
}

 

I have 2 objects Scholarship and Award.

 

The 2 objects are the exactly the same except that Scholarship has has a Master-Detail relationship and Award has 3 extra fields. I want to display them in a list of Awards & Scholarships only showing the common fields they share. I also want them to be clickable to view the Award or Scholarship.

Preface :

I really liked this <apex:inlineEditSupport> tag providing the functionality of inline edit for custom controllers.

 

I need to apply <apex:inlineEditSupport> for a table which shows matching objects. I am using Wrapper Class for getting the list of such matching objects.

 

And then showing it in the table through visualforce, Also I am rerendering the table with an ajax call.

 

Problem:

When the page loads and I double click on any item and it changes for editing according to the field type, I rerender the table and again doubleclick on any field and it again changes for editing as desired.

 

Now suppose the page is loaded and I rerender the table (without doubleclicking on any picklist field). When the table is rendered All other field works fine but picklist does not open for editing on double clicking.

 

So in short inlinEditSupport works for rerendered picklist only when any picklist field was doubleclicked when the page was loaded for the first time, Otherwise it don't.

 

Example Code :

 

Apex Class

Public class inlineEditTestController{
Public string AccSoql{get;set;}
Public integer AccCount{get;set;}
Public List<cContact> AccountVal {get;set;}
public class cContact {
  
          public Contact con {get; set;}
          public Opportunity opp {get; set;}
   
          public cContact(Contact c, Opportunity o) {
              con = c;
              opp = o;
          }
          
      }
Public pagereference inlineEditTestController(){
AccountVal = new List<cContact>();
AccSoql = 'select id, name, StageName, (select opportunitycontactrole.contact.id, opportunitycontactrole.contact.firstname, opportunitycontactrole.contact.lastname, opportunitycontactrole.contact.account.name, opportunitycontactrole.contact.Birthday__c from Opportunity.opportunitycontactroles) from opportunity order by LastModifiedDate desc';
AccCount = 10;
runQuery();
return null;
}

Public void runQuery(){
AccountVal.clear();
sObject[] newrows = Database.query(AccSoql+' LIMIT '+AccCount);
        Contact c = new Contact();
        Opportunity o = new Opportunity();
              for (SObject row : newrows){
         SObject[] childocr = row.getSObjects('OpportunityContactRoles');
      c = null;
     o = (opportunity)row;
     if(childocr != null){
     for (SObject con : childocr){
   OpportunityContactRole tempOcr = (OpportunityContactRole)con;
     c = (contact)tempOcr.contact;
     AccountVal.add(new cContact(c,o));
     }}
          }
system.debug(AccountVal.size()+'----'+AccountVal);
integer j = AccountVal.size();
if(j > 10)
{
   for(integer i=0; i<(j - 10); i++)
   {system.debug(i);
   try{
    AccountVal.remove(0);}
    catch (Exception e){}
    }
}
system.debug(AccountVal.size()+'----'+AccountVal);
}
Public pagereference moreRec(){
AccCount += 10;
runQuery();
return null;
}
Public pagereference lessRec(){
if(AccCount >= 10)
AccCount -= 10;
runQuery();
return null;
}
}

 

 

Visualforce Page

 

<apex:page controller="inlineEditTestController" action="{!inlineEditTestController}">
<apex:form >
<apex:pageBlock id="tableContainer">
<apex:pageBlockTable value="{!AccountVal}" var="Acc">
<apex:column ><apex:outputField value="{!Acc.con.LastName}"/></apex:column>
<apex:column ><apex:outputField value="{!Acc.opp.Name}"/></apex:column>
<apex:column ><apex:outputField value="{!Acc.opp.StageName}"/></apex:column>     // or any other picklist field from contact or opportunity
</apex:pageBlockTable>
</apex:pageBlock>
<apex:inlineEditSupport disabled="false" event="ondblclick"/>
<apex:commandLink action="{!moreRec}" reRender="tableContainer">More</apex:commandLink>&nbsp;&nbsp;<apex:commandLink action="{!lessRec}" reRender="tableContainer">Less</apex:commandLink>
</apex:form>
</apex:page>

 

 

Note : I am not using dependent picklist anywhere , the code provided was checked for error, without wrapperclass(i.e. for single objects) I didn't get any error and this is my first post so excuse me if I was not clear enough. Do ask me if you need some clarification.

 

Question: Is it a possible bug??

 

Anticipating quick response, Thank you.

 

Sam

  • April 21, 2011
  • Like
  • 0