• sudhirn@merunetworks.com
  • NEWBIE
  • 465 Points
  • Member since 2013

  • Chatter
    Feed
  • 0
    Best Answers
  • 5
    Likes Received
  • 0
    Likes Given
  • 145
    Questions
  • 169
    Replies
Hi Apex Experts, 

   I need your valuable suggestion for a trgger written below Trigger update quote values based on the values that are added in quotelineitems there are few apex class called inside the trigger 

  Have written the test class but logic does not seems to be working please suggest me how to write the logic to get good code coverage.  
trigger GenQuoteApproval on QuoteLineItem (After Insert, After Update, After Delete) {

  Decimal LineMaxDiscount;
  Decimal LineMaxACV;
  Decimal SubLineMaxDiscount;
  Decimal SubLineMaxACV;
  Decimal SerLineMaxDiscount;
  Decimal SerLineMaxACV;
  Map<ID, Quote> ParentQuote = new Map<ID, Quote>();
  String SALREPID;
  String MRGID;
  String SALID;
  String CFOID;
  String Level;
  Integer GSublevel1Count;
  Integer GSublevel2Count;
  Integer GSublevel3Count;
  Integer GSublevel4Count;
  Integer GSerlevel1Count;
  Integer GSerlevel2Count;
  Integer GSerlevel3Count;
  Decimal SubscriptionTerm;
 
Try 
{
if ( Trigger.isAfter)
  {
 List<Id> listIds = new List<Id>();
 //Set<Id> listIds = new Set<Id>();

 List<Quote> QuotetList = new List<Quote>();

 /* Get Quote ID */
 for (QuoteLineItem childquoteline :  Trigger.new)
 {
        listIds.add(childquoteline.QuoteId);
    }

 ParentQuote = new Map<Id, Quote>([SELECT id,Level_1__c,Level_2__c,Level_3__c,Level_4__c FROM Quote WHERE ID IN :listIds]);


  /* Get service list of all quote id */
  list<id> serviceid = new list<id>();
  for(QuoteLineItem getserviceid : [select id  from  QuoteLineItem
                                     where quoteid in :listIds and
                                           product2.Productcode  like 'CBSVC%'] )
   {
      serviceid.add(getserviceid.id);

   }

  /* Get subscription list of all quote id */
  list<id> subscriptionid = new list<id>();
  for(QuoteLineItem getsubscriptionid : [select id  from  QuoteLineItem
                                     where quoteid in :listIds and
                                           Subscription_Terms__c <> 0] )
   {
      subscriptionid.add(getsubscriptionid.id);

   }

 /* Subscription Discount and ACV */
    List<AggregateResult> MaxSubscription = [select max(Discount_Percent__c) SubQuoteLineMaxDiscount,sum(f_ACV__c) SubQuoteLineMaxACV
                                                   from  QuoteLineItem
                                                   where quoteid in :listIds and Subscription_Terms__c <> 0 and
                                                         ID not in :serviceid
                                                 ];

  for (AggregateResult SubQuoteMaxDiscount : MaxSubscription)
  {
  SubLineMaxDiscount = (Decimal)SubQuoteMaxDiscount.get('SubQuoteLineMaxDiscount');
  SubLineMaxACV = (Decimal)SubQuoteMaxDiscount.get('SubQuoteLineMaxACV');
  }

   system.debug('Subscription Line Discount  :' + SubLineMaxDiscount);
   system.debug('Subscription Line ACV  :' + SubLineMaxACV);

   /* Service Discount and ACV */
  List<AggregateResult> MaxService = [select max(Discount_Percent__c) SerQuoteLineMaxDiscount,SUM(f_ACV__c) SerQuoteLineMaxACV
                                      from  QuoteLineItem
                                      where quoteid in :listIds and product2.Productcode  like 'CBSVC%' and
                                            id not in :subscriptionid];

  for (AggregateResult SerQuoteMaxDiscount : MaxService)
  {
  SerLineMaxDiscount = (Decimal)SerQuoteMaxDiscount.get('SerQuoteLineMaxDiscount');
  SerLineMaxACV = (Decimal)SerQuoteMaxDiscount.get('SerQuoteLineMaxACV');
  }

   system.debug('Service Line Discount  :' + SerLineMaxDiscount);
   system.debug('Service Line ACV  :' + SerLineMaxACV);

  Opportunity Opp = [select ownerid
                    from opportunity
                    where
                    id in (select OpportunityId from quote where id in :listIds) ];

  system.debug(listIds);
  
  SubscriptionTerm = ApprovalUtils.GetSubscriptionTerm(listIds);

  system.debug('Get New Subscription Term' + SubscriptionTerm);
  
  /* Get Manager ID */
  User Usr = [select managerid from user where id = :opp.ownerid];

 /* Subscription Query to get level 1..4 values */
   if ( SubscriptionTerm != null &&
        SubLineMaxACV != null &&
        SubLineMaxDiscount != null)
   {
       GSublevel1Count = ApprovalUtils.SubLevel1(SubscriptionTerm , SubLineMaxACV , SubLineMaxDiscount);

       system.debug('Subscription Level1 :' + GSublevel1Count);

       GSublevel2Count = ApprovalUtils.SubLevel2(SubscriptionTerm , SubLineMaxACV , SubLineMaxDiscount);

       system.debug('Subscription Level2 :' + GSublevel2Count);

       GSublevel3Count = ApprovalUtils.SubLevel3(SubscriptionTerm , SubLineMaxACV , SubLineMaxDiscount);

       system.debug('Subscription Level3 :' + GSublevel3Count);

       GSublevel4Count = ApprovalUtils.SubLevel4(SubscriptionTerm , SubLineMaxACV , SubLineMaxDiscount);

       system.debug('Subscription Level4 :' + GSublevel4Count);

        
   }

    /* Service Query to get level 1..4 values */
   if (SerLineMaxACV != null && SerLineMaxDiscount != null)
    {
       GSerlevel1Count = ApprovalUtils.SerLevel1(SerLineMaxACV,SerLineMaxDiscount);

       system.debug('Service Level1 :' + GSerlevel1Count);

        GSerlevel2Count = ApprovalUtils.SerLevel2(SerLineMaxACV,SerLineMaxDiscount);

       system.debug('Service Level2 :' + GSerlevel2Count);

        GSerlevel3Count = ApprovalUtils.SerLevel3(SerLineMaxACV,SerLineMaxDiscount);

       system.debug('Service Level3 :' + GSerlevel3Count);
    }    
   
   
   If( GSublevel1Count >= 1  || GSerlevel1Count >= 1  )
     {
      SALREPID = Opp.OwnerId;
      }   
     
     
    If (GSublevel2Count >= 1 || GSerlevel2Count >= 1  )
    {
      SALREPID = NULL;
      MRGID = Usr.managerid;
    }
       
    
    /* Future here you may have to change for amount > 1000000 if its going only to SVP */
   If ( GSublevel3Count >= 1 || GSerlevel3Count >= 1)
      {
      SALREPID = NULL;
      MRGID = Usr.managerid;
      SALID = '00580000007jaoA';
      }
      
    If ( GSublevel4Count >= 1 )
    {
    SALREPID = NULL;
    MRGID = Usr.managerid;
    SALID = '00580000007jaoA';
    CFOID = '00580000006HV0w';
    Level = '4sub';
    }  
  
    //system.debug('Which Level :' + Level);
    system.debug('Sales Rep :' + SALREPID);
    system.debug('Manager :' + MRGID);
    system.debug('Sales Ops :' + SALID);
    system.debug('CEO CFO :'  + CFOID);

for (QuoteLineItem gqtl : Trigger.new)
 {
   Quote MyParentQuote = ParentQuote.get(gqtl.QuoteId);

    MyParentQuote.Level_1__c = SALREPID;
    MyParentQuote.Level_2__c=MRGID;
    MyParentQuote.Level_3__c=SALID;
    MyParentQuote.Level_4__c=CFOID;
 
  }

  update ParentQuote.values();

 }
}

catch(Exception e) {
    System.debug('The following exception has occurred: ' + e.getMessage());    
}
  
}

