• TechnozChamp
  • NEWBIE
  • 5 Points
  • Member since 2012

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 0
    Questions
  • 23
    Replies
Hi,
I have a trigger. when I'm trying to update data through dataloader, I getting Soql 101 query limit error
trigger Approvers on Approval__c (before insert,before update)
{
Boolean assigned ;
list<Approver__c> lstApprover;
for(Approval__c c:trigger.new)
{
 if(c.Category__c=='Dental' || c.Category__c=='General')
 {
 lstApprover = [Select Bill__c, Approver_1__c, Approver_2__c,Category__c,Market__c,Reason__c, Id, RecordTypeId, Region__c, Division__c, Sub_Division__c,Zone__c 
 from Approver__c where  reason__c= :c.reason__c and  Category__c=:c.Category__c order by Bill__c asc];
 assigned = false;
}
}
if(lstApprover.size()>0 && c.Status__c!='Approved'){
    
for(Approver__c tmplstApprover :  lstApprover ){
if(assigned == false && c.Bill__c < tmplstApprover.Bill__c){
            c.Approver_1__c=tmplstApprover.Approver_1__c;
            c.Approver_2__c=tmplstApprover.Approver_2__c;
             c.Approver__c= tmplstApprover.id; 
            assigned = true;
          }
    }
}

}

Thanks  in Advance.
I am trying to create a trigger that creates a new user record when a custom object picklist is set to 'in progress'. I am getting an error that says "Illegal variable declaration: newUser.FirstName" Can anyone help me out and tell me what this error means? Here is the whole trigger, the bolded line is causing the error:

trigger AutoUserCreate on User (after update) {
    List<User> UserList = new List<User>();
    for( Support_Request__c sr : Trigger.new) {
       if (sr.status__c == 'in progress'){
    User newUser = new User ();
    string newUser.FirstName = Support_Request__c.First_Name__c;
    string newUser.LastName = Support_Request__c.Last_Name__c;
    insert UserList;
    }
   }
}
I want to loop through a list of existing Cases and capture the Parent Case into another list.
What's the best way to accomplish this?  This code doesn't work because I'm trying to add an ID as an Object, so how do I add the sObject?
List<Case> childCases = new List<Case>([SELECT id, parentid FROM Case WHERE condition exists]);

