• Ronaldo Costa
  • NEWBIE
  • 55 Points
  • Member since 2012


  • Chatter
    Feed
  • 1
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 15
    Questions
  • 22
    Replies
Hello all,
I'm working on a roll-up summary trigger to rollup values separated by commas. and I'm getting the following error:

Apex script unhandled exception by user/organization: 005300000073SRQ/00D5400000097yi
Source organization: 00D30000001HvZp (null)
Failed to invoke future method 'public static void ProcessConcessionsAsync(Set<Id>)' on class 'ConcessionsRollUpTriggerHandler' for job id '7075400000IMKrB'

caused by: System.SObjectException: SObject row was retrieved via SOQL without querying the requested field: Concessions__c.Name

Class.ConcessionsRollUpTriggerHandler.ProcessConcessionsAsync: line 20, column 1


Class:
//class//class
  public with sharing class ConcessionsRollUpTriggerHandler {

    @future 
    public static void ProcessConcessionsAsync(Set<ID> agreementIds){

      // holds o mapa de agreements id separando as concessoes por ,
      Map<Id, String> agreementConcessionMap = new Map<Id, String>();

      // get ALL of the concessions for all affected agreement to build
      List<Concessions__c> agreementConcessions = [select id, Agreement__c from Concessions__c 
        where Agreement__c IN :agreementIds order by Concessions__c.name]; //stopped here

      for (Concessions__c ar : agreementConcessions) {
        //if (!agreementConcessionMap.containsKey(ar.Agreement__c)) {
          // if the key (agreement) doesn't exist, add it with concession name
          //agreementConcessionMap.put(ar.Agreement__c,ar.Name);
        //} else {
          // if the key (agreement) already exist, add ", concession-name"
          agreementConcessionMap.put(ar.Agreement__c,agreementConcessionMap.get(ar.Agreement__c) + ', ' + ar.Name);
        //}
      }

      // get the agreements that were affected
      List<Apttus__APTS_Agreement__c> agreements = [select id from Apttus__APTS_Agreement__c where Id IN :agreementIds];

      // add the comma separated list of concessions
      for (Apttus__APTS_Agreement__c a : agreements)
        a.Concessions_Holder_Test__c  = agreementConcessionMap.get(a.id);

      // update the agreements
      update agreements;

    }  

  }
Trigger
trigger ConcessionsRollUpTrigger on Concessions__c (after delete, after insert, after update) {

  // shot dps do insert e update
  if((Trigger.isInsert || Trigger.isUpdate) && Trigger.isAfter){

    // search os ids de tds agreements afetados
    Set<Id> agreementIds = new Set<Id>();
    for (Concessions__c ar : [select Id, Agreement__c from Concessions__c 
      where Id IN :Trigger.newMap.keySet()])
      agreementIds.add(ar.Agreement__c);

    // processa os agreements
    ConcessionsRollUpTriggerHandler.ProcessConcessionsAsync(agreementIds);

  // shot qdo os registros são deletados
  } else if(Trigger.isDelete && Trigger.isAfter){

    // search os ids de tds agreements afetados
    Set<Id> agreementIds = new Set<Id>();
    for (ID id : Trigger.oldMap.keySet())
      agreementIds.add(Trigger.oldMap.get(id).Agreement__c);
//
    // process the agreements
    ConcessionsRollUpTriggerHandler.ProcessConcessionsAsync(agreementIds);

  }

}

Any ideas?

Thanks,
Ron

 
Hello all, I have the following code to roll-up summary products name to an opportunity text-long field, I need a summary of purchased products separated by commas.
Everything runs good with no errors, however I get no results, nothing happens, can you please take a look and help me?

Trigger:
trigger OppProductsTrigger on OpportunityLineItem (after delete, after insert, after update) {

    // fires after both insert and update
    if((Trigger.isInsert || Trigger.isUpdate) && Trigger.isAfter){

      // find the ids of all opps that were affected
      Set<Id> oppIds = new Set<Id>();
      for (OpportunityLineItem ar : [select Id, name, OpportunityId from OpportunityLineItem 
        where Id IN :Trigger.newMap.keySet()])
        oppIds.add(ar.OpportunityId);

      // process the opps  
      OppProductsTriggerHandler.ProcessProductsAsync(oppIds);


    // fires when records are deleted. may want to do undelete also?
    } else if(Trigger.isDelete && Trigger.isAfter){

      // find the ids of all opps that were affected
      Set<Id> oppIds = new Set<Id>();
      for (ID id : Trigger.oldMap.keySet())
        oppIds.add(Trigger.oldMap.get(id).OpportunityId);

      // process the opps
      OppProductsTriggerHandler.ProcessProductsAsync(oppIds);

    }

  }

Class: 
public with sharing class OppProductsTriggerHandler {

  @future 
  public static void ProcessProductsAsync(Set<ID> oppIds){

    // holds a map of the opp id and comma separated products to build
    Map<Id, String> oppProductMap = new Map<Id, String>();

    // get ALL of the products for all affected opps so we can build
    List<OpportunityLineItem> oppProducts = [select id, name, OpportunityId 
      from OpportunityLineItem 
      where OpportunityId IN :oppIds order by Name];

    for (OpportunityLineItem ar : oppProducts) {
      if (!oppProductMap.containsKey(ar.OpportunityId)) {
        // if the key (opp) doesn't exist, add it with product name
        oppProductMap.put(ar.OpportunityId,ar.Name);
      } else {
        // if the key (opp) already exist, add ", product-name"
        oppProductMap.put(ar.OpportunityId,oppProductMap.get(ar.OpportunityId) + 
          ', ' + ar.Name);
      }
    }

    // get the opps that were affected
    List<Opportunity> opps = [select id from Opportunity where Id IN :oppIds];

    // add the comma separated list of regions
    for (Opportunity a : opps)
      a.Products_Purchased__c = oppProductMap.get(a.id);

    // update the opps
    update opps;

  }  

}

Thank you!
Ron
Hello all, I have the following code to roll-up summary products name to an opportunity text-long field, I need a summary of purchased products separated by commas.
Everything runs good with no errors, however I get no results, nothing happens, can you please take a look and help me?

Trigger:
 
trigger OppProductsTrigger on OpportunityLineItem (after delete, after insert, after update) {

  // fires after both insert and update
  if((Trigger.isInsert || Trigger.isUpdate) && Trigger.isAfter){

    // find the ids of all opps that were affected
    Set<Id> oppIds = new Set<Id>();
    for (OpportunityLineItem ar : [select Id, name, OpportunityId from OpportunityLineItem 
      where Id IN :Trigger.newMap.keySet()])
      oppIds.add(ar.OpportunityId);

    // process the opps  
    OppProductsTriggerHandler.ProcessProductsAsync(oppIds);


  // fires when records are deleted. may want to do undelete also?
  } else if(Trigger.isDelete && Trigger.isAfter){

    // find the ids of all opps that were affected
    Set<Id> oppIds = new Set<Id>();
    for (ID id : Trigger.oldMap.keySet())
      oppIds.add(Trigger.oldMap.get(id).OpportunityId);

    // process the opps
    OppProductsTriggerHandler.ProcessProductsAsync(oppIds);

  }

}