Test Class below is the test written trigger still shows 0% code coverage please advice me how to get good coverage and logic how to write test class for above trigger 
@isTest(SeeAllData=True)

private class GenQuoteApproval_Test {

 static testMethod void GenQuote(){
 
     
 
     QuoteLineItem Qtl = [select id,quoteid from QuoteLineItem  where id = '0QL18000000HS8x'];
     
     Quote Qot = [select id,Level_1__c,Level_2__c,Level_3__c,Level_4__c,opportunityid FROM Quote WHERE ID  = :Qtl.quoteid ]; 
 
     
     Opportunity Opp = [select ownerid
                        from opportunity
                        where
                        id = :Qot.opportunityid  ];
                        
     User Usr = [select managerid from user where id = :opp.ownerid];
     
     test.startTest();
         
     
     List<quote> qList = new List <quote> ();
     
      //Iterate and collect all the end user records
      for (quote q : [select id,Level_1__c,Level_2__c,Level_3__c,Level_4__c,opportunityid FROM Quote WHERE ID  = :Qtl.id]) {
                 qList.add(new quote(Id = q.Id, 
                                    Level_1__c= opp.ownerid,
                                    Level_2__c= usr.managerid,
                                    Level_3__c= '00580000007jaoA',
                                    Level_4__c= '00580000007jaoA'));
                     }
  
  
                        update qList;
                        
                    test.stopTest();     
                        
  }      
}

Thanks
Sudhir
 
Hi Experts, 

 We have a custom object SPR__c which has submit for approval button in history section this need to be removed or disabled since we have custom button new submit for approval this will be used 

 Please suggest me how to remove this button from history section I tryed below method adding code inside new submit for apporval button but it doesn't seem to be working 
 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script> 
<script>
 $(document).ready(function() {  
      $("input[name='piSubmit']").hide();
   }); 
 </script>

Please suggest. 

Thanks
Sudhir

 
Hi, 

  Below is the formula written which has no error but this is not working when values are changed in forecast category name please suggest me what is the issue with the formula field.  
AND(
 ISCHANGED(ForecastCategoryName),
 OR(
  AND(
   PRIORVALUE(ForecastCategoryName) = 'Pipeline',
   ISPICKVAL(ForecastCategoryName,'Best Case')
  ),
  AND(
   PRIORVALUE(ForecastCategoryName) = 'Pipeline',
   ISPICKVAL(ForecastCategoryName,'Commit')
  ),
  AND(
   PRIORVALUE(ForecastCategoryName) = 'Best Case',
   ISPICKVAL(ForecastCategoryName,'Pipeline')
  ),
  AND(
   PRIORVALUE(ForecastCategoryName) = 'Commit',
   ISPICKVAL(ForecastCategoryName,'Pipeline')
  )
 )
)

Thanks
Sudhir
Hi, 

  Below is the trigger written 
trigger chatter_answers_question_escalation_to_case_trigger on Question (after update) {
    for (Question q: Trigger.new) {
        try {
            if (q.Priority == 'high' && (q.Cases == null || q.Cases.size() == 0) && Trigger.oldMap.get(q.id).Priority != 'high') {
                q = [select Id, Title, Body, CommunityId, createdById, createdBy.AccountId, createdBy.ContactId from Question where Id = :q.Id];
                Case newCase = new Case(Origin='Chatter Answers', OwnerId=q.CreatedById, QuestionId=q.Id, CommunityId=q.CommunityId, Subject=q.Title, Description = (q.Body == null? null: q.Body.stripHtmlTags()), AccountId=q.CreatedBy.AccountId, ContactId=q.CreatedBy.ContactId);
                insert newCase;
            }
        } catch (Exception e) {
            //In case you have issues with code coverage for this section, you can move this to a separate helper class method which can be tested separately
            Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
            mail.setReplyTo('no-reply@salesforce.com');
            mail.setSenderDisplayName('Salesforce Chatter Answers User');

            // The default sender is the portal user causing this trigger to run, to change this, set an organization-wide address for
            // the portal user profile, and set the ID in the following line.
            // mail.setOrgWideEmailAddressId(orgWideEmailAddressId);
            mail.setToAddresses(new String[] { Site.getAdminEmail() });
            mail.setSubject('Case Escalation exception in site ' + Site.getName());
            mail.setPlainTextBody('Case Escalation on Question having ID: ' + q.Id + ' has failed with the following message: ' + e.getMessage() + '\n\nStacktrace: ' + e.getStacktraceString());
            Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
        }
    }
}
Test class for trigger not sure what is missing it is still giving 0% code coverage. Please suggest me how to fix this issue. 
@isTest(seealldata=true)
public class  test_chatter_answers_question
{
 static testMethod void test_chatter_answers_question(){
 	
 	
 Question  q = new Question(Title='test', Body='test', CommunityId='09a800000000w1dAAA', createdById='00580000007lJUbAAM');
 
 insert q;
 
 Case newCase = new Case(Origin='Chatter Answers', OwnerId=q.CreatedById, QuestionId=q.Id, CommunityId=q.CommunityId, Subject=q.Title, Description = (q.Body == null? null: q.Body.stripHtmlTags()), AccountId=q.CreatedBy.AccountId, ContactId=q.CreatedBy.ContactId);
                
 insert newCase;
 }
}

Thanks
Sudhir
Hi, 

  Please suggest me test class for below controller it has approval process. 
public class  check_spr_coterm
{
 
 Integer Olicheck;
 Integer Athcheck;
 String PageID; 
 String P_SPR_Approver_Director;
 String P_SPR_Approver_RVP;
 String P_SPR_Approver_GVP;
 String P_SPR_Approver_EVP;  
 
 public check_spr_coterm()
 {
   SPR__c SP;
   //OpportunityLineItem OLI;
    
   SP = [select id,Opportunity__c from SPR__c 
          where Id = : ApexPages.currentPage().getParameters().get('id') limit 1];
   
   PageID = ApexPages.currentPage().getParameters().get('id');
   
  List<SPR__c> SPRO = new List<SPR__c>();

   SPRO = [select id,SPR_Approver_Director__c,SPR_Approver_RVP__c,SPR_Approver_GVP__c,SPR_Approver_EVP__c from SPR__c 
           where 
           id = :ApexPages.currentPage().getParameters().get('id') and
           ( SPR_Approver_Director__c = null or SPR_Approver_RVP__c = null or 
             SPR_Approver_GVP__c = null or SPR_Approver_EVP__c = null ) limit 1 ];
             
      if(!SPRO.isEmpty()) // check if list is not empty
        {       
       P_SPR_Approver_Director = SPRO[0].SPR_Approver_Director__c;
       P_SPR_Approver_RVP = SPRO[0].SPR_Approver_RVP__c;  
       P_SPR_Approver_GVP = SPRO[0].SPR_Approver_GVP__c;
       P_SPR_Approver_EVP = SPRO[0].SPR_Approver_EVP__c;
        }
      else
      {
        P_SPR_Approver_Director = 's';
        P_SPR_Approver_RVP =  's';  
        P_SPR_Approver_GVP =  's';
        P_SPR_Approver_EVP =  's';
       }     
     
   List<AggregateResult> OLI = [select count(id) olicnt from OpportunityLineItem 
                                where opportunityid = :SP.Opportunity__c and name like '%COTERM%' ];
    
   List<AggregateResult>  ATH = [select count(id) athcnt from  Attachment 
                                 where parentid = :ApexPages.currentPage().getParameters().get('id')];  
 
   Olicheck = (Integer)OLI[0].get('olicnt');
   Athcheck = (Integer)ATH[0].get('athcnt');  
     
 }
 public void pageAction(){
 
     if ( P_SPR_Approver_Director == NULL || P_SPR_Approver_RVP == NULL || P_SPR_Approver_GVP == NULL || P_SPR_Approver_EVP == NULL  )
     {
      ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.info,'Your SPR approvers have not been set up, please contact the SFDC Administrator @ SFDC@fortinet.com'));  
     }
 
     else if( Olicheck > 0 && Athcheck ==0) // COTERM product exist and attached is missing this will fire
     {
      ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.info,'An RTS Quote is required for the COTERM product.Please attach quote(s) and then resubmit your SPR for approval'));     
     }
     
     else if ( P_SPR_Approver_Director <> NULL && P_SPR_Approver_RVP <> NULL && P_SPR_Approver_GVP <> NULL && P_SPR_Approver_EVP <> NULL  )
     {
       Approval.ProcessSubmitRequest req = new Approval.ProcessSubmitRequest();
       req.setObjectId(PageID);
       Approval.ProcessResult result = Approval.process(req);
       ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.info,'Sucessfully submitted for approval'));
       redirectpage();
      }
     
 }
 
 
 public PageReference redirectpage()
 {
   PageReference pageRef = new PageReference('/' + PageID);
   pageRef.setRedirect(true);
   return pageRef;
 }
 
 
}