List<Case> parentCases = new List<Case>();
for(Case c:childCases{
  parentCases.add(childCases.ParentId);
}

 
Trying to deploy development from my sandbox using change sets. Whilst custom fields, tabs etc come across fine, the triggers are failing with the following error:

Code Coverage Failure Your organization's code coverage is 0%. You need at least 75% coverage to complete this deployment. Also, the following triggers have 0% code coverage. Each trigger must have at least 1% code coverage.

This means nothing to me and I'm just getting more confused looking through the help documents. I don't really do code and I don't know where to start. Any help would be very much appreciated
I am deploying my code to production and i am getting the below error

My trigger

trigger OpportunityTrigger on Opportunity (after delete, after insert, after undelete,
after update, before delete, before insert, before update) {

    if(Trigger.isAfter && Trigger.isInsert){
        {
        EncryptURl.insertOpp(Trigger.new,Trigger.newMap.keySet());
        }
}

and my trigger class is

public static void insertOpp(Opportunity[] o,Set<id> newMapKeySet)
{

    list<Opportunity> oppsToUpdate =[select id,Encrypted_URL__c from Opportunity where id  IN :newMapKeySet];
    for(Opportunity op:oppsToUpdate){
        if(op.id != null){
            string oppid=op.id;
            Blob dataLead = Blob.valueOf(oppid);
            String b64Data = EncodingUtil.base64Encode(dataLead);
            string oppURL =Label.PWV_FavoriteURL+'oId='+b64Data;
            op.Encrypted_URL__c =oppURL;
        }  
   }
    try{
    update oppsToUpdate;
    }catch(exception e){
            system.debug('DMl exception'+e);
     }

}

can i know how to over the soql exception

Hi,

I am trying to setup a functionality when the user creates a child record from the child related list on the parent page,
some fields in the child record get prepopulated with the details from the parent record. I am having no issues doing this.
However the user should be able to change the parent (lookup field) from the child record and when the user does that I have a button that updates the child record fields with the new parent information.

I keep getting an Attempt to dereference a null object error.

Can someone please point out any corrections that I can do to my code to make it work.


public class Test_Controller {
    public Test_Controller(ApexPages.StandardController controller) {
    Child__c child = (Child__c)controller.getRecord();
        if (child.parent__c != null) {
            Parent__c parent = [select Name__c, TField1__c, FROM Parent__c  
                                                  WHERE id =: child.parent__c limit 1];

            child.parent__c = parent.Id;
            child.Name__c = parent.Name;
            child.TField1__c = parent.TField1__c;

        }
    }
 
    public PageReference UpdateParentInfo(){
        child = (Child__c)std.getRecord();
            List<Parent__c> parent = [SELECT Name__c, TField1__c, FROM Parent__c  
                                                      WHERE id =: child.parent__c];
        
            if(!parent.isEmpty()){
                child.Name__c = parent.get(0).Name;
                child.TField1__c = parent.get(0).TField1__c;
           
            }

    }
}


Hello I am a beginner developer. I have implemented an apex trigger that counts all related Consumer Lead records.

I am getting this error when I try to create a new Lead Request record

 

Error: Invalid Data. 
Review all error messages below to correct your data.
Apex trigger rollupConsumerLeads caused an unexpected exception, contact your administrator: rollupConsumerLeads: execution of BeforeInsert caused by: System.NullPointerException: Attempt to de-reference a null object: Trigger.rollupConsumerLeads: line 5, column 1
 

 

trigger rollupConsumerLeads on Lead_Request__c (before insert, before update) {
  for(Lead_Request__c p:Trigger.new)
    p.Leads_Given_NEW__c = 0;
  for(Consumer_Leads__c c:[select id,Lead_Request_NEW__c from Consumer_Leads__c where Lead_Request_NEW__c in :Trigger.new])
    Trigger.newMap.get(c.Lead_Request_NEW__c).Leads_Given_NEW__c++;
}

 

Any help would be appricciated.

Apex Test Result Detail  

Time Started 4/4/2013 1:28 PM Class QuoteManager_Test Method Name invokeTestMethod Pass/Fail Fail Error Message System.NullPointerException: Attempt to de-reference a null object Stack Trace Class.QuoteManager.updatePartnerCBMDetails: line 43, column 1
Class.QuoteManager_Test.invokeTestMethod: line 41, column 1

 

Please advice me what should I do to successfully run my test case.

===================================================================================

public with sharing class QuoteManager {

  /* REPLACES trigger QuoteFieldUpdates on Quote__c (before insert, before update)*/
  
   private static List<Opportunity> OppList;

    public static List<Opportunity> getOppISVTeamMembersDetails(Set<Id> opportunityIds)
    {
        if (OppList == null){
            OppList = [SELECT Partner_CBM__c, End_User_Account_Owner__c FROM Opportunity WHERE Id in:opportunityIds];
        }
        return OppList;
    }
    
    private static List<Quote_Part__c > QuotePartsList;

    public static List<Quote_Part__c> getQuotePartsDetails(Set<Id> requiredQuoteIDs)
    {
        if (QuotePartsList == null){
            QuotePartsList = [SELECT Product_Category__c, 
                              Margin_Percent__c,Product_Code__c, 
                              Quote_Ref__c,Margin_Net_Dollars__c,CurrencyISOCode 
                              FROM Quote_Part__c
                              WHERE Quote_Ref__c =: requiredQuoteIDs 
                              AND Product_Category__c != 'Multi Product Accessory' 
                              AND Product_Category__c != 'Media' 
                              AND Product_Category__c != 'Service' 
                              AND Product_Category__c != 'Software' 
                              AND Product_Category__c != 'ProductLinks' 
                              AND Product_Category__c != 'OEM' 
                              AND Margin_Net_Dollars__c != null
                              ORDER BY Margin_Net_Dollars__c];
        }
        return QuotePartsList;
    }
    
    public static void updatePartnerCBMDetails(List<Quote__C> newQuote)
    {
        Map<Id, Opportunity> oppMap = new Map<Id, Opportunity>();
        
        List<Opportunity> oppsData = new List<Opportunity>();
       
        Set<ID> opportunityIds = new Set<ID>();                            // this line I am getting an error while running the test case.
         
        if (trigger.isUpdate && !QuotePartManager.isInsert)
        {
            for (Quote__c quote :newQuote)
            {
            opportunityIds.add(quote.Opportunity_Name__c);
            }
            /*oppsData = [SELECT Partner_CBM__c, End_User_Account_Owner__c FROM Opportunity WHERE Id in :opportunityIds];*/
            oppsData =getOppISVTeamMembersDetails(opportunityIds);
            
            for(Opportunity opp : oppsData) {
            oppMap.put(opp.Id, opp);
            }  
        }
  
        for (Quote__c quote :newQuote)
        {
            if (trigger.isInsert)
            {
              quote.Owner_Lookup__c = quote.OwnerID;  
            }
            if (trigger.isUpdate)
            {
              if(quote.Owner_Lookup__c != quote.OwnerId)
              {
                quote.Owner_Lookup__c = quote.OwnerID;  
              }
              if(oppMap.get(quote.Opportunity_Name__c) != null)
              {
                if(oppMap.get(quote.Opportunity_Name__c).Partner_CBM__c != quote.Partner_CBM__c)
                {
                  quote.Partner_CBM__c = oppMap.get(quote.Opportunity_Name__c).Partner_CBM__c;  
                }
                if(oppMap.get(quote.Opportunity_Name__c).End_User_Account_Owner__c != quote.End_User_Account_Owner__c)
                {
                  quote.End_User_Account_Owner__c = oppMap.get(quote.Opportunity_Name__c).End_User_Account_Owner__c;  
                }
              }  
            }
    }
    }
    
  /* REPLACES trigger QuoteBeforeDelete on Quote__c (before delete)*/
    public static void QuoteBeforeDelete(List<Quote__c> oldQuotes)
    {
    for (Quote__c quote : oldQuotes)
    {
      if (quote.Main_Quote__c)
      {
        if(!Test.isRunningTest())
        {
          quote.addError('You cannot delete a Main Quote. Uncheck the Main Quote checkbox on the Quote prior to deleting.');
        }
      }
    }
    }

 
  /*
    
    REPLACES trigger populateMarginsFromQuoteParts on Quote__c (before update)
    Trigger to assign field values "Lowest_Margin_Percent__c" and "Highest_Margin_Net_Value__c" on EDIT of a Quote:
    IF(Quote__c.Quote_Type__c EQUALS 'Hardware' AND PE.Approval_Stage__c EQUALS 'In Review') 
    ONE:
    o   Evaluate all HW Quote Parts WHERE Product_Category__c NOT EQUALS Media, Service, Software, ProductLinks, OEM:
    o   return item with lowest overall margin percentage (Margin_Percent__c)
    o   Capture that Item's corresponding Product_Code__c, Margin_Net_Dollars__c, and Margin_Percent__c into text field(s) on the Quote
    TWO:
    o   Evaluate all HW Quote Parts WHERE Product_Category__c NOT EQUALS Multi Product Accessory, Media, Service, Software, ProductLinks, OEM:
    o   return item with highest total margin dollar value (Margin_Net__Dollars__c) that has the lowest margin percentage (Margin_Percent__c)
    o   Capture that Item's corresponding Product_Code__c, Margin_Net_Dollars__c, and Margin_Percent__c into text field(s) on the Quote 
    
  */
  public static void populateMarginsFromQuoteParts(List<Quote__c> newQuotes)
  {
    /*Set of Quote IDs for which the Margins from Quote Parts should be calculated*/
    Set<Id> requiredQuoteIDs = new Set<Id>();
    Quote__c[] Quotes = new Quote__c[]{};
    for(Integer i=0; i < newQuotes.size(); i++)
    {
        if(newQuotes[i].HW_Approval_Stage__c == 'In Review')
        {
            system.debug('Approval is IN REVIEW');
            requiredQuoteIDs.add(newQuotes[i].Id);
            Quotes.add(newQuotes[i]);
        }
    }
    
    /*     
     Map of Quote ID and List of Quote Parts under that Quote - Lowest Margin Percent       
    */
    
    Map<Id,List<Quote_Part__c>> quotePartsMapLowestMarginPercent = new Map<Id,List<Quote_Part__c>>();
    
    /*    
    Map of Quote ID and List of Quote parts under that Quote - HIghest Margin Dollar Value    
    */
    
    Map<Id,List<Quote_Part__c>> quotePartsMapHighestMarginValue = new Map<Id,List<Quote_Part__c>>();
    
    /*    
    Query through all Line Items (WHERE Product_Category__c NOT EQUALS Media, 
    Service, Software, ProductLinks, OEM)    
    */
    if (!requiredQuoteIDs.isEmpty()){
      system.debug('requiredQuoteIDs contains ID');
      
    /*  
     FIRST ELEMENT --> LOWEST MARGIN PERCENT*
    */
    for(Quote_Part__c qpLi:getQuotePartsDetails(requiredQuoteIDs))
      {
          if(quotePartsMapLowestMarginPercent.get(qpLi.Quote_Ref__c) == null)
          {
              quotePartsMapLowestMarginPercent.put(qpLi.Quote_Ref__c, new List<Quote_Part__c>{ qpLi });
          }
          else
          {
              quotePartsMapLowestMarginPercent.get(qpLi.Quote_Ref__c).add(qpLi);
          }
          
      }
      system.debug('LowestMarginPercent map size is '+quotePartsMapLowestMarginPercent.size());
      /*
      Query through all Quote Parts (WHERE Product_Category__c NOT EQUALS Multi Product Accessory, Media, Service, Software, ProductLinks, OEM)
      */
     for(Quote_Part__c qpLi:getQuotePartsDetails(requiredQuoteIDs))
      {
          if(quotePartsMapHighestMarginValue.get(qpLi.Quote_Ref__c) == null)
          {
              quotePartsMapHighestMarginValue.put(qpLi.Quote_Ref__c, new List<Quote_Part__c>{ qpLi });
          }
          else
          {
              quotePartsMapHighestMarginValue.get(qpLi.Quote_Ref__c).add(qpLi);
          }
      }
      system.debug('HighestMarginValue map size is '+quotePartsMapHighestMarginValue.size());
    }
    /*Loop through Price Exceptions being updated and assign Value*/
    if (!Quotes.isEmpty())
    {
      system.debug('Quotes Loop begins');
      for(Quote__c Quote: Quotes)
      {
          if(quotePartsMapLowestMarginPercent.get(Quote.Id) != null && quotePartsMapLowestMarginPercent.get(Quote.Id).size() > 0)
          {
              system.debug('Lowest Percent Margin Percent is '+quotePartsMapLowestMarginPercent.get(Quote.Id)[0].Margin_Percent__c);
              String marginValueFormat = quotePartsMapLowestMarginPercent.get(Quote.Id)[0].Margin_Net_Dollars__c.format();
              system.debug('Lowest Percent marginNetDollars is '+quotePartsMapLowestMarginPercent.get(Quote.Id)[0].Margin_Net_Dollars__c.format());
              system.debug('Lowest Percent marginValueFormat is '+marginValueFormat);
              if(marginValueFormat.contains('.'))
              {
                  List<String> marginDecimals = marginValueFormat.split('\\.');
                  
                  if(marginDecimals.size() == 2)
                  {
                      if(marginDecimals[1].length() == 1)
                      {
                          marginValueFormat = marginValueFormat + '0';
                      }
                  }
              }
              else
              {
                  marginValueFormat = marginValueFormat + '.00';
              }
              
              String lowestMarginPercent = 'P/N ' + String.valueOf(quotePartsMapLowestMarginPercent.get(Quote.Id)[0].Product_Code__c) + 
                             ', Margin Value=' + quotePartsMapLowestMarginPercent.get(Quote.Id)[0].CurrencyISOCode + ' ' + marginValueFormat + 
                             ', Margin %=' + String.valueOf(quotePartsMapLowestMarginPercent.get(Quote.Id)[0].Margin_Percent__c);
              
              //Assign to Field
              Quote.Quote_Part_Lowest_Lowest_Margin__c = lowestMarginPercent;
          }
          
          if(quotePartsMapHighestMarginValue.get(Quote.Id) != null && quotePartsMapHighestMarginValue.get(Quote.Id).size() > 0)
          {
              Integer index = quotePartsMapHighestMarginValue.get(Quote.Id).size() - 1;
              
              String marginValueFormat = quotePartsMapHighestMarginValue.get(Quote.Id)[index].Margin_Net_Dollars__c.format();
              system.debug('Highest Value marginNetDollars is '+quotePartsMapHighestMarginValue.get(Quote.Id)[index].Margin_Net_Dollars__c.format());
              system.debug('Highest Value marginValueFormat is '+marginValueFormat);
              if(marginValueFormat.contains('.'))
              {
                  List<String> marginDecimals = marginValueFormat.split('\\.');
                  
                  if(marginDecimals.size() == 2)
                  {
                      if(marginDecimals[1].length() == 1)
                      {
                          marginValueFormat = marginValueFormat + '0';
                      }
                  }
              }
              else
              {
                  marginValueFormat = marginValueFormat + '.00';
              }
              
              String highestMarginValue = 'P/N ' + String.valueOf(quotePartsMapHighestMarginValue.get(Quote.Id)[index].Product_Code__c) + 
                            ', Margin Value=' + quotePartsMapHighestMarginValue.get(Quote.Id)[0].CurrencyISOCode + ' ' + marginValueFormat + 
                            ', Margin %=' + String.valueOf(quotePartsMapHighestMarginValue.get(Quote.Id)[index].Margin_Percent__c);
              
              //Assign to Field
              Quote.Quote_Part_Highest_Margin_Lowest_Marg__c = highestMarginValue;
          }
      }
    }
  }
}

 

 

===============================================================================

 

This is my test class

 

@isTest
public with sharing class QuoteManager_Test {
    
    static testMethod void invokeTestMethod()
    {
    List<Account> alist = TestUtil.createTestAccounts(1, true);
    
    List<Opportunity> olist = TestUtil.createTestOpportunities(1, true, alist.get(0));
    
    Quote__c quote = new Quote__c(Opportunity_Name__c = olist.get(0).Id,Multiple__c = 100,Discount__c = 0,
                              Valid_Until__c = system.today().addDays(28),Sync_Required__c=true,Is_Portal_Quote__c=true,
                              HW_Approval_Stage__c='In Review',
                              Main_Quote__c=true,Type__c='Master',Status__c='Live'); 
    List<Quote__c> quoteList = new List<Quote__c>();
    
    quoteList.add(quote);
    
    //QuoteManager.QuoteBeforeDelete(quoteList);
    
   QuoteManager.populateMarginsFromQuoteParts(quoteList);
   QuoteManager.QuoteBeforeDelete(quoteList);
    
   //Opportunity[] testopps = TestUtil.createTestOpportunities(1, false, testaccts.get(0));
      
     Opportunity[] testopps = TestUtil.createTestOpportunities(1, false, alist.get(0));
    for (Opportunity to : testOpps)
    {
        to.PR_Admin__c = alist.get(0).Id;
        to.OwnerId = UserInfo.getUserId();
        to.End_User_Location_RCSM__c = alist.get(0).Id;
        to.End_User_Location_RVP__c = alist.get(0).Id;
        to.End_User_Account_Owner__c = alist.get(0).Id;
        to.Partner_CBM__c = alist.get(0).Id;
        to.Partner_CBM_Manager__c = alist.get(0).Id;
    }
    
    if(quoteList.get(0).HW_Approval_Stage__c == 'In Review'){
    
    }
    
    QuoteManager.updatePartnerCBMDetails(quoteList);
    }
    
    static testMethod void testupdatePartnerCBMDetails(){
     
    }
}

 

==================================================================

 

I have an app that is getting a System.NullPointerException: Attempt to de-reference a null object at a customer account.  Does this error log any information about the error that I can ask the customer to provide - if so how does one get to the info?

We have triggers running to update Contact when Campaign Member Status is changed for different types of Campaigns. Each trigger has filtering, that means only those Campaign Members fall in a particular campaign will update Contact.  We have another new campaign and just developed a simple trigger to update Contact.  The trigger itself is running fine but when we deployed to production, another two test class has error "System.LimitException: Too many SOQL queries: 101".  One is related to Campaign while the other is related to Contact.  May I know why?

Hi,

Any one please solve this issue 

 

when i am going to run the test class it will show an error System.QueryException: List has no rows for assignment to SObject 

and Class.SalesrepForecastUpdatetest.testsearch: line 66, column 9 External entry point

 

This is my  Apex class code sample  

 

 

User usr = [Select id,Alias,lastname,firstname,ContactId,Profile.name from User where id=:UserInfo.getUserId() Limit 1];

    public List<CustForecastWrapper> getCustForecasts(){ 

      if(custForecasts != null){

            return custForecasts;        } 

      custForecasts = new List<CustForecastWrapper>();

        if(usr.id == null){

            return custForecasts;   

    } 

      New_Forecast__c CustFCst=new New_Forecast__c(); 

              CustFCst=[select id,name from new_forecast__c where Region__r.sales_Rep__c=:usr.id limit 1];

           '''''''''''''''''''''

''''''''''''''''''

'''''''''''''

}

 

    public void SearchForecast(){    

   custForecasts = null;

   prodForecasts = null;             

  if(ObjectType == 'Product'){            

  ForeCastTitle = Year + ' Product Forecast';            

    getProdForecasts();   

    }        

      if(ObjectType=='Region'){                  

    if(usr.firstname == null)         

      ForeCastTitle = '';   

        else        

        ForeCastTitle = Year + ' Region Forecast for ' + usr.firstname;                  

  getCustForecasts();   

    }

        }

 

Test Method:

 

    static testMethod void testsearch(){ 

    User usr = [Select id from User where firstname=:'test' Limit 1];     

     SalesrepForecastUpdate con=new  SalesrepForecastUpdate (); 

      con.ObjectType = 'Region';    con.Year = String.ValueOf(Date.today().year()); 

         con.searchforecast();              

 List<CustForecastWrapper> forecasts = con.getCustForecasts();                                        }

 

 

 

Thanks 

 

Im getting error like List has no rows for assignment to SObject here im giving the code plse tell me what s the error in that controller.

 

public class AAFControl {
    private ApexPages.StandardController con;    
    private Application_Form__c objAAF;
    private Application_Form__c aaf = new Application_Form__c();
  //public List<Application_Form__c> aaform{get;set;}
    public String LDate{get;set;}
     public String EDate{get;set;}
     public String BDate{get;set;}  
    private String AfName{get;set;}
    public String sDate{get;set;}
     public String stDate{get;set;}
     public String cDate{get;set;}
    public String  dyDate{get;set;}
     public String oDate{get;set;}
     public String eyDate{get;set;}
     public String tDate{get;set;}
     public String  fDate{get;set;}
     public Id pid;
     public Id aafId;
     public AAFControl(ApexPages.StandardController controller) {
        
      con=controller;
      aafId=con.getRecord().id;
      system.debug('iddddddddddddddddddddddd'+aafId);
      aaf=[select Id,Date_of_Issue__c,Expiry_Date__c,Date_of_Birth__c,SPM_O_Level_or_equivalent_Year_of_Comp__c,STPM_A_Level_UEC_or_equivalent_Year__c,Certificate_Year_if_Completion__c,Diploma_Year_if_Completion__c,Others_Year_if_Completion__c,English_1119_Year_of_Completion__c,TOEFL_IELT_Year_of_Completion__c,Form__c from Application_Form__c where id=:aafId];
       system.debug('testtttttttttttttttttt'+aaf);
        //aaf = [select Id,Date_of_Issue__c,Expiry_Date__c,Date_of_Birth__c,SPM_O_Level_or_equivalent_Year_of_Comp__c,STPM_A_Level_UEC_or_equivalent_Year__c,Certificate_Year_if_Completion__c,Diploma_Year_if_Completion__c,Others_Year_if_Completion__c,English_1119_Year_of_Completion__c,TOEFL_IELT_Year_of_Completion__c,Form__c from Application_Form__c where id=:ApexPages.currentPage().getParameters().get('id')][0];
       //aaf = aaform.get(0);
      // aafform=aaf.get(0);
      // system.debug('AAFFFFFFFFFFFFFF'+aafform);
       // pid = aaform.id;
        system.debug('pid'+pid);
        DateTime dt=aaf.Date_of_Issue__c;
        DateTime ed=aaf.Expiry_Date__c;
        DateTime dob=aaf.Date_of_Birth__c;
        DateTime spm=aaf.SPM_O_Level_or_equivalent_Year_of_Comp__c;
        DateTime stpm=aaf.STPM_A_Level_UEC_or_equivalent_Year__c;
        DateTime cyc=aaf.Certificate_Year_if_Completion__c;
        DateTime dyc=aaf.Diploma_Year_if_Completion__c;
        DateTime oyc=aaf.Others_Year_if_Completion__c;
        DateTime eyc=aaf.English_1119_Year_of_Completion__c;
        DateTime toe=aaf.TOEFL_IELT_Year_of_Completion__c;
        DateTime frm=aaf.Form__c;
          sDate=' ';
          stDate=' ';
          dyDate=' ';
          cDate=' ';
          oDate=' ';
          tDate=' ';
          fDate=' ';
          eyDate=' ';
       LDate=dt.format('dd-MM-yyyy');
       EDate=ed.format('dd-MM-yyyy');
         BDate=dob.format('dd-MM-yyyy');
     sDate=spm.format('dd-MM-yyyy');
      stDate=stpm.format('dd-MM-yyyy');
      
       cDate=cyc.format('dd-MM-yyyy');
        
     dyDate=dyc.format('dd-MM-yyyy');
      
      oDate=oyc.format('dd-MM-yyyy');
       
       eyDate=eyc.format('dd-MM-yyyy');
        
     tDate=toe.format('dd-MM-yyyy');
      
      fDate=frm.format('dd-MM-yyyy');
      
     
    }

    public PageReference saveSB() {
       con.save();
       objAAF = new Application_Form__c();
       PageReference pr=null;
       String ObjectPrefix =Application_Form__c.sObjectType.getDescribe().getKeyPrefix();
       pr = new PageReference('/' + ObjectPrefix + '/o');  
       pr.setRedirect(true);
       insert objAAF;
       return pr;
       
    }
   
    
    
    public PageReference getdummyAction() {
         return null;
    }
      public static testMethod void testAccount () {
      
        Account a= new Account(Name='Test Account1');
        insert a;
        ApexPages.currentPage().getParameters().put('Id1',a.Id);
        ApexPages.StandardController controller2 = new ApexPages.StandardController(a);
        AAFControl afc1 = new AAFControl(controller2);
        Application_Form__c aaf1= new Application_Form__c(name='demoapplicationform');
        insert aaf1;
        ApexPages.currentPage().getParameters().put('Id',aaf1.Id);
        ApexPages.StandardController controller1 = new ApexPages.StandardController(aaf1);
        AAFControl afc = new AAFControl(controller1);
        
 
 
        
       }
 
 
 }

  • February 08, 2011
  • Like
  • 0

Hi,

   I created Page for custom save controller. my page apex code given below...

 

<apex:page controller="newOpportunityController11" tabStyle="Account">
<apex:form >
<apex:pageBlock title="Congratulations">
<apex:inputField value="{!Invoice.Name}"/>
<apex:inputField value="{!Invoice.Line_Item__c}"/>
<apex:inputField value="{!Invoice.Pay_by_Date__c}"/>
<apex:inputField value="{!Invoice.Total_Amount__c}"/>
<apex:inputField value="{!Invoice.Client_Name__c}"/>
<apex:inputField value="{!Invoice.Invoice_Status__c}"/>
<apex:commandButton action="{!save}" value="Save"/>
<apex:commandButton action="{!cancel}" value="Cancel"/>
</apex:pageBlock>
</apex:form>
</apex:page>
and my apex class is...
public class newOpportunityController11
 {  
Opportunity opportunity;
public Invoice__c invoice{ get; set; }
public Opportunity getOpportunity() {
//if(opportunity == null) opportunity = new Opportunity();
return opportunity;
}
public Invoice__c getinvoice() {
//if(Invoice == null) Invoice = new Invoice__c();
Id id = ApexPages.currentPage().getParameters().get('id');
invoice= [SELECT Client_Name__c,Invoice_Status__c,Line_Item__c,Pay_by_Date__c,Total_Amount__c FROM Invoice__c WHERE id = :id];
return invoice;
}
public PageReference cancel() {
PageReference opportunityPage = new ApexPages.StandardController(opportunity).view();
opportunityPage.setRedirect(true);
return opportunityPage;
}
public PageReference save() 
{
update invoice;
return null;
}
}
the above page and class was successfully save without error... and then when i run this page and enter the data then click save button the error given below error is occur...
System.NullPointerException: Attempt to de-reference a null object

 

Class.newOpportunityController11.save: line 47, column 8 External entry point
How to solve this....pls help

 

 

 

 

 

  • January 25, 2011
  • Like
  • 0

Hi All,

 

I am trying to send the values from controller to visualforce input text filed through getters and setters.But here i am getting query exception.

 

mycode is as follows:

 

<apex:page standardController="House_Bill_Of_Ladding__c" extensions="x1_validate">
 <apex:form> 
    <apex:outputLabel value="SFN Control No." /></td>       
    <apex:inputField id="sfn" value="{!House_Bill_Of_Ladding__c.SFN_Number__c}" style="width:82px">
                   </apex:inputField> </td>  
    <apex:outputLabel value="Voyage No." ></apex:outputLabel></td>    
    <apex:inputText id="voy" value="{!hblvoyage}" style="width:82px">      
                       </apex:inputText> </td>             
                        
    <apex:commandLink value="Get" />
 
 
 </apex:form>
</apex:page>

 

public class x1_validate
{
 private House_Bill_Of_Ladding__c  curr_record =new House_Bill_Of_Ladding__c();
 Sea_Foot_Note__c SFN_voyage;

 public string hblvoyage{get; set;}
 public x1_validate(ApexPages.StandardController controller)
  {
   this.curr_record=(House_Bill_Of_Ladding__c)controller.getRecord();
   string curr_sfn=curr_record.SFN_Number__c;
   SFN_voyage=[SELECT Voyage_Number__c FROM  Sea_Foot_Note__c where SFN_Number__c =: curr_sfn];     
  }
 
  public Sea_Foot_Note__c gethblvoyage()
   {   
    return SFN_voyage;
   }
   public void sethblvoyage(Sea_Foot_Note__c s)
   {
    this.SFN_voyage=s;
   }
 }

if i declared SFN_voyage return type as Sea_Foot_Note__c[] i can rectify the query exception.but again i am getting the following error.

 

Error: Compile Error: Return value must be of type: SOBJECT:chiranjeevi__Sea_Foot_Note__c at line 16 column 5

 

plz tell me is i am going in a correct way or not.i know that through setters and getters only we can pass the values from controller to visualforce.i can able to pass  string value.but here i was unable to pass object value.if any one knows other solution plz give me example or plz check my code.my requirement is if i click on link i should populate the value to input text.

 

plzz help me.

 

Thanks in advance,

Manu..

 

 

 

  • January 20, 2010
  • Like
  • 0

Hello,

 

I am trying to implement an example that uses a method called getLeadAddressByEmail,which uses SOQL to look up a lead based on an email address.  The query returns a lead object with only Street, City, State, and PostalCode.  But when I run the program, I get the following error:

 

System.QueryException: List has no rows for assignment to SObject
Class.getLeadInfo.getLeadAddressByEmail: line 4, column 10 External entry point

Source Error:

Line 105:        [return: System.Xml.Serialization.XmlElementAttribute("result", IsNullable=true)]
Line 106:        public Lead getLeadAddressByEmail([System.Xml.Serialization.XmlElementAttribute(IsNullable=true)] string LeadEmail) {
Line 107:            object[] results = this.Invoke("getLeadAddressByEmail", new object[] {
Line 108:                        LeadEmail});
Line 109:            return ((Lead)(results[0]));

  

FYI, here's my code:

 

public partial class _Default : System.Web.UI.Page

{

private string _userId = "yyyyy@zzzzzzz.com";

private string _password = "XXXXXXXXXXXXX";

private string _sessionId;

private string _serverUrl;

private string _nextLoginTime;

private string _leadEmail;

protected void Page_Load(object sender, EventArgs e)

{

 

}

protected void cmdSubmit_Click(object sender, EventArgs e)

{

//Confirm Lead Email Exists

_leadEmail = this.txtEmail.Text;

//See if Session ID exists

_sessionId = (string)(Application["_sessionId"].ToString() == null ? Application["_sessionId"] : "");

_serverUrl = (string)(Application["_serverUrl"].ToString() == null ? Application["_serverUrl"] : "");_nextLoginTime = (

string)(Application["_nextLoginTime"].ToString() == null ? Application["_nextLoginTime"] : "01/01/200000:00:00"); if ((!isConnected()))

{

getSessionInfo();

}

//Call getLeadInfo Web Service

getLeadInfoService getLeadInfo = new getLeadInfoService();

getLeadInfo.SessionHeaderValue = new getLeadInfo.SessionHeader();getLeadInfo.SessionHeaderValue.sessionId =

this._sessionId;getLeadInfo.Lead getLeadInfoResponse = default(getLeadInfo.Lead);

getLeadInfoResponse = getLeadInfo.getLeadAddressByEmail(_leadEmail);

this.txtAddress.Text = getLeadInfoResponse.Street.ToString();

this.txtCity.Text = getLeadInfoResponse.City.ToString();

this.txtState.Text = getLeadInfoResponse.State.ToString();

this.txtZip.Text = getLeadInfoResponse.PostalCode.ToString();

}

public bool isConnected()

{

bool functionReturnValue = false; if (!string.IsNullOrEmpty(_sessionId) & _sessionId != null)

{

//if (DateTime.Now.ToString() > _nextLoginTime)

 if (_nextLoginTime.CompareTo(DateTime.Now.ToString()) < 0)

{

functionReturnValue = false;

}

else

{

functionReturnValue = true;

}

}

else {functionReturnValue = false;

}

return functionReturnValue;

}

public void getSessionInfo()

{

sforce.LoginResult lr = default(sforce.LoginResult);sforce.

SforceService ss = new sforce.SforceService();

lr = ss.login(_userId, _password);

_sessionId = lr.sessionId;

Application["_sessionId"] = lr.sessionId;

_serverUrl = lr.serverUrl;

Application["_serverUrl"] = lr.serverUrl;Application["_nextLoginTime"] = DateTime.Now;

}

}

 

Web Service Code:

 

global class getLeadInfo {

    WebService static Lead getLeadAddressByEmail(string LeadEmail) {
    Lead c = [SELECT Street, City, State, PostalCode from Lead WHERE Email = :LeadEmail];
    Lead l = new Lead(Street = c.Street, City = c.City, State = c.State, PostalCode = c.PostalCode);
   
   return l;

  }
}

 

Any help would be greatly appreciated.  Thanks.

 

Monir

 

Hi ...

I don't really understand "de-reference a null object" errors and how they're caused.

Every time an Account is updated and the OwnerId value changes, I want all Contacts to get the same OwnerId as the account they're associated to.   Once I get that trigger working, I'll write the trigger on the Contact record as well.

Here is the Account trigger.  What do I change to not get "CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, accountUpdateContactOwner: execution of AfterUpdate caused by: System.NullPointerException: Attempt to de-reference a null object Trigger.accountUpdateContactOwner: line 21, column 62"


trigger accountUpdateContactOwner on Account (after update) {

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

    for (Integer i = 0; i < Trigger.new.size(); i++)
    {
        if (Trigger.old[i].OwnerId != Trigger.new[i].OwnerId ) {
            AcctIds.add(Trigger.old[i].Id);
        }
    }
   
Map<Id, Account> AcctOwners = new Map<Id, Account> ([select Id, OwnerId from Account
                 where Id in :AcctIds]);
                

    for (Contact updContacts : [select Id, OwnerId from Contact
                 where AccountId in :AcctIds])
         
    {
        updContacts.OwnerId = AcctOwners.get(updContacts.Id).OwnerId;
        update updContacts;
    }       

}


We are trying to do a trigger to calculate the amount in USD and store in a custom field in Opportunity. But I am facing the NullPointerException

Code:
trigger opptyAmountNusd on Opportunity (after update) {
//Calculates the USD equivalent and updates in another field

if (Trigger.isUpdate) {
    //for (Opportunity o_oppty : Trigger.old) {
   
    Opportunity[] opps = new List<Opportunity>();
        for (Opportunity n_oppty : Trigger.new) {
            Opportunity opp_tmp = n_oppty;
           
            if ((n_oppty.Amount != 0) ||(n_oppty.Amount != NULL) ) {
                    Decimal a = n_oppty.Amount;
                    String c = n_oppty.CurrencyIsoCode.substring(0,3);
                   
                    CurrencyType ct = [Select ConversionRate from CurrencyType where IsoCode=:c limit 1][0];
           
                    Decimal cr = ct.ConversionRate;
                   
                    opp_tmp.Amount_In_USD__c = cr*a;
                    opps.add(opp_tmp);
                   
                    //n_oppty.Amount_In_USD__c = cr*a;      
            }
        }
    //}
   
     for (Opportunity opp_tmp : opps) {
    
         update opp_tmp;
     }
}



}

Message Edited by rob_ocp on 07-10-2008 11:08 AM

Message Edited by rob_ocp on 07-10-2008 11:11 AM
I'm getting the following error on on a campaign trigger
 
Error: Invalid Data.
Review all error messages below to correct your data.
Apex trigger findParent2 caused an unexpected exception, contact your administrator: findParent2: execution of AfterUpdate caused by: System.SObjectException: SObject row was retrieved via SOQL without querying the requested field: ChildCampaigns: Trigger.findParent2: line 6, column 30
  = Required InformationCampaign Information:
 
 
trigger findParent2 on Campaign (after update) {
   ID ParentID = null;
  
   for (Campaign cam1 : [Select id, name from Campaign]){
        system.debug('Loop 1 - campaign id : ' + cam1.id);
        for (Campaign cam2 : cam1.childcampaigns){
           system.debug('Loop 2 - campaign id : ' + cam2.id);
            if (cam2.id == cam1.id){
                  ParentID = cam1.id;     
            }
       }
   }
     system.debug('Parent for  is '+ParentID);
 }
I am getting this error and I don't know what is causing it.
I am creating a Map in my Trigger that has a String and SObject values.
I think the issue is I am not setting the Country in my Map, but I am not sure how to do this.

What am I doing wrong.
Thanks for you time.

Code:
trigger hooverAddressFileds on Account bulk (before update) {

//create a string set of all the countries that are in the update file 
 Set<String> country = new Set<String>();
 for(Account accounts : Trigger.new){
  country.add(accounts.Hoover_s_Country__c);
 }

//create a Map of all the Set
 Map<String, iso_country_code__c> iso = new Map<String, iso_country_code__c>([select ISO_code__c from iso_country_code__c where Country__c in :country]);
//updating the ISO code on the billing and shipping country
 for(Account accounts : Trigger.new){
  if(accounts.Hoover_s_Country__c != null){
   accounts.billingcountry = iso.get(accounts.Hoover_s_Country__c).ISO_code__c;
   accounts.shippingcountry = iso.get(accounts.Hoover_s_Country__c).ISO_code__c; 
  }
 }
//updatting billing and shipping street with the new Hoovers address field
 for(Account accounts : Trigger.new){
  if(accounts.Hoover_s_Address_Two__c != null && accounts.Hoover_s_Address_One__c != null){
   accounts.BillingStreet = accounts.Hoover_s_Address_One__c + ' ' + accounts.Hoover_s_Address_Two__c;
   accounts.ShippingStreet = accounts.Hoover_s_Address_One__c + ' ' + accounts.Hoover_s_Address_Two__c; 
  }
 }
//nulling out the hoovers fields
 for(Account accounts : Trigger.new){
  accounts.Hoover_s_Address_One__c = null;
  accounts.Hoover_s_Address_Two__c = null;
  accounts.Hoover_s_Country__c = null;
 }
}

 

  • April 04, 2007
  • Like
  • 0