Class:
 
public with sharing class OppProductsTriggerHandler {

  @future 
  public static void ProcessProductsAsync(Set<ID> oppIds){

    // holds a map of the opp id and comma separated products to build
    Map<Id, String> oppProductMap = new Map<Id, String>();

    // get ALL of the products for all affected opps so we can build
    List<OpportunityLineItem> oppProducts = [select id, name, OpportunityId 
      from OpportunityLineItem 
      where OpportunityId IN :oppIds order by Name];

    for (OpportunityLineItem ar : oppProducts) {
      if (!oppProductMap.containsKey(ar.OpportunityId)) {
        // if the key (opp) doesn't exist, add it with product name
        oppProductMap.put(ar.OpportunityId,ar.Name);
      } else {
        // if the key (opp) already exist, add ", product-name"
        oppProductMap.put(ar.OpportunityId,oppProductMap.get(ar.OpportunityId) + 
          ', ' + ar.Name);
      }
    }

    // get the opps that were affected
    List<Opportunity> opps = [select id from Opportunity where Id IN :oppIds];

    // add the comma separated list of regions
    for (Opportunity a : opps)
      a.Products_Purchased__c = oppProductMap.get(a.id);

    // update the opps
    update opps;

  }  

}


Thank you, thank you!
Ron
 
I created the following apex class to count opportunities, show min and max values - having them displayed in a visualforce component/page.
I'm having several issues to start the test class, can anybody please show me how to do it? Maybe I created the class in a wrong way, obviously it works on Sandbox and I cannot deploy to production.
 
public with sharing class CountBubbles {
    
    private ApexPages.StandardController stdCtrl;
    public List<Opportunity> allAccounts{get;set;}
    public Integer srNo            {get;set;}
    public Id recId              {get;set;}  
    public boolean isSaved          {get;set;} 
    Opportunity acc;    
    public Opportunity minSource {get; private set;}
    public Opportunity maxSource {get; private set;}
    public Opportunity minQualify {get; private set;}
    public Opportunity maxQualify {get; private set;}

    
	public Integer getTOTAL_Opps_Source() {
        Integer counter = [ Select count() from Opportunity WHERE StageName = 'Source' AND CloseDate <= Next_N_DAYS:365 
        and CloseDate >= Last_N_DAYS:365];
        return counter;
    }
    //Get total opps qualify phase
    public Integer getTOTAL_Opps_Qualify() {
        Integer counter = [ Select count() from Opportunity WHERE StageName = 'Qualify' AND CloseDate <= Next_N_DAYS:365 
        and CloseDate >= Last_N_DAYS:365];
        return counter;
    }
   
public CountBubbles(ApexPages.StandardController std)
   {
   	
  
  ID qid = std.getRecord().Id;

     try { minSource = [SELECT Id,Name,StageName,Opportunity_Probability__c FROM Opportunity 
              Where StageName = 'Source' AND CloseDate <= Next_N_DAYS:365 
          and CloseDate >= Last_N_DAYS:365 ORDER BY Opportunity_Probability__c ASC limit 1];
     } catch (exception e) {
          
     }
     try { maxSource = [SELECT Id,Name,StageName,Opportunity_Probability__c FROM Opportunity 
              Where StageName = 'Source' AND CloseDate <= Next_N_DAYS:365 
          and CloseDate >= Last_N_DAYS:365 ORDER BY Opportunity_Probability__c DESC limit 1];  
     } catch (exception e) {
      
     }
     try { minQualify = [SELECT Id,Name,StageName,Opportunity_Probability__c FROM Opportunity 
              Where StageName = 'Qualify' AND CloseDate <= Next_N_DAYS:365 
          and CloseDate >= Last_N_DAYS:365 ORDER BY Opportunity_Probability__c ASC limit 1];
     } catch (exception e) {
      
     }
     try { maxQualify = [SELECT Id,Name,StageName,Opportunity_Probability__c FROM Opportunity 
              Where StageName = 'Qualify' AND CloseDate <= Next_N_DAYS:365 
          and CloseDate >= Last_N_DAYS:365 ORDER BY Opportunity_Probability__c DESC limit 1];  
     } catch (exception e) {
      
     } 
  
  }   
}


Thank you!
Ronaldo.
Hi,

I need to pass the primary contact role's email into the opportunity record.
Can you please advise if this will require a trigger/apex code or if it can be accomplish only with workflow rules?


Thanks,
Ronaldo.
Hello,

Please review the code below, I don't get why its not passing 100%

Trigger:
 
trigger CreateFlightItinerary on Opportunity (after update) {    
List<Itinerary__c> fi = new List<Itinerary__c>();
    for (Opportunity a: Trigger.New)
         if (a.fi_automation_check__c == TRUE){
                 <b>fi.add (new Itinerary__c(</b>
                     Flight_Booking__c = a.Id,
					 Stop_1__c = a.Stop1_ID__c,
					 Flight_Crew_1__c = a.CrewM_1_ID__c
				));
         }
   insert fi;
}

Test class:
 
@isTest
private class testCreateFlightItinerary{
    static TestMethod void myTestClass()
    {
    	Account a = new Account();
	    a.Name = 'TestName';
	    a.Phone = '5512991224391';
        insert a;
    	
    	Opportunity o = new Opportunity();
 		o.Name = 'TestName';
		o.AccountID = a.Id;
		o.closedate = system.today();
		o.stagename = 'Sample Quote';
		o.Aircraft_Type__c = 'King Air';
		o.fi_automation_check__c=false;
		insert o; 
		
		o.fi_automation_check__c=true;
		update o;
    }
}

Thanks!
Hello all,

Please review the code below, I don't get why its not passing 100%

Trigger:
trigger CreateFlightItinerary on Opportunity (after update) {    
List<Itinerary__c> fi = new List<Itinerary__c>();
    for (Opportunity a: Trigger.New)
         if (a.fi_automation_check__c == TRUE){
                 fi.add (new Itinerary__c(
                     Flight_Booking__c = a.Id,
					 Stop_1__c = a.Stop1_ID__c,
					 Flight_Crew_1__c = a.CrewM_1_ID__c
				));
         }
   insert fi;
}

Test:
 
@isTest
private class testCreateFlightItinerary{
    static TestMethod void myTestClass()
    {
    	Account a = new Account();
	    a.Name = 'TestName';
	    a.Phone = '5512991224391';
        insert a;

    	Opportunity o = new Opportunity();
	    o.Name = 'TestName';
            o.AccountID = a.Id;
            o.closedate = system.today();
            o.stagename = 'Sample Quote';
            o.Aircraft_Type__c = 'King Air';
            o.fi_automation_check__c=True;
        insert o;             
    }
}