Thanks
Sudhir
 
Hi, 

  We have approvals on custom object based some conditions we are displaying message once the conditions are met approval is fired. below is the class written Need suggestion to write test class for below controller please suggest. 
 
public class  check_spr_coterm
{
 
 Integer Olicheck;
 Integer Athcheck;
 String PageID; 
 String P_SPR_Approver_Director;
 String P_SPR_Approver_RVP;
 String P_SPR_Approver_GVP;
 String P_SPR_Approver_EVP;  
 
 public check_spr_coterm()
 {
   SPR__c SP;
   //OpportunityLineItem OLI;
    
   SP = [select id,Opportunity__c from SPR__c 
          where Id = : ApexPages.currentPage().getParameters().get('id') limit 1];
   
   PageID = ApexPages.currentPage().getParameters().get('id');
   
  List<SPR__c> SPRO = new List<SPR__c>();

   SPRO = [select id,SPR_Approver_Director__c,SPR_Approver_RVP__c,SPR_Approver_GVP__c,SPR_Approver_EVP__c from SPR__c 
           where 
           id = :ApexPages.currentPage().getParameters().get('id') and
           ( SPR_Approver_Director__c = null or SPR_Approver_RVP__c = null or 
             SPR_Approver_GVP__c = null or SPR_Approver_EVP__c = null ) limit 1 ];
             
      if(!SPRO.isEmpty()) // check if list is not empty
        {       
       P_SPR_Approver_Director = SPRO[0].SPR_Approver_Director__c;
       P_SPR_Approver_RVP = SPRO[0].SPR_Approver_RVP__c;  
       P_SPR_Approver_GVP = SPRO[0].SPR_Approver_GVP__c;
       P_SPR_Approver_EVP = SPRO[0].SPR_Approver_EVP__c;
        }
      else
      {
        P_SPR_Approver_Director = 's';
        P_SPR_Approver_RVP =  's';  
        P_SPR_Approver_GVP =  's';
        P_SPR_Approver_EVP =  's';
       }     
     
   List<AggregateResult> OLI = [select count(id) olicnt from OpportunityLineItem 
                                where opportunityid = :SP.Opportunity__c and name like '%COTERM%' ];
    
   List<AggregateResult>  ATH = [select count(id) athcnt from  Attachment 
                                 where parentid = :ApexPages.currentPage().getParameters().get('id')];  
 
   Olicheck = (Integer)OLI[0].get('olicnt');
   Athcheck = (Integer)ATH[0].get('athcnt');  
     
 }
 public void pageAction(){
 
     if ( P_SPR_Approver_Director == NULL || P_SPR_Approver_RVP == NULL || P_SPR_Approver_GVP == NULL || P_SPR_Approver_EVP == NULL  )
     {
      ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.info,'Your SPR approvers have not been set up, please contact the SFDC Administrator @ SFDC@fortinet.com'));  
     }
 
     else if( Olicheck > 0 && Athcheck ==0) // COTERM product exist and attached is missing this will fire
     {
      ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.info,'An RTS Quote is required for the COTERM product.Please attach quote(s) and then resubmit your SPR for approval'));     
     }
     
     else if ( P_SPR_Approver_Director <> NULL && P_SPR_Approver_RVP <> NULL && P_SPR_Approver_GVP <> NULL && P_SPR_Approver_EVP <> NULL  )
     {
       Approval.ProcessSubmitRequest req = new Approval.ProcessSubmitRequest();
       req.setObjectId(PageID);
       Approval.ProcessResult result = Approval.process(req);
       ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.info,'Sucessfully submitted for approval'));
       redirectpage();
      }
     
 }
 
 
 public PageReference redirectpage()
 {
   PageReference pageRef = new PageReference('/' + PageID);
   pageRef.setRedirect(true);
   return pageRef;
 }
 
 
}

Visualforce code
<apex:page controller="check_spr_coterm" action="{!pageAction}">
<apex:pageMessages />
<apex:form >
        <apex:commandButton value="Ok" action="{!redirectpage}" oncomplete="abc();"/>
    </apex:form>
<script>
function abc() {
    window.location = 'https://www.google.com';
}
</script>
</apex:page>

 
Hi,

  I have writted a controller to check if attached is added or not on a custom object if not added it will show a message else submit for approval. 

  I want to redirect to same page where the user clicked the button from with page refresh I added below code but it is not working please suggest me how to modify the code. 
public class  check_spr_coterm
{
Integer count = 0;
String PageID; 
 public check_spr_coterm()
 {
   SPR__c SP;
   //OpportunityLineItem OLI;
     
   
   SP = [select id,Opportunity__c from SPR__c 
          where Id = : ApexPages.currentPage().getParameters().get('id') limit 1];
   
   PageID = ApexPages.currentPage().getParameters().get('id');
   
   List<AggregateResult> OLI = [select count(id) from OpportunityLineItem 
                                where opportunityid = :SP.Opportunity__c and name like '%COTERM%' ];
    
   List<AggregateResult>  ATH = [select count(id) athcnt from  Attachment 
                                 where parentid = :ApexPages.currentPage().getParameters().get('id')];  
   
   count = (Integer)ATH[0].get('athcnt');  
     
 }
 public void pageAction(){
     if(count ==0){
         ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.info,'You cannot submit as this record dont have attachment'));      
     }
     else
     {
        Approval.ProcessSubmitRequest req = new Approval.ProcessSubmitRequest();
        req.setObjectId(PageID);
        Approval.ProcessResult result = Approval.process(req);
        //ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.info,'Sucessfully submitted for approval'));
        redirectpage();
      }
     
 }
 
 
 public PageReference redirectpage()
 {
   PageReference pageRef = new PageReference(PageID);
   pageRef.setRedirect(true);
   return pageRef;
 }
 
 
}

Hi,

  Have written below SOQL to display all product name now i need to add filter to products only start with T has to be retrived. Please suggest me how to add this condition 
 
SELECT Name, Product2.name, Number_of_Nodes__c,UnitPrice,ListPrice,TotalPrice FROM OpportunityLineItem WHERE OpportunityId = '0063400000yU7br'

Tried adding 
Product2.name = 'T%'  but this did not work and not displaying any products

Thanks
Sudhir
Hi, 

 I wrote a below formula on stage when stage is set to 8c or 8b it cannot be changed I want to add additional condition only specific profile should be able to change the stage 

 $User.ProfileId = '00e50000000pn5v',
$User.ProfileId = '00e50000000pn5q'  

Please suggest me how to add profile condition to below formuals only they can change no one else should be able to change once this is set 
NOT(
AND(
ISCHANGED(StageName),
OR(
ISPICKVAL(StageName, "8c - Won"),
ISPICKVAL(StageName, "8b - PO Received")
)
)
)

 
Hi, 

  I have written a controller which is on a custom object is related to opportunity. My requirement is if there is a any product with name 'COTERM' is added and attachment is missing an alter message should be populated on visual force page saying approval cannot be submit since there is no attached. 

 If product is COTERM and attachment is added it must submit for approval please sugget me how to add this functionality 

Below is the controller checking the product and attached 
public class  check_spr_coterm
{
 public check_spr_coterm()
 {
   SPR__c SP;
   //OpportunityLineItem OLI;
   
   SP = [select Opportunity__c from SPR__c 
          where Id = : ApexPages.currentPage().getParameters().get('id') limit 1];
   
   List<AggregateResult> OLI = [select count(id) from OpportunityLineItem 
                                where opportunityid = :SP.Opportunity__c and name like '%COTERM%' ];
    
   List<AggregateResult>  ATH = [select count(id) from  Attachment 
                                 where parentid = :ApexPages.currentPage().getParameters().get('id')];  
   
   
 }
}


How to add the approval process and call this controll in visualforce page please suggest me.
 

<apex:page controller="check_spr_coterm">
<script>
window.alert('{!$CurrentPage.Parameters.Id}');
window.parent.opener.location.reload(true);
window.parent.close();
</script>
</apex:page>
 



Thanks

Sudhir

Hi, 

  Do we have any option to disable trigger during data loader mass update? Please suggest me if we have any options to disable. 

Thanks
Sudhir
Hi Experts, 

 Wrote two types of trigger both are working fine as expected problem is when dataloader with batch size > 1 mass update is done it is exploding with same values not sure what is the issue with the code please suggest me the soloution to fix this issue. 

Trigger 1 
trigger logosince on Account bulk (Before update) 
{
if(checkRecursive.runOnce())
{
  
   Set<Id> accountId = new Set<Id>();
   List<Id> chkoneprt = new List<Id>();
   List<Id> chkoneid = new List<Id>();
   for (Account a : Trigger.New) 
   {     
      accountId.add(a.id);
      chkoneid.add(a.id);
      chkoneprt.add(a.parentid);
      
      } 
       
  list<Account> act = [Select id, parentid from account 
                     where id in :accountId];

  list<id> actid = new list<id>();
  list<id> actparentid = new list<id>();

  //actid.clear();
  //actparentid.clear();         
              
 for( account gact : act)
{
     actid.add(gact.id);
     actparentid.add(gact.parentid);
        
}    
 //act.clear();
 
  system.debug('id  ' + actid);
  system.debug('parentid  ' + actparentid);
  system.debug(actparentid.size());
  system.debug(actparentid.isempty());
  system.debug(!actparentid.isempty());

  list<id> firstid = new list<id>(); 
  list<id> firstparentid = new list<id>();

  if ( !actparentid.isempty() )
  {
  list<Account> firstact = [Select id, parentid from account 
                       where parentid  in :actparentid and parentid != '']; 
      
   for( account gfirstact : firstact)
  {
     firstid.add(gfirstact.id);
     firstid.add(gfirstact.parentid);   
    }
  // firstact.clear();
   
   system.debug('First id  ' + firstid);    
  }

  list<id> secondid = new list<id>(); 
  list<id> secondparentid = new list<id>(); 

if ( !actparentid.isempty())
  {
  list<Account> Secondact = [Select id, parentid from account 
                       where parentid in :actid]; 
      
  for( account gfirstact : Secondact)
  {
     secondid.add(gfirstact.id);
     secondid.add(gfirstact.parentid);   
    }
   
   //Secondact.clear();
   
   system.debug('Second id  ' + secondid);
  
  }


  Try
   {
List<AggregateResult> gr = [ 
     SELECT min(closedate) from opportunity 
     WHERE (accountid in :firstid or 
            accountid in :secondid or 
            accountid in :actid)
            //AND (StageName = '1 - Closed Won' OR StageName = 'Booked') 
             ];
             
     for (AggregateResult ar : gr)  {
        system.debug('Min Opp date' + (Datetime)ar.get('expr0'));
        for(Account acts : trigger.new) 
              {
              acts.Logo_Since__c = (Datetime)ar.get('expr0') + 1; 
              }
         } 
        // gr.clear();
      
  }

  catch (System.NullPointerException e) {
    system.debug('Null Exception');
            for(Account acts : trigger.new) 
              {
                acts.Logo_Since__c = null;
                acts.SubscriptionLogoSince__c = null;
              }
  }   

  Try
   {  
List<AggregateResult> sgr = [ 
     SELECT min(closedate) from opportunity 
     WHERE (accountid in :firstid or 
            accountid in :secondid or 
            accountid in :actid)
            //AND (StageName = '1 - Closed Won' OR StageName = 'Booked') 
            //AND ACV_Subscription_Amount__c > 0 
            ];
             
     for (AggregateResult ar : sgr)  {
        system.debug('Min Opp date' + (Datetime)ar.get('expr0'));
        for(Account acts : trigger.new) 
              {
              acts.SubscriptionLogoSince__c = (Datetime)ar.get('expr0') + 1; 
              }
         }   
         //sgr.clear();
          
 }        
          
     
   catch (System.NullPointerException e) {
    system.debug('Null Exception');
            for(Account acts : trigger.new) 
              {
                acts.SubscriptionLogoSince__c = null;
              }
  } 
 }      
}

Trigger -2 
trigger newlogosince on Account bulk (before update) 
{

   
   Set<Id> accountId = new Set<Id>();
   List<Id> chkoneprt = new List<Id>();
   List<Id> chkoneid = new List<Id>();
   Map<String, Account> mact = new Map<String, Account>();

   String mactid;
   String mactparentid;
   list<id> firstid = new list<id>(); 
   list<id> firstparentid = new list<id>();
   list<id> secondid = new list<id>(); 
   list<id> secondparentid = new list<id>(); 

   for (Account a : Trigger.New) 
    {     
      accountId.add(a.id);
      chkoneid.add(a.id);
      chkoneprt.add(a.parentid);
      mact.put(a.id, a);
      system.debug('Print Map Values' + mact.put(a.id, a)); 
      } 

   for (account aa : mact.values() )
   {
     System.debug('Map Account ID ' + aa.id);  
     System.debug('Map Parent ID ' + aa.parentid); 
     mactid = aa.id; 
     mactparentid = aa.parentid; 
   }

   system.debug('mactid' + mactid);
   system.debug('mactparentid' + mactparentid);

   if ( mactparentid != null )
   {
   Map<String, Account> firstact = new Map<String, Account>(
                       [Select id, parentid from account 
                       where parentid = :mactparentid and parentid != '']); 

   for (account afirst: firstact.values())
   {
     System.debug('Map First Account ID ' + afirst.id);  
     //System.debug('Map First Parent ID ' + afirst.parentid); 
       firstid.add(afirst.id);
    }
       
   Map<String, Account> secondact = new Map<String, Account>(
                       [Select id, parentid from account 
                       where parentid = :mactid]); 
       
   for (account asecond: secondact.values())
   {
     System.debug('Map Second Account ID ' + asecond.id);  
     //System.debug('Map Second Parent ID ' + asecond.parentid);    
     secondid.add(asecond.id);  
    }
       
   }
   
Try
   {
List<AggregateResult> gr = [ 
     SELECT min(closedate) from opportunity 
     WHERE (accountid in :firstid or 
            accountid in :secondid or 
            accountid = :mactid)
            //AND (StageName = '1 - Closed Won' OR StageName = 'Booked') 
             ];
             
     for (AggregateResult ar : gr)  {
        system.debug('Min Opp date' + (Datetime)ar.get('expr0'));
        for(Account acts : Trigger.New) 
              {
              acts.Logo_Since__c = (Datetime)ar.get('expr0') + 1; 
              system.debug('logo since' + (Datetime)ar.get('expr0') + 1); 
              //update acts;    
              }
         } 
  }

  catch (System.NullPointerException e) {
    system.debug('Null Exception');
            for(Account acts : Trigger.New) 
              {
                acts.Logo_Since__c = null;
              }
  } 


Try
{  
List<AggregateResult> sgr = [ 
     SELECT min(closedate) from opportunity 
     WHERE (accountid in :firstid or 
            accountid in :secondid or 
            accountid = :mactid)
            //AND (StageName = '1 - Closed Won' OR StageName = 'Booked') 
            //AND ACV_Subscription_Amount__c > 0 
            ];
             
     for (AggregateResult ar : sgr)  {
        system.debug('Min Opp date' + (Datetime)ar.get('expr0'));
        for(Account acts : Trigger.New) 
              {
              acts.SubscriptionLogoSince__c = (Datetime)ar.get('expr0') + 1; 
              }
         }    
 }        
            
   catch (System.NullPointerException e) {
    system.debug('Null Exception');
            for(Account acts : Trigger.New) 
              {
                acts.SubscriptionLogoSince__c = null;
              }
  } 
 
}