I get not coverage on the highlight line "fi.add (new Itinerary__c("


Thankss!!

Ronaldo.
Hello all,

Please review the code below, I don't get why its not passing 100%

Trigger:
 
trigger CreateFlightItinerary on Opportunity (after update) {    
List<Itinerary__c> fi = new List<Itinerary__c>();
    for (Opportunity a: Trigger.New)
         if (a.fi_automation_check__c == TRUE){
                 fi.add (new Itinerary__c(
                     Flight_Booking__c = a.Id,
					 Stop_1__c = a.Stop1_ID__c,
					 Flight_Crew_1__c = a.CrewM_1_ID__c
				));
         }
   insert fi;
}

@test Class
 
@isTest
private class testCreateFlightItinerary{
    static TestMethod void myTestClass()
    {
    	
    	Account a = new Account();
	    a.Name = 'TestName';
	    a.Phone = '5512991224391';
        insert a;

    	Opportunity o = new Opportunity();
	    o.Name = 'TestName';
            o.AccountID = a.Id;
            o.closedate = system.today();
            o.stagename = 'Sample Quote';
            o.Aircraft_Type__c = 'King Air';
        insert o;

        Itinerary__c i = new Itinerary__c();
	    i.Flight_Booking__c = o.Id;
		
        insert i;
        
    }
}

I highlighted the line "fi.add (new Itinerary__c(" which is not passing.

Thanks a lot!

Ronaldo.
Hello,

Please let me know your approach for the case below as I did not find a similar requirement over the forum.

1- User creates a Flight Booking record (parent object)
2- The user creates a Stop record (up to 14) (child object)
3- The user creates a Flight Crew record (up to 5) (child object)
4- Once the user is done creating Stop records and Flight Crew records, the user will then check the Initiate Itinerary Automation checkbox to trigger the following actions:

The system will create a Flight Itinerary record (child object) and will populate several lookup fields (for all related Stops and Flight Crew)

What should be the easiest solution? Because I think I would need to query the Flight Booking to find out all IDs for the Stops and Flight Crew in order to populate the related lookup fields for each one of them.


Thanks,

Ronaldo.
Hello all,

I need to add a picklist field to the CommunitiesSelfReg VF page, but am getting the error below because I need to change it from inputext to inputfield, otherwise it won't show the drop-down menu.

"Could not resolve the entity from <apex:inputField> value binding '{!purchasedfrom}'.  <apex:inputField> can only be used with SObjects, or objects that are Visualforce field component resolvable."

VF Page:

 
<apex:page id="communitiesSelfRegPage" showHeader="true" controller="CommunitiesSelfRegController" title="{!$Label.site.user_registration}">
     <apex:define name="body">  
      <center>
<apex:form id="theForm" forceSSL="true">
                    <apex:pageMessages id="error"/>
                    
                    
                    <apex:panelGrid columns="2" style="margin-top:1em;">
                      <apex:outputLabel style="font-weight:bold;color:red;" value="First Name" for="firstName"/>
                      <apex:inputText required="true" id="firstName" value="{!firstName}" label="First Name"/>
                      <apex:outputLabel style="font-weight:bold;color:red;" value="Last Name" for="lastName"/>
                      <apex:inputText required="true" id="lastName" value="{!lastName}" label="Last Name"/>
                      <apex:outputLabel style="font-weight:bold;color:red;" value="{!$Label.site.email}" for="email"/>
                      <apex:inputText required="true" id="email" value="{!email}" label="{!$Label.site.email}"/>
                      
                      <apex:outputLabel style="font-weight:bold;color:red;" value="Phone" for="phone"/>
                      <apex:inputText required="true" id="phone" value="{!phone}" label="Phone"/>
                      <apex:outputLabel value="Title" for="title"/>
                      <apex:inputText required="true" id="title" value="{!title}" label="Title"/>                      
                      <apex:outputLabel style="font-weight:bold;color:red;" value="Company" for="companyname"/>
                      <apex:inputText required="true" id="companyname" value="{!companyname}" label="Company"/>                      

                      <apex:outputLabel style="font-weight:bold;color:red;" value="Street" for="street"/>
                      <apex:inputText required="true" id="street" value="{!street}" label="Street"/>
                      <apex:outputLabel style="font-weight:bold;color:red;"  value="City" for="city"/>
                      <apex:inputText required="true" id="city" value="{!city}" label="City"/>
                      <apex:outputLabel style="font-weight:bold;color:red;"  value="Zip" for="postalcode"/>
                      <apex:inputText required="true" id="postalcode" value="{!postalcode}" label="Zip"/>
                      <apex:outputLabel style="font-weight:bold;color:red;"  value="Country" for="country"/>
                      <apex:inputText required="true" id="country" value="{!country}" label="Country"/>
                      <apex:outputLabel style="font-weight:bold;color:red;"  value="State" for="state"/>
                      <apex:inputText required="true" id="state" value="{!state}" label="State"/>
                      
                      <apex:outputLabel value="Product Owner" for="productowner"/>
                      <apex:inputText required="true" id="productowner" value="{!productowner}" label="Product Owner"/>
<!--                       <apex:outputLabel value="Purchased From" for="purchasedfrom"/> -->
<!--                       <apex:inputText required="true" id="purchasedfrom" value="{!purchasedfrom}" label="Purchased From"/> -->
                      <apex:outputLabel value="Serial Number" for="serialnumber"/>
                      <apex:inputText required="true" id="serialnumber" value="{!serialnumber}" label="Serial Number"/>
                      
                      <apex:inputfield value="{!u.Purchased_From__c}"/>  
                      
					  <apex:outputLabel value="{!$Label.site.community_nickname}" for="communityNickname"/>
                      <apex:inputText required="true" id="communityNickname" value="{!communityNickname}" label="{!$Label.site.community_nickname}"/>                      
                      <apex:outputLabel value="{!$Label.site.password}" for="password"/>
                      <apex:inputSecret id="password" value="{!password}"/>
                      <apex:outputLabel value="{!$Label.site.confirm_password}" for="confirmPassword"/>
                      <apex:inputSecret id="confirmPassword" value="{!confirmPassword}"/>
                      <apex:outputText value=""/>
                      <apex:commandButton action="{!registerUser}" value="{!$Label.site.submit}" id="submit"/>
                    </apex:panelGrid> 
                  <br/>
</apex:form>
     </center>
      <br/>
    </apex:define>

</apex:page>

Class:
 
/**
 * An apex page controller that supports self registration of users in communities that allow self registration
 */