Please suggest me how to fix this issue. 

Thanks
Sudhir
Hi, 

 I wrote a below trigger which is working perfect no issue I have issue while doing mass update using data loader when batch size is set to more than 1 trigger is updating wrongly to all the records when batch is set to 1 it is working as expected. 

  Please suggest me what is the issue in the code or do i have to add any aditional logic to handle this issue. 
trigger logosince on Account bulk (Before update) 
{
if(checkRecursive.runOnce())
{
  
   Set<Id> accountId = new Set<Id>();
   List<Id> chkoneprt = new List<Id>();
   List<Id> chkoneid = new List<Id>();
   for (Account a : Trigger.New) 
   {     
      accountId.add(a.id);
      chkoneid.add(a.id);
      chkoneprt.add(a.parentid);
      
      } 
       
  list<Account> act = [Select id, parentid from account 
                     where id in :accountId];

  list<id> actid = new list<id>();
  list<id> actparentid = new list<id>();

  actid.clear();
  actparentid.clear();         
              
 for( account gact : act)
{
     actid.add(gact.id);
     actparentid.add(gact.parentid);
        
}    

  system.debug('id  ' + actid);
  system.debug('parentid  ' + actparentid);
  system.debug(actparentid.size());
  system.debug(actparentid.isempty());
  system.debug(!actparentid.isempty());

  list<id> firstid = new list<id>(); 
  list<id> firstparentid = new list<id>();

  if ( !actparentid.isempty() )
  {
  list<Account> firstact = [Select id, parentid from account 
                       where parentid  in :actparentid and parentid != '']; 
      
   for( account gfirstact : firstact)
  {
     firstid.add(gfirstact.id);
     firstid.add(gfirstact.parentid);   
    }
   
   system.debug('First id  ' + firstid);    
  }

  list<id> secondid = new list<id>(); 
  list<id> secondparentid = new list<id>(); 

if ( !actparentid.isempty())
  {
  list<Account> Secondact = [Select id, parentid from account 
                       where parentid in :actid]; 
      
  for( account gfirstact : Secondact)
  {
     secondid.add(gfirstact.id);
     secondid.add(gfirstact.parentid);   
    }
   
   system.debug('Second id  ' + secondid);
  
  }


  Try
   {
List<AggregateResult> gr = [ 
     SELECT min(closedate) from opportunity 
     WHERE (accountid in :firstid or 
            accountid in :secondid or 
            accountid in :actid)
            AND (StageName = '1 - Closed Won' OR StageName = 'Booked') 
             ];
             
     for (AggregateResult ar : gr)  {
        system.debug('Min Opp date' + (Datetime)ar.get('expr0'));
        for(Account acts : trigger.new) 
              {
              acts.Logo_Since__c = (Datetime)ar.get('expr0') + 1; 
              }
         } 
  }

  catch (System.NullPointerException e) {
    system.debug('Null Exception');
            for(Account acts : trigger.new) 
              {
                acts.Logo_Since__c = null;
                acts.SubscriptionLogoSince__c = null;
              }
  }   

  Try
   {  
List<AggregateResult> sgr = [ 
     SELECT min(closedate) from opportunity 
     WHERE (accountid in :firstid or 
            accountid in :secondid or 
            accountid in :actid)
            AND (StageName = '1 - Closed Won' OR StageName = 'Booked') 
            AND ACV_Subscription_Amount__c > 0 ];
             
     for (AggregateResult ar : sgr)  {
        system.debug('Min Opp date' + (Datetime)ar.get('expr0'));
        for(Account acts : trigger.new) 
              {
              acts.SubscriptionLogoSince__c = (Datetime)ar.get('expr0') + 1; 
              }
         }    
 }        
          
     
   catch (System.NullPointerException e) {
    system.debug('Null Exception');
            for(Account acts : trigger.new) 
              {
                acts.SubscriptionLogoSince__c = null;
              }
  } 
 
  


  
 }      
}

 
Hi  Experts,

 Below code is working fine have no problem because of this too many queries am gettin 50001 issue when migrated to production

  Is there any alternative way to load the query count to the variable please suggest me
     
String query = 'SELECT Id, Name, OwnerId, Owner.Name, NextStep, StageName, Total_List_Price_Amount__c, ForecastCategoryName, '+
                        'CloseDate, Amount,Formula_Amount__c,(Select Id,Name,Status__c from SPR__r ORDER BY CreatedDate DESC LIMIT 1) '+
                       'FROM '+
                        'Opportunity '+
                       'WHERE '+
                        'Id != null';


  List<Id> listOppIds = new List<Id>(); 
        //List<Opportunity> CountOppRecords = Database.query(query);
        total_size = CountOppRecords.size();

Thanks
Sudhir
Hi, 

 I want to write a test class for below class Please suggest me how to write. 

http://blog.jeffdouglas.com/2011/02/15/find-my-salesforce-users-by-role-hierarchy/
 
public with sharing class RoleUtils {

  public static Set<ID> getRoleSubordinateUsers(Id userId) {

    // get requested user's role
    Id roleId = [select UserRoleId from User where Id = :userId].UserRoleId;
    // get all of the roles underneath the user
    Set<Id> allSubRoleIds = getAllSubRoleIds(new Set<ID>{roleId});
    // get all of the ids for the users in those roles
    Map<Id,User> users = new Map<Id, User>([Select Id, Name From User where 
      UserRoleId IN :allSubRoleIds]);
    // return the ids as a set so you can do what you want with them
    return users.keySet();

  }

  private static Set<ID> getAllSubRoleIds(Set<ID> roleIds) {

    Set<ID> currentRoleIds = new Set<ID>();

    // get all of the roles underneath the passed roles
    for(UserRole userRole :[select Id from UserRole where ParentRoleId 
      IN :roleIds AND ParentRoleID != null])
    currentRoleIds.add(userRole.Id);

    // go fetch some more rolls!
    if(currentRoleIds.size() > 0)
      currentRoleIds.addAll(getAllSubRoleIds(currentRoleIds));

    return currentRoleIds;

  }

}

Thanks
Sudhir
Hi,

  We have few trigger which is working as expected. during mass update it is failing if the batch size is 1 it is working as expected if it is more than 1 it is failing and not working as expected. 

 Please suggest me how to fix this issue. 

Thanks
Sudhir
Hi Experts,

   I have a requirement to add validation message on visual force page when OFFSET reach 2000 limit it shoud display message saying "OFFSET reached to 2000 limit'  Please suggest me how to add this logic in controller and visual force page.
 
   Also if OFFSET should not go beyond 2000 it must say at this limit please suggest how to add this logic. 

Thanks
Sudhir
Hi, 

 I wrote below formula to get quater of based on the date I want to dispaly even the year of the quater please suggest me how to add the year in the formula field. 
CASE(MONTH(DATEVALUE( Logo_Since__c ) ),
1, "Q1",
2, "Q1",
3, "Q1", 
4, "Q2", 
5, "Q2", 
6, "Q2",
7, "Q3",
8, "Q3",
9, "Q3",
10,"Q4",
11,"Q4",
12,"Q4",
"")

Thanks
Sudhir
Hi, 

 I have a below validaition rule that accepts only numbers I need add one more condition that it must not take 0 as a single value it can allow 10 20 30 etc as a combination values but not just as a single 0 as a value should not be allow please suggest me how to add this logic in below code.
 
function inputLimiter(e,allow) {
            var AllowableCharacters = '';

            if (allow == 'Letters'){AllowableCharacters=' ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';}
            if (allow == 'Numbers'){AllowableCharacters='1234567890';}
            if (allow == 'NameCharacters'){AllowableCharacters=' ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-.\'';}
            if (allow == 'NameCharactersAndNumbers'){AllowableCharacters='1234567890 ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-\'';}
            if (allow == 'Currency'){AllowableCharacters='1234567890.';}

            var k = document.all?parseInt(e.keyCode): parseInt(e.which);
            if (k!=13 && k!=8 && k!=0){
                if ((e.ctrlKey==false) && (e.altKey==false)) {
                return (AllowableCharacters.indexOf(String.fromCharCode(k))!=-1);
                } else {
                return true;
                }
            } else {
                return true;
            }
        }

Thanks
Sudhir
Hi, 

  I want to create a two formula fields 

  1. Based on today date which quater 
  2.  There is a custom field which is a date to know which quater the date falling 

 Please suggest me how to create these two formula fields 

Thanks
Sudhir
Hi,

  I have writted a controller to check if attached is added or not on a custom object if not added it will show a message else submit for approval. 

  I want to redirect to same page where the user clicked the button from with page refresh I added below code but it is not working please suggest me how to modify the code. 
public class  check_spr_coterm
{
Integer count = 0;
String PageID; 
 public check_spr_coterm()
 {
   SPR__c SP;
   //OpportunityLineItem OLI;
     
   
   SP = [select id,Opportunity__c from SPR__c 
          where Id = : ApexPages.currentPage().getParameters().get('id') limit 1];
   
   PageID = ApexPages.currentPage().getParameters().get('id');
   
   List<AggregateResult> OLI = [select count(id) from OpportunityLineItem 
                                where opportunityid = :SP.Opportunity__c and name like '%COTERM%' ];
    
   List<AggregateResult>  ATH = [select count(id) athcnt from  Attachment 
                                 where parentid = :ApexPages.currentPage().getParameters().get('id')];  
   
   count = (Integer)ATH[0].get('athcnt');  
     
 }
 public void pageAction(){
     if(count ==0){
         ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.info,'You cannot submit as this record dont have attachment'));      
     }
     else
     {
        Approval.ProcessSubmitRequest req = new Approval.ProcessSubmitRequest();
        req.setObjectId(PageID);
        Approval.ProcessResult result = Approval.process(req);
        //ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.info,'Sucessfully submitted for approval'));
        redirectpage();
      }
     
 }
 
 
 public PageReference redirectpage()
 {
   PageReference pageRef = new PageReference(PageID);
   pageRef.setRedirect(true);
   return pageRef;
 }
 
 
}

Hi,

   I need to add a condition on trigger where it must not fire when a lead is converted into account and opportuntiy and contact Please suggest me some condition how to add this logic inside the trigger. 

Thanks
Sudhir
Hi,

  I need a suggestion in this requirement there is a contact lookup created in opportunity page this field should be updated automatically.

  When a lead is converted in salesforce it gets converted into Account, Opportunity and Contact my requirement is to update the contact information to opportunity lookup please suggest me can i create a trigger and update will this be a good approach or there is any alternative way like workflow we to update please suggest

Thanks
Sudhir
Hi,
  
   We have two 3 roles ( Finance Approver , GHC Approver  , Program Administrator ) This can be assinged to only one user it cannot be assigned to multiple users we want to add a validation rule if this role is already assigned need to display a message in user screen please suggest me how to write this validation rule 

Thanks
Sudhir
Hi, 

  I need to prepare a report to find duplicate leads based on email id and company name please suggest me if this is possible to get. Please suggest me if there are any app to get this information.

Thanks
Sudhir
Hi, 

  Below is the trigger written 
trigger chatter_answers_question_escalation_to_case_trigger on Question (after update) {
    for (Question q: Trigger.new) {
        try {
            if (q.Priority == 'high' && (q.Cases == null || q.Cases.size() == 0) && Trigger.oldMap.get(q.id).Priority != 'high') {
                q = [select Id, Title, Body, CommunityId, createdById, createdBy.AccountId, createdBy.ContactId from Question where Id = :q.Id];
                Case newCase = new Case(Origin='Chatter Answers', OwnerId=q.CreatedById, QuestionId=q.Id, CommunityId=q.CommunityId, Subject=q.Title, Description = (q.Body == null? null: q.Body.stripHtmlTags()), AccountId=q.CreatedBy.AccountId, ContactId=q.CreatedBy.ContactId);
                insert newCase;
            }
        } catch (Exception e) {
            //In case you have issues with code coverage for this section, you can move this to a separate helper class method which can be tested separately
            Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
            mail.setReplyTo('no-reply@salesforce.com');
            mail.setSenderDisplayName('Salesforce Chatter Answers User');

            // The default sender is the portal user causing this trigger to run, to change this, set an organization-wide address for
            // the portal user profile, and set the ID in the following line.
            // mail.setOrgWideEmailAddressId(orgWideEmailAddressId);
            mail.setToAddresses(new String[] { Site.getAdminEmail() });
            mail.setSubject('Case Escalation exception in site ' + Site.getName());
            mail.setPlainTextBody('Case Escalation on Question having ID: ' + q.Id + ' has failed with the following message: ' + e.getMessage() + '\n\nStacktrace: ' + e.getStacktraceString());
            Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
        }
    }
}
Test class for trigger not sure what is missing it is still giving 0% code coverage. Please suggest me how to fix this issue. 
@isTest(seealldata=true)
public class  test_chatter_answers_question
{
 static testMethod void test_chatter_answers_question(){
 	
 	
 Question  q = new Question(Title='test', Body='test', CommunityId='09a800000000w1dAAA', createdById='00580000007lJUbAAM');
 
 insert q;
 
 Case newCase = new Case(Origin='Chatter Answers', OwnerId=q.CreatedById, QuestionId=q.Id, CommunityId=q.CommunityId, Subject=q.Title, Description = (q.Body == null? null: q.Body.stripHtmlTags()), AccountId=q.CreatedBy.AccountId, ContactId=q.CreatedBy.ContactId);
                
 insert newCase;
 }
}

Thanks
Sudhir
Hi, 

  Please suggest me test class for below controller it has approval process. 
public class  check_spr_coterm
{
 
 Integer Olicheck;
 Integer Athcheck;
 String PageID; 
 String P_SPR_Approver_Director;
 String P_SPR_Approver_RVP;
 String P_SPR_Approver_GVP;
 String P_SPR_Approver_EVP;  
 
 public check_spr_coterm()
 {
   SPR__c SP;
   //OpportunityLineItem OLI;
    
   SP = [select id,Opportunity__c from SPR__c 
          where Id = : ApexPages.currentPage().getParameters().get('id') limit 1];
   
   PageID = ApexPages.currentPage().getParameters().get('id');
   
  List<SPR__c> SPRO = new List<SPR__c>();

   SPRO = [select id,SPR_Approver_Director__c,SPR_Approver_RVP__c,SPR_Approver_GVP__c,SPR_Approver_EVP__c from SPR__c 
           where 
           id = :ApexPages.currentPage().getParameters().get('id') and
           ( SPR_Approver_Director__c = null or SPR_Approver_RVP__c = null or 
             SPR_Approver_GVP__c = null or SPR_Approver_EVP__c = null ) limit 1 ];
             
      if(!SPRO.isEmpty()) // check if list is not empty
        {       
       P_SPR_Approver_Director = SPRO[0].SPR_Approver_Director__c;
       P_SPR_Approver_RVP = SPRO[0].SPR_Approver_RVP__c;  
       P_SPR_Approver_GVP = SPRO[0].SPR_Approver_GVP__c;
       P_SPR_Approver_EVP = SPRO[0].SPR_Approver_EVP__c;
        }
      else
      {
        P_SPR_Approver_Director = 's';
        P_SPR_Approver_RVP =  's';  
        P_SPR_Approver_GVP =  's';
        P_SPR_Approver_EVP =  's';
       }     
     
   List<AggregateResult> OLI = [select count(id) olicnt from OpportunityLineItem 
                                where opportunityid = :SP.Opportunity__c and name like '%COTERM%' ];
    
   List<AggregateResult>  ATH = [select count(id) athcnt from  Attachment 
                                 where parentid = :ApexPages.currentPage().getParameters().get('id')];  
 
   Olicheck = (Integer)OLI[0].get('olicnt');
   Athcheck = (Integer)ATH[0].get('athcnt');  
     
 }
 public void pageAction(){
 
     if ( P_SPR_Approver_Director == NULL || P_SPR_Approver_RVP == NULL || P_SPR_Approver_GVP == NULL || P_SPR_Approver_EVP == NULL  )
     {
      ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.info,'Your SPR approvers have not been set up, please contact the SFDC Administrator @ SFDC@fortinet.com'));  
     }
 
     else if( Olicheck > 0 && Athcheck ==0) // COTERM product exist and attached is missing this will fire
     {
      ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.info,'An RTS Quote is required for the COTERM product.Please attach quote(s) and then resubmit your SPR for approval'));     
     }
     
     else if ( P_SPR_Approver_Director <> NULL && P_SPR_Approver_RVP <> NULL && P_SPR_Approver_GVP <> NULL && P_SPR_Approver_EVP <> NULL  )
     {
       Approval.ProcessSubmitRequest req = new Approval.ProcessSubmitRequest();
       req.setObjectId(PageID);
       Approval.ProcessResult result = Approval.process(req);
       ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.info,'Sucessfully submitted for approval'));
       redirectpage();
      }
     
 }
 
 
 public PageReference redirectpage()
 {
   PageReference pageRef = new PageReference('/' + PageID);
   pageRef.setRedirect(true);
   return pageRef;
 }
 
 
}