public with sharing class CommunitiesSelfRegController {

  public String firstName {get; set;}
  public String lastName {get; set;}
  public String email {get; set;}
  public String phone {get; set;}
  public String title {get; set;}
  public String companyname {get; set;}
  public String street {get; set;}
  public String city {get; set;}
  public String postalcode {get; set;}
  public String country {get; set;}
  public String state {get; set;}
  public String productowner {get; set;}
  public String purchasedfrom {get; set;}
  public String serialnumber {get; set;}
  public String password {get; set {password = value == null ? value : value.trim(); } }
  public String confirmPassword {get; set { confirmPassword = value == null ? value : value.trim(); } }
  public String communityNickname {get; set { communityNickname = value == null ? value : value.trim(); } }
  
  public CommunitiesSelfRegController() {}
  
  private boolean isValidPassword() {
    return password == confirmPassword;
  }

  public PageReference registerUser() {
  
    // it's okay if password is null - we'll send the user a random password in that case
    if (!isValidPassword()) {
      System.debug(System.LoggingLevel.DEBUG, '## DEBUG: Password is invalid - returning null');
      ApexPages.Message msg = new ApexPages.Message(ApexPages.Severity.ERROR, Label.site.passwords_dont_match);
      ApexPages.addMessage(msg);
      return null;
    }  

    
    String profileId = '00ej0000000jJMR'; // To be filled in by customer.
    
    String accountId = '001g000000QMTDX'; // To be filled in by customer.  

    // Set this to your main Communities Profile API Name
    String profileApiName = 'PowerCustomerSuccess';
    //String profileId = [SELECT Id FROM Profile WHERE UserType = :profileApiName LIMIT 1].Id;
    //List<Account> accounts = [SELECT Id FROM Account LIMIT 1];
    //System.assert(!accounts.isEmpty(), 'There must be at least one account in this environment!');
    //String accountId = accounts[0].Id;
    
    String userName = email;

    User u = new User();
    u.Username = userName;
    u.Email = email;
    u.Phone = phone;
    u.Title = title;
    u.Street = street;
    u.City = city;
    u.PostalCode = postalcode;
    u.Country = country;
    u.State = state;
    u.Product_Owner__c = productowner;
    u.Purchased_From__c = purchasedfrom;
    u.Serial_Number__c = serialnumber;
    u.CompanyName = companyname;
    u.FirstName = firstName;
    u.LastName = lastName;
    u.CommunityNickname = communityNickname;
    u.ProfileId = profileId;
    
    String userId = Site.createPortalUser(u, accountId, password);
   
    if (userId != null) { 
      if (password != null && password.length() > 1) {
        System.debug(System.LoggingLevel.DEBUG, '## DEBUG: User creation successful and password ok - returning site.login');
        return Site.login(userName, password, null);
      }
      else {
        System.debug(System.LoggingLevel.DEBUG, '## DEBUG: User creation successful but password not ok - redirecting to self reg confirmation');
        PageReference page = System.Page.CommunitiesSelfRegConfirm;
        page.setRedirect(true);
        return page;
      }
    }
    System.debug(System.LoggingLevel.DEBUG, '## DEBUG: User creation not successful - returning null');
    return null;
  }
}


Thanks!!!

Ronaldo.
Hello all,

I''m having trouble with the following test class. I get an error on line #15, "attempt to de-reference a null object".
Any thoughts please? I belive it has to do with the profile id, but I'm not sure.
@isTest 
private class ChatterAnswersAuthProviderRegTest { 
static testMethod void validateCreateUpdateUser() { 
Auth.UserData userData = new Auth.UserData('00ej0000000jJMR', 'testFirst', 'testLast', 
'testFirst testLast', 'no-reply@salesforce.com', null, 'testuserlong', 'en_US', 'facebook', 
null, new Map<String, String>{'language' => 'en_US'}); 
ChatterAnswersAuthProviderRegistration reg = new ChatterAnswersAuthProviderRegistration(); 
User newUser = reg.createUser(null, userData); 
System.assert(newUser == null); 


Auth.UserData updateUserData = new Auth.UserData('00ej0000000jJMR', 'updatedFirst', 'updatedLast', 
'updatedFirst updatedLast', 'no-reply@new.salesforce.com', null, 'testuserlong', 'en_US', 'facebook', 
null, new Map<String, String>{'language' => 'en_US'}); 
reg.updateUser(newUser.iD, null, updateUserData); 
} 
}

Thanks!!
I tried to search this over and over, but did not find any previous need like this one.

Is it possible to automatically create an ID upon loading of a visualforce page?

I was thinking about making the <apex:page "action="{!NewID}" > tag.. like the following:


public PageReference NewID() {


   Object__c NewID = new Object__c (name = 'New Record');
  
   insert NewID;

   String changepage2 = '/apex/MyVF_Page?id='+NewID.Id;
   PageReference pageref2 = new Pagereference(changepage2);
   pageref2.setRedirect(true);
         return pageref2;
   }


Any thoughts?


Thanks!

Hi guys,

 

So I have a trigger that writes the value of a number field into a text field. However it is not working properly, here is the problem.

 