Thanks
Sudhir
 
Hi, 

  We have approvals on custom object based some conditions we are displaying message once the conditions are met approval is fired. below is the class written Need suggestion to write test class for below controller please suggest. 
 
public class  check_spr_coterm
{
 
 Integer Olicheck;
 Integer Athcheck;
 String PageID; 
 String P_SPR_Approver_Director;
 String P_SPR_Approver_RVP;
 String P_SPR_Approver_GVP;
 String P_SPR_Approver_EVP;  
 
 public check_spr_coterm()
 {
   SPR__c SP;
   //OpportunityLineItem OLI;
    
   SP = [select id,Opportunity__c from SPR__c 
          where Id = : ApexPages.currentPage().getParameters().get('id') limit 1];
   
   PageID = ApexPages.currentPage().getParameters().get('id');
   
  List<SPR__c> SPRO = new List<SPR__c>();

   SPRO = [select id,SPR_Approver_Director__c,SPR_Approver_RVP__c,SPR_Approver_GVP__c,SPR_Approver_EVP__c from SPR__c 
           where 
           id = :ApexPages.currentPage().getParameters().get('id') and
           ( SPR_Approver_Director__c = null or SPR_Approver_RVP__c = null or 
             SPR_Approver_GVP__c = null or SPR_Approver_EVP__c = null ) limit 1 ];
             
      if(!SPRO.isEmpty()) // check if list is not empty
        {       
       P_SPR_Approver_Director = SPRO[0].SPR_Approver_Director__c;
       P_SPR_Approver_RVP = SPRO[0].SPR_Approver_RVP__c;  
       P_SPR_Approver_GVP = SPRO[0].SPR_Approver_GVP__c;
       P_SPR_Approver_EVP = SPRO[0].SPR_Approver_EVP__c;
        }
      else
      {
        P_SPR_Approver_Director = 's';
        P_SPR_Approver_RVP =  's';  
        P_SPR_Approver_GVP =  's';
        P_SPR_Approver_EVP =  's';
       }     
     
   List<AggregateResult> OLI = [select count(id) olicnt from OpportunityLineItem 
                                where opportunityid = :SP.Opportunity__c and name like '%COTERM%' ];
    
   List<AggregateResult>  ATH = [select count(id) athcnt from  Attachment 
                                 where parentid = :ApexPages.currentPage().getParameters().get('id')];  
 
   Olicheck = (Integer)OLI[0].get('olicnt');
   Athcheck = (Integer)ATH[0].get('athcnt');  
     
 }
 public void pageAction(){
 
     if ( P_SPR_Approver_Director == NULL || P_SPR_Approver_RVP == NULL || P_SPR_Approver_GVP == NULL || P_SPR_Approver_EVP == NULL  )
     {
      ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.info,'Your SPR approvers have not been set up, please contact the SFDC Administrator @ SFDC@fortinet.com'));  
     }
 
     else if( Olicheck > 0 && Athcheck ==0) // COTERM product exist and attached is missing this will fire
     {
      ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.info,'An RTS Quote is required for the COTERM product.Please attach quote(s) and then resubmit your SPR for approval'));     
     }
     
     else if ( P_SPR_Approver_Director <> NULL && P_SPR_Approver_RVP <> NULL && P_SPR_Approver_GVP <> NULL && P_SPR_Approver_EVP <> NULL  )
     {
       Approval.ProcessSubmitRequest req = new Approval.ProcessSubmitRequest();
       req.setObjectId(PageID);
       Approval.ProcessResult result = Approval.process(req);
       ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.info,'Sucessfully submitted for approval'));
       redirectpage();
      }
     
 }
 
 
 public PageReference redirectpage()
 {
   PageReference pageRef = new PageReference('/' + PageID);
   pageRef.setRedirect(true);
   return pageRef;
 }
 
 
}

Visualforce code
<apex:page controller="check_spr_coterm" action="{!pageAction}">
<apex:pageMessages />
<apex:form >
        <apex:commandButton value="Ok" action="{!redirectpage}" oncomplete="abc();"/>
    </apex:form>
<script>
function abc() {
    window.location = 'https://www.google.com';
}
</script>
</apex:page>

 
Hi, 

 I wrote a below formula on stage when stage is set to 8c or 8b it cannot be changed I want to add additional condition only specific profile should be able to change the stage 

 $User.ProfileId = '00e50000000pn5v',
$User.ProfileId = '00e50000000pn5q'  

Please suggest me how to add profile condition to below formuals only they can change no one else should be able to change once this is set 
NOT(
AND(
ISCHANGED(StageName),
OR(
ISPICKVAL(StageName, "8c - Won"),
ISPICKVAL(StageName, "8b - PO Received")
)
)
)

 
Hi, 

  I have written a controller which is on a custom object is related to opportunity. My requirement is if there is a any product with name 'COTERM' is added and attachment is missing an alter message should be populated on visual force page saying approval cannot be submit since there is no attached. 

 If product is COTERM and attachment is added it must submit for approval please sugget me how to add this functionality 

Below is the controller checking the product and attached 
public class  check_spr_coterm
{
 public check_spr_coterm()
 {
   SPR__c SP;
   //OpportunityLineItem OLI;
   
   SP = [select Opportunity__c from SPR__c 
          where Id = : ApexPages.currentPage().getParameters().get('id') limit 1];
   
   List<AggregateResult> OLI = [select count(id) from OpportunityLineItem 
                                where opportunityid = :SP.Opportunity__c and name like '%COTERM%' ];
    
   List<AggregateResult>  ATH = [select count(id) from  Attachment 
                                 where parentid = :ApexPages.currentPage().getParameters().get('id')];  
   
   
 }
}


How to add the approval process and call this controll in visualforce page please suggest me.
 

<apex:page controller="check_spr_coterm">
<script>
window.alert('{!$CurrentPage.Parameters.Id}');
window.parent.opener.location.reload(true);
window.parent.close();
</script>
</apex:page>
 



Thanks

Sudhir

Hi, 

  Do we have any option to disable trigger during data loader mass update? Please suggest me if we have any options to disable. 

Thanks
Sudhir
Hi Experts, 

 Wrote two types of trigger both are working fine as expected problem is when dataloader with batch size > 1 mass update is done it is exploding with same values not sure what is the issue with the code please suggest me the soloution to fix this issue. 