It works up to Millions, however if I write the exact round amount of 9M, it doesn`t work properly and actually concatenates "Thousand" at the end, the final result would be: Nine Million Thousand.

 

All the rest is working 100% well. Any thoughts please?

 

trigger NumberToWords on Contract (before update) {
    For(Contract a : trigger.new){
        String alphaNumber = '';
        String numericNumber = string.valueof(a.Agreement_Value__c);
        System.debug(numericNumber);
        List<string> numericNumbers = new list <string>();
        For(integer i=numericNumber.length(); i>0; i-=3){
            Integer n=0;
            System.debug('integer n ' + n);
            If(I>3){
                n = i-3;
            }
            String substring = Numericnumber.substring(n,i);
            If(substring.length()==2){
                Substring = '0'+substring;
            }else if(substring.length()==1){
                Substring = '00'+ substring;
            }
            System.debug('substring '+substring);
            Numericnumbers.add(substring);
            If(I<3){break;}
        }
        System.debug('grouped list : ' +numericnumbers+'original number : '+a.Agreement_Value__c);
        For(integer I=0;I<numericnumbers.size();I++){ 
            String ngroup = numericnumbers.get(I);
            String ones = ngroup.substring(2,3);
            String tens = ngroup.substring(1,2);
            String hundreds = ngroup.substring(0,1);
            If(I != 0){
                If(I == 1){alphanumber = 'Thousand ' + alphanumber;}
                Else if(I == 2){alphanumber = 'Million ' + alphanumber;}
                //etc etc
            }
            If(tens == '1' && ones != '0'){
                If(ones =='1'){alphanumber = 'Eleven' + alphanumber;}
                Else if(ones == '2'){alphanumber = 'Twelve '+alphanumber;}
                Else if(ones == '3'){alphanumber = 'Thirteen '+alphanumber;}
                Else if(ones == '4'){alphanumber = 'Fourteen ' + alphanumber;}
                Else if(ones == '5'){alphanumber = 'Fifteen ' + alphanumber;}
                Else if(ones == '6'){alphanumber = 'Sixteen ' + alphanumber;}
                Else if(ones == '7'){alphanumber = 'Seventeen ' + alphanumber;}
                Else if(ones == '8'){alphanumber = 'Eighteen ' + alphanumber;}
                Else if(ones == '9'){alphanumber = 'Nineteen ' + alphanumber;}
            }else if(tens == '1' && ones == '0'){
                Alphanumber = 'Ten ' + alphanumber;
            }else if(ones != '0'){
                String o = underTen(ones);
                Alphanumber = o +' '+ alphanumber;
            }
            If(tens != '0' && tens != '1'){
                If(tens == '2'){alphanumber = 'Twenty ' + alphanumber;}
                Else if(tens =='3'){alphanumber = 'Thirty ' + alphanumber;}
                Else if(tens == '4'){alphanumber = 'Forty ' + alphanumber;}
                Else if(tens =='5'){alphanumber = 'Fifty ' +alphanumber;}
                Else if(tens == '6'){alphanumber = 'Sixty ' + alphanumber;}
                Else if(tens == '7'){alphanumber = 'Seventy ' + alphanumber;}
                Else if(tens == '8'){alphanumber = 'Eighty ' + alphanumber;}
                Else if(tens == '9'){alphanumber = 'Ninety ' + alphanumber;}
            }
            If(hundreds != '0'){
                String h = underten(hundreds);
                Alphanumber = h+' Hundred ' + alphanumber;
            }
        }
        Alphanumber.capitalize();
        //set the value of your text field to alphanumber
        System.debug('alphanumber : ' +alphanumber);
        a.USD_Agreement_Value__c = Alphanumber;
    }
    Public string underTen(string num){
        If(num =='1'){num = 'One';}
        Else if(num == '2'){num = 'Two';}
        Else if(num == '3'){num = 'Three';}
        Else if(num == '4'){num = 'Four';}
        Else if(num == '5'){num = 'Five';}
        Else if(num == '6'){num = 'Six';}
        Else if(num == '7'){num = 'Seven';}
        Else if(num == '8'){num = 'Eight';}
        Else if(num == '9'){num = 'Nine';}
        Return num;
    }

}

 

Thanks,

 

Ronaldo.

Hello,

 

 

I have successfuly imeplemented the code below for a custom object, however I can not find any test methods examples over the boards for the same need.

 

Can anybody please help me write a simple test method for the following class?

 

public with sharing class RelatedController 
{
 private ApexPages.StandardController stdCtrl;
  
 public RelatedController(ApexPages.StandardController std)
 {
  stdCtrl=std;
 }
  
 public void AccountPopulated()
 {
  Contact cont=(Contact) stdCtrl.getRecord();
  cont.Account=[select AccountNumber, Site from Account where id=:cont.AccountId];
 }
}

 

Original post at BobBuzzard blog

 

Thanks!!!

 

Ronaldo.

Hello, 

 

I have only 35% code coverage on the class below and I've been trying to increase it for a while but no success. Would someone please help me? :)

 

It has been developed to fix the 10000 soql limit, because my client has more than 100 fields in his page, as you can see there are one Edit VS page and a VIEW VS page.

 

public class Contracts_AVAC {
	
    public A_C_Availability__c q1 {get; private set;}
    public A_C_Availability__c q2 {get; private set;}
    public A_C_Availability__c q3 {get; private set;}
	
    public Contracts_AVAC (ApexPages.StandardController stdController) {
       
               ID qid = stdController.getRecord().Id;


//GENERAL FIELDS 

		q1 = [select A_C_Availability__c.Name, A_C_Availability__c.Status__c, A_C_Availability__c.Serial_Number__c

					from A_C_Availability__c where id = :qid limit 1];

//MORE FIELDS
				
		q2 = [select A_C_Availability__c.PInterior__c, A_C_Availability__c.POptional__c

					from A_C_Availability__c where id = :qid limit 1];

//MORE FIELDS
				
		q3 = [select A_C_Availability__c.LOptional__c, A_C_Availability__c.LOptionalF__c,					

					from A_C_Availability__c where id = :qid limit 1];
   }

		public PageReference save() {
			update q1;
			update q2;
			update q3;
			String changepage = '/apex/Contracts_View_AVAC?id='+ApexPages.currentPage().getParameters().get('id');
			PageReference pageref = new Pagereference(changepage);
			pageref.setRedirect(true);
			return pageref;  
		}
	
			
		public PageReference NewAVAC() {

		A_C_Availability__c NewAVAC = new A_C_Availability__c (name = 'New AVAC');
		insert NewAVAC;
	
// Load Edit page

		String changepage2 = '/apex/Contracts_New_AVAC?id='+NewAVAC.Id;
		PageReference pageref2 = new Pagereference(changepage2);
		pageref2.setRedirect(true);
        return pageref2;
		}	
				

}

 Test method:

 

public static testMethod void testContracts_AVAC() {

		// Make test AVAC	
				A_C_Availability__c testAVAC = new A_C_Availability__c (Name = 'Test AVAC');
				insert testAVAC;
		
		// Get ID from new AVAC	
				PageReference pageRef = new PageReference('/apex/Contracts_New_AVAC');
				ApexPages.currentPage().getParameters().put('id', testAVAC.id);
				Test.setCurrentPage(pageRef);
		
		// Open Custom Controller	
				ApexPages.StandardController avacController = new ApexPages.StandardController(testAVAC);
		
		// Open extension
				Contracts_AVAC qe1 = new Contracts_AVAC(avacController);
		
		// Create Test Object
				A_C_Availability__c TestAVAC1 = qe1.q1;
		
		// Check fields
				System.assertEquals('Test AVAC', TestAVAC1.Name);
	}

 

Thank you so much,

 

Ronaldo.

Hello all, I have the following code to roll-up summary products name to an opportunity text-long field, I need a summary of purchased products separated by commas.
Everything runs good with no errors, however I get no results, nothing happens, can you please take a look and help me?

Trigger:
trigger OppProductsTrigger on OpportunityLineItem (after delete, after insert, after update) {

    // fires after both insert and update
    if((Trigger.isInsert || Trigger.isUpdate) && Trigger.isAfter){

      // find the ids of all opps that were affected
      Set<Id> oppIds = new Set<Id>();
      for (OpportunityLineItem ar : [select Id, name, OpportunityId from OpportunityLineItem 
        where Id IN :Trigger.newMap.keySet()])
        oppIds.add(ar.OpportunityId);

      // process the opps  
      OppProductsTriggerHandler.ProcessProductsAsync(oppIds);


    // fires when records are deleted. may want to do undelete also?
    } else if(Trigger.isDelete && Trigger.isAfter){

      // find the ids of all opps that were affected
      Set<Id> oppIds = new Set<Id>();
      for (ID id : Trigger.oldMap.keySet())
        oppIds.add(Trigger.oldMap.get(id).OpportunityId);

      // process the opps
      OppProductsTriggerHandler.ProcessProductsAsync(oppIds);

    }

  }

Class: 
public with sharing class OppProductsTriggerHandler {

  @future 
  public static void ProcessProductsAsync(Set<ID> oppIds){

    // holds a map of the opp id and comma separated products to build
    Map<Id, String> oppProductMap = new Map<Id, String>();

    // get ALL of the products for all affected opps so we can build
    List<OpportunityLineItem> oppProducts = [select id, name, OpportunityId 
      from OpportunityLineItem 
      where OpportunityId IN :oppIds order by Name];

    for (OpportunityLineItem ar : oppProducts) {
      if (!oppProductMap.containsKey(ar.OpportunityId)) {
        // if the key (opp) doesn't exist, add it with product name
        oppProductMap.put(ar.OpportunityId,ar.Name);
      } else {
        // if the key (opp) already exist, add ", product-name"
        oppProductMap.put(ar.OpportunityId,oppProductMap.get(ar.OpportunityId) + 
          ', ' + ar.Name);
      }
    }

    // get the opps that were affected
    List<Opportunity> opps = [select id from Opportunity where Id IN :oppIds];

    // add the comma separated list of regions
    for (Opportunity a : opps)
      a.Products_Purchased__c = oppProductMap.get(a.id);

    // update the opps
    update opps;

  }  

}

Thank you!
Ron
Hello all, I have the following code to roll-up summary products name to an opportunity text-long field, I need a summary of purchased products separated by commas.
Everything runs good with no errors, however I get no results, nothing happens, can you please take a look and help me?

Trigger:
 
trigger OppProductsTrigger on OpportunityLineItem (after delete, after insert, after update) {

  // fires after both insert and update
  if((Trigger.isInsert || Trigger.isUpdate) && Trigger.isAfter){

    // find the ids of all opps that were affected
    Set<Id> oppIds = new Set<Id>();
    for (OpportunityLineItem ar : [select Id, name, OpportunityId from OpportunityLineItem 
      where Id IN :Trigger.newMap.keySet()])
      oppIds.add(ar.OpportunityId);

    // process the opps  
    OppProductsTriggerHandler.ProcessProductsAsync(oppIds);


  // fires when records are deleted. may want to do undelete also?
  } else if(Trigger.isDelete && Trigger.isAfter){

    // find the ids of all opps that were affected
    Set<Id> oppIds = new Set<Id>();
    for (ID id : Trigger.oldMap.keySet())
      oppIds.add(Trigger.oldMap.get(id).OpportunityId);

    // process the opps
    OppProductsTriggerHandler.ProcessProductsAsync(oppIds);

  }

}

Class:
 
public with sharing class OppProductsTriggerHandler {

  @future 
  public static void ProcessProductsAsync(Set<ID> oppIds){

    // holds a map of the opp id and comma separated products to build
    Map<Id, String> oppProductMap = new Map<Id, String>();

    // get ALL of the products for all affected opps so we can build
    List<OpportunityLineItem> oppProducts = [select id, name, OpportunityId 
      from OpportunityLineItem 
      where OpportunityId IN :oppIds order by Name];

    for (OpportunityLineItem ar : oppProducts) {
      if (!oppProductMap.containsKey(ar.OpportunityId)) {
        // if the key (opp) doesn't exist, add it with product name
        oppProductMap.put(ar.OpportunityId,ar.Name);
      } else {
        // if the key (opp) already exist, add ", product-name"
        oppProductMap.put(ar.OpportunityId,oppProductMap.get(ar.OpportunityId) + 
          ', ' + ar.Name);
      }
    }

    // get the opps that were affected
    List<Opportunity> opps = [select id from Opportunity where Id IN :oppIds];

    // add the comma separated list of regions
    for (Opportunity a : opps)
      a.Products_Purchased__c = oppProductMap.get(a.id);

    // update the opps
    update opps;

  }  

}


Thank you, thank you!
Ron
 
Hello,

Please review the code below, I don't get why its not passing 100%

Trigger:
 
trigger CreateFlightItinerary on Opportunity (after update) {    
List<Itinerary__c> fi = new List<Itinerary__c>();
    for (Opportunity a: Trigger.New)
         if (a.fi_automation_check__c == TRUE){
                 <b>fi.add (new Itinerary__c(</b>
                     Flight_Booking__c = a.Id,
					 Stop_1__c = a.Stop1_ID__c,
					 Flight_Crew_1__c = a.CrewM_1_ID__c
				));
         }
   insert fi;
}

Test class:
 
@isTest
private class testCreateFlightItinerary{
    static TestMethod void myTestClass()
    {
    	Account a = new Account();
	    a.Name = 'TestName';
	    a.Phone = '5512991224391';
        insert a;
    	
    	Opportunity o = new Opportunity();
 		o.Name = 'TestName';
		o.AccountID = a.Id;
		o.closedate = system.today();
		o.stagename = 'Sample Quote';
		o.Aircraft_Type__c = 'King Air';
		o.fi_automation_check__c=false;
		insert o; 
		
		o.fi_automation_check__c=true;
		update o;
    }
}

Thanks!
Hello all,

Please review the code below, I don't get why its not passing 100%

Trigger:
trigger CreateFlightItinerary on Opportunity (after update) {    
List<Itinerary__c> fi = new List<Itinerary__c>();
    for (Opportunity a: Trigger.New)
         if (a.fi_automation_check__c == TRUE){
                 fi.add (new Itinerary__c(
                     Flight_Booking__c = a.Id,
					 Stop_1__c = a.Stop1_ID__c,
					 Flight_Crew_1__c = a.CrewM_1_ID__c
				));
         }
   insert fi;
}

Test:
 
@isTest
private class testCreateFlightItinerary{
    static TestMethod void myTestClass()
    {
    	Account a = new Account();
	    a.Name = 'TestName';
	    a.Phone = '5512991224391';
        insert a;

    	Opportunity o = new Opportunity();
	    o.Name = 'TestName';
            o.AccountID = a.Id;
            o.closedate = system.today();
            o.stagename = 'Sample Quote';
            o.Aircraft_Type__c = 'King Air';
            o.fi_automation_check__c=True;
        insert o;             
    }
}

I get not coverage on the highlight line "fi.add (new Itinerary__c("


Thankss!!

Ronaldo.
Hello all,

Please review the code below, I don't get why its not passing 100%

Trigger:
 
trigger CreateFlightItinerary on Opportunity (after update) {    
List<Itinerary__c> fi = new List<Itinerary__c>();
    for (Opportunity a: Trigger.New)
         if (a.fi_automation_check__c == TRUE){
                 fi.add (new Itinerary__c(
                     Flight_Booking__c = a.Id,
					 Stop_1__c = a.Stop1_ID__c,
					 Flight_Crew_1__c = a.CrewM_1_ID__c
				));
         }
   insert fi;
}

@test Class
 
@isTest
private class testCreateFlightItinerary{
    static TestMethod void myTestClass()
    {
    	
    	Account a = new Account();
	    a.Name = 'TestName';
	    a.Phone = '5512991224391';
        insert a;

    	Opportunity o = new Opportunity();
	    o.Name = 'TestName';
            o.AccountID = a.Id;
            o.closedate = system.today();
            o.stagename = 'Sample Quote';
            o.Aircraft_Type__c = 'King Air';
        insert o;

        Itinerary__c i = new Itinerary__c();
	    i.Flight_Booking__c = o.Id;
		
        insert i;
        
    }
}

I highlighted the line "fi.add (new Itinerary__c(" which is not passing.

Thanks a lot!

Ronaldo.
Hello all,

I need to add a picklist field to the CommunitiesSelfReg VF page, but am getting the error below because I need to change it from inputext to inputfield, otherwise it won't show the drop-down menu.

"Could not resolve the entity from <apex:inputField> value binding '{!purchasedfrom}'.  <apex:inputField> can only be used with SObjects, or objects that are Visualforce field component resolvable."

VF Page:

 
<apex:page id="communitiesSelfRegPage" showHeader="true" controller="CommunitiesSelfRegController" title="{!$Label.site.user_registration}">
     <apex:define name="body">  
      <center>
<apex:form id="theForm" forceSSL="true">
                    <apex:pageMessages id="error"/>
                    
                    
                    <apex:panelGrid columns="2" style="margin-top:1em;">
                      <apex:outputLabel style="font-weight:bold;color:red;" value="First Name" for="firstName"/>
                      <apex:inputText required="true" id="firstName" value="{!firstName}" label="First Name"/>
                      <apex:outputLabel style="font-weight:bold;color:red;" value="Last Name" for="lastName"/>
                      <apex:inputText required="true" id="lastName" value="{!lastName}" label="Last Name"/>
                      <apex:outputLabel style="font-weight:bold;color:red;" value="{!$Label.site.email}" for="email"/>
                      <apex:inputText required="true" id="email" value="{!email}" label="{!$Label.site.email}"/>
                      
                      <apex:outputLabel style="font-weight:bold;color:red;" value="Phone" for="phone"/>
                      <apex:inputText required="true" id="phone" value="{!phone}" label="Phone"/>
                      <apex:outputLabel value="Title" for="title"/>
                      <apex:inputText required="true" id="title" value="{!title}" label="Title"/>                      
                      <apex:outputLabel style="font-weight:bold;color:red;" value="Company" for="companyname"/>
                      <apex:inputText required="true" id="companyname" value="{!companyname}" label="Company"/>                      

                      <apex:outputLabel style="font-weight:bold;color:red;" value="Street" for="street"/>
                      <apex:inputText required="true" id="street" value="{!street}" label="Street"/>
                      <apex:outputLabel style="font-weight:bold;color:red;"  value="City" for="city"/>
                      <apex:inputText required="true" id="city" value="{!city}" label="City"/>
                      <apex:outputLabel style="font-weight:bold;color:red;"  value="Zip" for="postalcode"/>
                      <apex:inputText required="true" id="postalcode" value="{!postalcode}" label="Zip"/>
                      <apex:outputLabel style="font-weight:bold;color:red;"  value="Country" for="country"/>
                      <apex:inputText required="true" id="country" value="{!country}" label="Country"/>
                      <apex:outputLabel style="font-weight:bold;color:red;"  value="State" for="state"/>
                      <apex:inputText required="true" id="state" value="{!state}" label="State"/>
                      
                      <apex:outputLabel value="Product Owner" for="productowner"/>
                      <apex:inputText required="true" id="productowner" value="{!productowner}" label="Product Owner"/>
<!--                       <apex:outputLabel value="Purchased From" for="purchasedfrom"/> -->
<!--                       <apex:inputText required="true" id="purchasedfrom" value="{!purchasedfrom}" label="Purchased From"/> -->
                      <apex:outputLabel value="Serial Number" for="serialnumber"/>
                      <apex:inputText required="true" id="serialnumber" value="{!serialnumber}" label="Serial Number"/>
                      
                      <apex:inputfield value="{!u.Purchased_From__c}"/>  
                      
					  <apex:outputLabel value="{!$Label.site.community_nickname}" for="communityNickname"/>
                      <apex:inputText required="true" id="communityNickname" value="{!communityNickname}" label="{!$Label.site.community_nickname}"/>                      
                      <apex:outputLabel value="{!$Label.site.password}" for="password"/>
                      <apex:inputSecret id="password" value="{!password}"/>
                      <apex:outputLabel value="{!$Label.site.confirm_password}" for="confirmPassword"/>
                      <apex:inputSecret id="confirmPassword" value="{!confirmPassword}"/>
                      <apex:outputText value=""/>
                      <apex:commandButton action="{!registerUser}" value="{!$Label.site.submit}" id="submit"/>
                    </apex:panelGrid> 
                  <br/>
</apex:form>
     </center>
      <br/>
    </apex:define>

</apex:page>

Class:
 
/**
 * An apex page controller that supports self registration of users in communities that allow self registration
 */
public with sharing class CommunitiesSelfRegController {

  public String firstName {get; set;}
  public String lastName {get; set;}
  public String email {get; set;}
  public String phone {get; set;}
  public String title {get; set;}
  public String companyname {get; set;}
  public String street {get; set;}
  public String city {get; set;}
  public String postalcode {get; set;}
  public String country {get; set;}
  public String state {get; set;}
  public String productowner {get; set;}
  public String purchasedfrom {get; set;}
  public String serialnumber {get; set;}
  public String password {get; set {password = value == null ? value : value.trim(); } }
  public String confirmPassword {get; set { confirmPassword = value == null ? value : value.trim(); } }
  public String communityNickname {get; set { communityNickname = value == null ? value : value.trim(); } }
  
  public CommunitiesSelfRegController() {}
  
  private boolean isValidPassword() {
    return password == confirmPassword;
  }

  public PageReference registerUser() {
  
    // it's okay if password is null - we'll send the user a random password in that case
    if (!isValidPassword()) {
      System.debug(System.LoggingLevel.DEBUG, '## DEBUG: Password is invalid - returning null');
      ApexPages.Message msg = new ApexPages.Message(ApexPages.Severity.ERROR, Label.site.passwords_dont_match);
      ApexPages.addMessage(msg);
      return null;
    }  

    
    String profileId = '00ej0000000jJMR'; // To be filled in by customer.
    
    String accountId = '001g000000QMTDX'; // To be filled in by customer.  

    // Set this to your main Communities Profile API Name
    String profileApiName = 'PowerCustomerSuccess';
    //String profileId = [SELECT Id FROM Profile WHERE UserType = :profileApiName LIMIT 1].Id;
    //List<Account> accounts = [SELECT Id FROM Account LIMIT 1];
    //System.assert(!accounts.isEmpty(), 'There must be at least one account in this environment!');
    //String accountId = accounts[0].Id;
    
    String userName = email;

    User u = new User();
    u.Username = userName;
    u.Email = email;
    u.Phone = phone;
    u.Title = title;
    u.Street = street;
    u.City = city;
    u.PostalCode = postalcode;
    u.Country = country;
    u.State = state;
    u.Product_Owner__c = productowner;
    u.Purchased_From__c = purchasedfrom;
    u.Serial_Number__c = serialnumber;
    u.CompanyName = companyname;
    u.FirstName = firstName;
    u.LastName = lastName;
    u.CommunityNickname = communityNickname;
    u.ProfileId = profileId;
    
    String userId = Site.createPortalUser(u, accountId, password);
   
    if (userId != null) { 
      if (password != null && password.length() > 1) {
        System.debug(System.LoggingLevel.DEBUG, '## DEBUG: User creation successful and password ok - returning site.login');
        return Site.login(userName, password, null);
      }
      else {
        System.debug(System.LoggingLevel.DEBUG, '## DEBUG: User creation successful but password not ok - redirecting to self reg confirmation');
        PageReference page = System.Page.CommunitiesSelfRegConfirm;
        page.setRedirect(true);
        return page;
      }
    }
    System.debug(System.LoggingLevel.DEBUG, '## DEBUG: User creation not successful - returning null');
    return null;
  }
}


Thanks!!!

Ronaldo.
I tried to search this over and over, but did not find any previous need like this one.

Is it possible to automatically create an ID upon loading of a visualforce page?

I was thinking about making the <apex:page "action="{!NewID}" > tag.. like the following:


public PageReference NewID() {


   Object__c NewID = new Object__c (name = 'New Record');
  
   insert NewID;

   String changepage2 = '/apex/MyVF_Page?id='+NewID.Id;
   PageReference pageref2 = new Pagereference(changepage2);
   pageref2.setRedirect(true);
         return pageref2;
   }


Any thoughts?


Thanks!

Hello,

 

 

I have successfuly imeplemented the code below for a custom object, however I can not find any test methods examples over the boards for the same need.

 

Can anybody please help me write a simple test method for the following class?

 

public with sharing class RelatedController 
{
 private ApexPages.StandardController stdCtrl;
  
 public RelatedController(ApexPages.StandardController std)
 {
  stdCtrl=std;
 }
  
 public void AccountPopulated()
 {
  Contact cont=(Contact) stdCtrl.getRecord();
  cont.Account=[select AccountNumber, Site from Account where id=:cont.AccountId];
 }
}

 

Original post at BobBuzzard blog

 

Thanks!!!

 

Ronaldo.

Hello, 

 

I have only 35% code coverage on the class below and I've been trying to increase it for a while but no success. Would someone please help me? :)

 

It has been developed to fix the 10000 soql limit, because my client has more than 100 fields in his page, as you can see there are one Edit VS page and a VIEW VS page.

 

public class Contracts_AVAC {
	
    public A_C_Availability__c q1 {get; private set;}
    public A_C_Availability__c q2 {get; private set;}
    public A_C_Availability__c q3 {get; private set;}
	
    public Contracts_AVAC (ApexPages.StandardController stdController) {
       
               ID qid = stdController.getRecord().Id;


//GENERAL FIELDS 

		q1 = [select A_C_Availability__c.Name, A_C_Availability__c.Status__c, A_C_Availability__c.Serial_Number__c

					from A_C_Availability__c where id = :qid limit 1];

//MORE FIELDS
				
		q2 = [select A_C_Availability__c.PInterior__c, A_C_Availability__c.POptional__c

					from A_C_Availability__c where id = :qid limit 1];

//MORE FIELDS
				
		q3 = [select A_C_Availability__c.LOptional__c, A_C_Availability__c.LOptionalF__c,					

					from A_C_Availability__c where id = :qid limit 1];
   }

		public PageReference save() {
			update q1;
			update q2;
			update q3;
			String changepage = '/apex/Contracts_View_AVAC?id='+ApexPages.currentPage().getParameters().get('id');
			PageReference pageref = new Pagereference(changepage);
			pageref.setRedirect(true);
			return pageref;  
		}
	
			
		public PageReference NewAVAC() {

		A_C_Availability__c NewAVAC = new A_C_Availability__c (name = 'New AVAC');
		insert NewAVAC;
	
// Load Edit page

		String changepage2 = '/apex/Contracts_New_AVAC?id='+NewAVAC.Id;
		PageReference pageref2 = new Pagereference(changepage2);
		pageref2.setRedirect(true);
        return pageref2;
		}	
				

}

 Test method:

 

public static testMethod void testContracts_AVAC() {

		// Make test AVAC	
				A_C_Availability__c testAVAC = new A_C_Availability__c (Name = 'Test AVAC');
				insert testAVAC;
		
		// Get ID from new AVAC	
				PageReference pageRef = new PageReference('/apex/Contracts_New_AVAC');
				ApexPages.currentPage().getParameters().put('id', testAVAC.id);
				Test.setCurrentPage(pageRef);
		
		// Open Custom Controller	
				ApexPages.StandardController avacController = new ApexPages.StandardController(testAVAC);
		
		// Open extension
				Contracts_AVAC qe1 = new Contracts_AVAC(avacController);
		
		// Create Test Object
				A_C_Availability__c TestAVAC1 = qe1.q1;
		
		// Check fields
				System.assertEquals('Test AVAC', TestAVAC1.Name);
	}

 

Thank you so much,

 

Ronaldo.

Hi

 

I have a VF page where in I am using case standard controller.

The first time when the page is displayed 2 input fields (eg.) are there i.e. Name and Email. which are static. Another 2 fields are their like Vendor Name and Vendor Contact No. which are dynamic.

 

Now, I want to implement the functionality wherein if a user clicks on Add Row button,  1more row will appear to enter a value in both  the fields(Vendor name and Vendor Contact No.). So, if he clicks the button 5 times, 5 rows shud appear with thses two columns.

After providing the inputs, he will click on "Save " button, and the record should be saved wherein the inputs provided in multiple rows should be saved into the related list of the Case detail page (Case details page will contain the information like Name and Email). Request you to please forward me the code for the above mentioned functionality. Since its a n urgent requirement. An early reply will be highly appreciated. Thanks.

  • May 07, 2010
  • Like
  • 0