Trigger 1 
trigger logosince on Account bulk (Before update) 
{
if(checkRecursive.runOnce())
{
  
   Set<Id> accountId = new Set<Id>();
   List<Id> chkoneprt = new List<Id>();
   List<Id> chkoneid = new List<Id>();
   for (Account a : Trigger.New) 
   {     
      accountId.add(a.id);
      chkoneid.add(a.id);
      chkoneprt.add(a.parentid);
      
      } 
       
  list<Account> act = [Select id, parentid from account 
                     where id in :accountId];

  list<id> actid = new list<id>();
  list<id> actparentid = new list<id>();

  //actid.clear();
  //actparentid.clear();         
              
 for( account gact : act)
{
     actid.add(gact.id);
     actparentid.add(gact.parentid);
        
}    
 //act.clear();
 
  system.debug('id  ' + actid);
  system.debug('parentid  ' + actparentid);
  system.debug(actparentid.size());
  system.debug(actparentid.isempty());
  system.debug(!actparentid.isempty());

  list<id> firstid = new list<id>(); 
  list<id> firstparentid = new list<id>();

  if ( !actparentid.isempty() )
  {
  list<Account> firstact = [Select id, parentid from account 
                       where parentid  in :actparentid and parentid != '']; 
      
   for( account gfirstact : firstact)
  {
     firstid.add(gfirstact.id);
     firstid.add(gfirstact.parentid);   
    }
  // firstact.clear();
   
   system.debug('First id  ' + firstid);    
  }

  list<id> secondid = new list<id>(); 
  list<id> secondparentid = new list<id>(); 

if ( !actparentid.isempty())
  {
  list<Account> Secondact = [Select id, parentid from account 
                       where parentid in :actid]; 
      
  for( account gfirstact : Secondact)
  {
     secondid.add(gfirstact.id);
     secondid.add(gfirstact.parentid);   
    }
   
   //Secondact.clear();
   
   system.debug('Second id  ' + secondid);
  
  }


  Try
   {
List<AggregateResult> gr = [ 
     SELECT min(closedate) from opportunity 
     WHERE (accountid in :firstid or 
            accountid in :secondid or 
            accountid in :actid)
            //AND (StageName = '1 - Closed Won' OR StageName = 'Booked') 
             ];
             
     for (AggregateResult ar : gr)  {
        system.debug('Min Opp date' + (Datetime)ar.get('expr0'));
        for(Account acts : trigger.new) 
              {
              acts.Logo_Since__c = (Datetime)ar.get('expr0') + 1; 
              }
         } 
        // gr.clear();
      
  }

  catch (System.NullPointerException e) {
    system.debug('Null Exception');
            for(Account acts : trigger.new) 
              {
                acts.Logo_Since__c = null;
                acts.SubscriptionLogoSince__c = null;
              }
  }   

  Try
   {  
List<AggregateResult> sgr = [ 
     SELECT min(closedate) from opportunity 
     WHERE (accountid in :firstid or 
            accountid in :secondid or 
            accountid in :actid)
            //AND (StageName = '1 - Closed Won' OR StageName = 'Booked') 
            //AND ACV_Subscription_Amount__c > 0 
            ];
             
     for (AggregateResult ar : sgr)  {
        system.debug('Min Opp date' + (Datetime)ar.get('expr0'));
        for(Account acts : trigger.new) 
              {
              acts.SubscriptionLogoSince__c = (Datetime)ar.get('expr0') + 1; 
              }
         }   
         //sgr.clear();
          
 }        
          
     
   catch (System.NullPointerException e) {
    system.debug('Null Exception');
            for(Account acts : trigger.new) 
              {
                acts.SubscriptionLogoSince__c = null;
              }
  } 
 }      
}

Trigger -2 
trigger newlogosince on Account bulk (before update) 
{

   
   Set<Id> accountId = new Set<Id>();
   List<Id> chkoneprt = new List<Id>();
   List<Id> chkoneid = new List<Id>();
   Map<String, Account> mact = new Map<String, Account>();

   String mactid;
   String mactparentid;
   list<id> firstid = new list<id>(); 
   list<id> firstparentid = new list<id>();
   list<id> secondid = new list<id>(); 
   list<id> secondparentid = new list<id>(); 

   for (Account a : Trigger.New) 
    {     
      accountId.add(a.id);
      chkoneid.add(a.id);
      chkoneprt.add(a.parentid);
      mact.put(a.id, a);
      system.debug('Print Map Values' + mact.put(a.id, a)); 
      } 

   for (account aa : mact.values() )
   {
     System.debug('Map Account ID ' + aa.id);  
     System.debug('Map Parent ID ' + aa.parentid); 
     mactid = aa.id; 
     mactparentid = aa.parentid; 
   }

   system.debug('mactid' + mactid);
   system.debug('mactparentid' + mactparentid);

   if ( mactparentid != null )
   {
   Map<String, Account> firstact = new Map<String, Account>(
                       [Select id, parentid from account 
                       where parentid = :mactparentid and parentid != '']); 

   for (account afirst: firstact.values())
   {
     System.debug('Map First Account ID ' + afirst.id);  
     //System.debug('Map First Parent ID ' + afirst.parentid); 
       firstid.add(afirst.id);
    }
       
   Map<String, Account> secondact = new Map<String, Account>(
                       [Select id, parentid from account 
                       where parentid = :mactid]); 
       
   for (account asecond: secondact.values())
   {
     System.debug('Map Second Account ID ' + asecond.id);  
     //System.debug('Map Second Parent ID ' + asecond.parentid);    
     secondid.add(asecond.id);  
    }
       
   }
   
Try
   {
List<AggregateResult> gr = [ 
     SELECT min(closedate) from opportunity 
     WHERE (accountid in :firstid or 
            accountid in :secondid or 
            accountid = :mactid)
            //AND (StageName = '1 - Closed Won' OR StageName = 'Booked') 
             ];
             
     for (AggregateResult ar : gr)  {
        system.debug('Min Opp date' + (Datetime)ar.get('expr0'));
        for(Account acts : Trigger.New) 
              {
              acts.Logo_Since__c = (Datetime)ar.get('expr0') + 1; 
              system.debug('logo since' + (Datetime)ar.get('expr0') + 1); 
              //update acts;    
              }
         } 
  }

  catch (System.NullPointerException e) {
    system.debug('Null Exception');
            for(Account acts : Trigger.New) 
              {
                acts.Logo_Since__c = null;
              }
  } 


Try
{  
List<AggregateResult> sgr = [ 
     SELECT min(closedate) from opportunity 
     WHERE (accountid in :firstid or 
            accountid in :secondid or 
            accountid = :mactid)
            //AND (StageName = '1 - Closed Won' OR StageName = 'Booked') 
            //AND ACV_Subscription_Amount__c > 0 
            ];
             
     for (AggregateResult ar : sgr)  {
        system.debug('Min Opp date' + (Datetime)ar.get('expr0'));
        for(Account acts : Trigger.New) 
              {
              acts.SubscriptionLogoSince__c = (Datetime)ar.get('expr0') + 1; 
              }
         }    
 }        
            
   catch (System.NullPointerException e) {
    system.debug('Null Exception');
            for(Account acts : Trigger.New) 
              {
                acts.SubscriptionLogoSince__c = null;
              }
  } 
 
}

Please suggest me how to fix this issue. 

Thanks
Sudhir
Hi  Experts,

 Below code is working fine have no problem because of this too many queries am gettin 50001 issue when migrated to production

  Is there any alternative way to load the query count to the variable please suggest me
     
String query = 'SELECT Id, Name, OwnerId, Owner.Name, NextStep, StageName, Total_List_Price_Amount__c, ForecastCategoryName, '+
                        'CloseDate, Amount,Formula_Amount__c,(Select Id,Name,Status__c from SPR__r ORDER BY CreatedDate DESC LIMIT 1) '+
                       'FROM '+
                        'Opportunity '+
                       'WHERE '+
                        'Id != null';


  List<Id> listOppIds = new List<Id>(); 
        //List<Opportunity> CountOppRecords = Database.query(query);
        total_size = CountOppRecords.size();

Thanks
Sudhir
Hi,

  We have few trigger which is working as expected. during mass update it is failing if the batch size is 1 it is working as expected if it is more than 1 it is failing and not working as expected. 

 Please suggest me how to fix this issue. 

Thanks
Sudhir