• Shweta_Agarwal
  • NEWBIE
  • 309 Points
  • Member since 2013
  • KVP Business Solutions


  • Chatter
    Feed
  • 10
    Best Answers
  • 0
    Likes Received
  • 2
    Likes Given
  • 1
    Questions
  • 52
    Replies
Hi Friends,

I written one apex class with different methods. now i call this apex class in one trigger. But It gives some error.

Apex class :

public with sharing class Account_Handler {
 public static void afterInsert (List<Opportunity> newList){
        List<Account> Updacc = new List<Account>();
      for(Opportunity opp : newList){
              List<Account> acc = [select id,Total_Open_Opportunities__c from Account where Id =: opp.AccountId]; 
              List<Opportunity > opportunity= [select id,AccountId,StageName from Opportunity where AccountId =:opp.AccountId AND ( StageName NOT IN ('Closed Won','Closed Lost')) ];
           for(Account a :acc )
           {
             a.Total_Open_Opportunities__c=opportunity.size();
             Updacc.add(a);
          }
      }update Updacc; 
   }
    
    public static void afterUpdate (List<Opportunity> newList){
          List<Account> Updacc = new List<Account>();
        for(Opportunity opp : newList){
              List<Account> acc = [select id,Total_Open_Opportunities__c from Account where Id =: opp.AccountId]; 
              List<Opportunity > opportunity= [select id,AccountId,StageName from Opportunity where AccountId =:opp.AccountId AND ( StageName NOT IN ('Closed Won','Closed Lost'))];
           for(Account a :acc )
           {
             a.Total_Open_Opportunities__c=opportunity.size();
             Updacc.add(a);
           }
       }update Updacc; 
    } 
    
    public static void afterDelete (List<Opportunity> oldList){
          List<Account> Updacc = new List<Account>();
        for(Opportunity opp : oldList){
              List<Account> acc = [select id,Total_Open_Opportunities__c from Account where Id =: opp.AccountId]; 
              List<Opportunity > opportunity= [select id,AccountId,StageName from Opportunity where AccountId =:opp.AccountId AND ( StageName NOT IN ('Closed Won','Closed Lost'))];
           for(Account a :acc )
           {
             a.Total_Open_Opportunities__c=opportunity.size();
             Updacc.add(a);
           }
       }update Updacc; 
    }   
}

This is Sample code. Its not a complete code. I have another methods also.

Trigger :

trigger AccountTrigger on Account (before insert, after insert, after update,after delete) {
  if (Trigger.isBefore) {
    if (Trigger.isInsert) {
      Account_Handler.beforeInsert(Trigger.new);
    }
  }

  if (Trigger.isAfter) {
    if (Trigger.isInsert) {
      Account_Handler.afterInsert(Trigger.new);
      Account_Handler.afterInsert(Trigger.new);
    }
    if (Trigger.isUpdate) {
        Account_Handler.afterUpdate(Trigger.new);
      Account_Handler.afterUpdate(Trigger.newMap, Trigger.oldMap);
      
    }
    if (Trigger.isDelete) {
      Account_Handler.afterDelete(Trigger.old);
    }
  }
}

Error :

Method does not exist or incorrect signature: Account_Handler.afterUpdate(List<Account>)

This error comes for afterUpdate & afterdelete methods.

Thanks in advance,
Shahid.
Hi,

I am getting below error on visualforce page for find query.
Please suggest the changes which I need to make in order to work with below code.

Error -- Content cannot be displayed: line 1:118 no viable alternative at character '\'


String parentIdWhereClause = parentCaseId != null ?  'AND Id <> \''+ parentCaseId +'\'': '';

string casesubjectSearch = caseSubject.replace(' ', ' OR ');

string sosl = 'FIND :casesubjectSearch IN ALL FIELDS RETURNING Case(id,CaseNumber, Subject where RecordTypeId =:recordtype '+String.escapeSingleQuotes(parentIdWhereClause)+' ORDER BY LastModifiedDate DESC) LIMIT 100';
List<List<case>> searchList = search.query(sosl);
  • April 25, 2017
  • Like
  • 0
Hi, 
  
   Added a recursive condition to a trigger to avoid too many soql error after than code coverage is 0% not at all improving please suggest me what might be the issue in the code. 

  Trigger : After recussive conidtion code coverage is 0%
trigger SyncRenwalQuote on Quote (After Insert, After Update, Before Delete) {

  Set<Id> setquoteid = new Set<id>();
  Set<string> setprodcode = new Set<string>();
  Set<id> setoppid = new Set<id>();
  String grecordtype;
  Boolean gsync = false;
  String gprioroppid;
  List<QuoteLineItem> listoli = new  List<QuoteLineItem> ();
  List< OpportunitylineItem> synlisoptln = new  List< OpportunitylineItem > ();
  List< OpportunitylineItem> nonsynlisoptln = new  List< OpportunitylineItem > ();
  Try 
  {
   If(SyncRenwalQuote_Recursive.runOnce()){
   
   if(trigger.isafter){
   
      for (Quote qt :  Trigger.new){
          setquoteid.add(qt.id);
       }
     
      list<Quote> Qt = [select IsSyncing ,opportunity.recordtype.name,opportunity.Prior_Year_Opportunity__c,
                                opportunityid
                           from Quote where id in :setquoteid and
                                opportunity.recordtype.name = 'Renewal Opportunity' and
                                opportunity.Prior_Year_Opportunity__c <> null
                              ];
 
         
        gsync = Qt[0].IsSyncing;
        gprioroppid = Qt[0].opportunity.Prior_Year_Opportunity__c;
      
       list<QuoteLineItem> qltln = [select id,quoteid,Prior_Discount__c,product2.productcode,
                                            quote.opportunityid,quote.opportunity.recordtype.name                   
                                     from QuoteLineItem where quoteid In :setquoteid]; 
                                     
                                      
         for(QuoteLineItem qtl : qltln){
            qtl.Prior_Discount__c = RenewalUtils.OppLineDisc(qtl.quote.opportunityid,qtl.quoteid,qtl.product2.productcode);
            qtl.Opportunity_Line_Item_ID__c = RenewalUtils.OppLineID(qtl.quote.opportunityid,qtl.quoteid,qtl.product2.productcode);
            listoli.add(qtl);
            setprodcode.add(qtl.product2.productcode);
            }
            
         if (!listoli.isEmpty()){
              update(listoli);
                                 
            }
                  
          
         if ( gsync == true){      
         
         // Uncheck opportunity product line in parent    
       list<OpportunityLineItem> opplstnonsyn = [select id, Renewed__c, opportunity.Prior_Year_Opportunity__c 
                                                    from OpportunityLineItem 
                                                    where opportunityid = :gprioroppid and 
                                                          product2.productcode <> :setprodcode];
                                                    
               for (OpportunitylineItem Oplnnonsync : opplstnonsyn){
                      Oplnnonsync.Renewed__c = false; 
                      nonsynlisoptln.add(Oplnnonsync);
                     }
                 
                    database.update(nonsynlisoptln);  
         
         // Check opportunity product line in parent                                                     
        list<OpportunityLineItem> opplstsyn = [select id, Renewed__c, opportunity.Prior_Year_Opportunity__c,
                                                    opportunity.syncedquoteid
                                            from OpportunityLineItem 
                                            where opportunityid = :gprioroppid and 
                                                  product2.productcode = :setprodcode];    
                                                  
               
               for (OpportunitylineItem Oplnsync : opplstsyn){
                      Oplnsync.Renewed__c = true; 
                      synlisoptln.add(Oplnsync);
                     }
                     
                  database.update(synlisoptln);   
      
          }    
        }
    }
 } 

catch(Exception e) {
    System.debug('The following exception has occurred: ' + e.getMessage());    
}
}
 Test Class
@isTest(seeAllData=true)
private class SyncRenwalQuote_test {

static testMethod void SyncRenwalQuote_test() {

 test.StartTest();
 
 If(SyncRenwalQuote_Recursive.runOnce()) return;

RecordType TY = [select id from RecordType  where DeveloperName = 'Standard_Opportunity' limit 1];
 
Account acc = new Account(Name = 'GMASJ + Sudhir + Sam');
insert acc;

//get standard pricebook
Pricebook2  standardPb = [select id, name, isActive from Pricebook2 where IsStandard = true limit 1];

Pricebook2 pbk1 = new Pricebook2 (Name='Test Pricebook Entry 1',Description='Test Pricebook Entry 1', isActive=true);
insert pbk1;

Product2 prd1 = new Product2 (Name='Test Product Entry 1',Description='Test Product Entry 1',productCode = 'ABC', isActive = true);
insert prd1;


PricebookEntry pbe1 = new PricebookEntry (Product2ID=prd1.id,Pricebook2ID=standardPb.id,UnitPrice=50, isActive=true);
insert pbe1;


Opportunity opp1 = new Opportunity (Name='Opp1',StageName='Stage 0 - Lead Handed Off',CloseDate=Date.today(),Pricebook2Id = pbe1.Pricebook2Id, AccountId = acc.id,recordtypeid = TY.ID);
insert opp1;


OpportunityLineItem lineItem1 = new OpportunityLineItem (OpportunityID=opp1.id,PriceBookEntryID=pbe1.id, quantity=4, totalprice=200);
insert lineItem1;

RecordType RTY = [select id from RecordType  where DeveloperName = 'Renewal_Opportunity' limit 1];

Opportunity opp2 = new Opportunity (Name='Opp1',StageName='Stage 0 - Lead Handed Off',CloseDate=Date.today(),
                                    Pricebook2Id = pbe1.Pricebook2Id, AccountId = acc.id,recordtypeid = RTY.ID,
                                    Prior_Year_Opportunity__c=opp1.id);
insert opp2;


Quote q= new Quote ();
            q.Name= 'Testq';
            q.OpportunityId= Opp2.id;
            q.BillingStreet= '123';
            q.BillingCity= 'City';
            q.BillingPostalCode= '12345';
            q.Pricebook2Id= pbe1.Pricebook2Id;
            
            
            insert q;
         
            
 QuoteLineItem qli = new QuoteLineItem(
            QuoteId = q.Id, 
            PricebookEntryid= pbe1.Id,
            Quantity = 1, 
            UnitPrice = 500,
            Discount_Percent__c = 10,
            Subscription_Terms__c = 1,
            Number_of_Nodes__c = 10
            );
        insert qli;
        
             
  opp2.SyncedQuoteId = q.id;
  opp2.Prior_Year_Opportunity__c=opp1.id;
  String str = RenewalUtils.OppLineDisc(opp2.id,q.id,'CGOLD');
  SyncRenwalQuote_Recursive.run = true;  
    update opp2;    
  
   test.StopTest(); 
                   
 
}
}

 Recursive class 
public Class SyncRenwalQuote_Recursive{
    public static boolean run = true;
    public static boolean runOnce(){
    if(run){
     run=false;
     return true;
    }else{
        return run;
    }
    }
}

Please suggest me to fix this issue. 

Thanks
Sudhir
 
  
  • March 23, 2017
  • Like
  • 0
Hi
I have 2 lists which I want to compare and remove duplicates and insert the values into sobject.
Here is the code its working but I want to know if I can remove atleast one For Loop using Map function.

List<Account> accList1=new List<Account>();
Account acc1=new Account();
acc1.Name='Falcon1';
Account acc2=new Account();
acc2.Name='Falcon1';
Account acc3=new Account();
acc3.Name='Falcon2';
Account acc4=new Account();
acc4.Name='Falcon3';
accList1.add(acc1);
accList1.add(acc2);
accList1.add(acc3);
accList1.add(acc4);

accList1.sort();

Set<Account> mySet1 = new Set<Account>();

mySet1.addAll(accList1); //removes duplicates from list
   
List<Account> aList2=[select ID,Name from Account Limit 50000];

Set<Account> mySet2 = new Set<Account>();

mySet2.addAll(aList2); //removes duplicates from List

Set<Account> dupSet = new Set<Account>();

for(Account a1:mySet1)
{
    for(Account a2:mySet2)
    {
        If (a1 == a2) //if there are duplicates then collect them in dupes   SET
           dupSet.add(a1);
    }
}
mySet1.removeAll(dupSet); //remove duplicates from mySet1
   
aList2.clear();
aList2.addAll(mySet1);
Database.Insert(aList2,false);

I want to know if there is an elegant way of doing the above using Map.

Thanks
pooja
 
In reference to my own roadblock, and this post:  https://developer.salesforce.com/forums/?id=906F000000099TBIAY

Unless I'm missing something, it seems as though it is not possible to utilize both a user response "confirm" call (JS) and a reRender attribute on a command button. Here is the page and controller to test what I am pointing out; perhaps I'm making an error or there is another way.

Page
<apex:page controller="JSForwardToActionCon">
    <apex:form >

    <script>
    
        var x;
    
        function AreYouSure() { 
            x = confirm("Are you sure?");
            console.log('x: ' + x);
            return x;
        }
    </script>


  <!-- Begin Default Content REMOVE THIS -->
  <h1>Congratulations</h1>
  This is your new Page: JSforwardToAction
  <!-- End Default Content REMOVE THIS -->
  
    <br/><br/>
    <apex:outputLabel id="label" value="{!TheString}" />
    <br/><br/>
    <apex:commandButton action="{!AssignTheString}" value="Test" onClick="return AreYouSure();" >
        </apex:commandButton>
    
    </apex:form>
</apex:page>
Controller
public class JSForwardToActionCon {

    public String TheString;
    public String getTheString() {
        if (TheString == null) {
            TheString = 'test';
        }
        return TheString;
    }
    
    public Boolean UserResponse {get; set;}
    public void AssignTheString() {
        system.debug('UserResponse: ' + UserResponse);
    
        if (TheString == 'Assigned')
            TheString = 'test';    
        else if (TheString == 'test')
            TheString = 'Assigned';
    }

}

Now, modify the page and add a reRender="label" attribute to the command button. The user response no longer applies to the action method call in the controller. I believe this is due to the translation that occurs when VF is translated to HTML/AJAX calls when the reRender is used (uses JS to do this) and is a platform issue. I can confirm this is happening by viewing the source of both versions and locating the syntax error that occurs in the command button's onClick attribute of the HTML.

My question is - is there another way to accomplish this same task, or is this something that needs to go in Ideas and be implemented/fixed?

 

Hi there,
I have a custom zip code field (text field) in my application and when I recently loaded a large volume of data, I the leading zero on a few hundred of the zip codes were dropped.

I have written a SOQL query that identifies all of the records that I want to fix:

SELECT Name, Physical_Address_Zip_Code__c FROM Location__c WHERE NOT Physical_Address_Zip_Code__c LIKE '_____' ORDER BY Physical_Address_Zip_Code__c
but I want to write an apex script that concatenates a leading zero to the start of all these records. Anyone know how to do this? Thanks!
Hi guys.

Looking to create an Apex trigger to fire on the Opportunity to convert a Long Text Area String to opportunityLineItems. I have a pricebook set on the opportunity already, so i think i am looking for a type of map that looks at the pricebook entry from the name and supplies a PricebookEntryID, then creating a loop of Opportunity Line Items with the entrys.

E.g. On Opportunity - Product_Names__c - Product 1, Product 2, Product 3

I can have the string seperated/formated in a number of ways, semi colon, no space etc.

Does anyone have any idea how this would look? sorry, still new with Maps.

Nick
Hi All,

I have created a custom button executing javascript on Opprtunity product related list of opportunity. This button just mass updates the checkbox (Trafficked__c) to true on selected opportunity line items of opportunity. Business users just have to select the number of line items and click the button and the checkbox will be set to TRUE. I want with the second click on the button , the ckeckbox should be set to FALSE.  Below is the javascript which sets the cjeckbos to TRUE. Kindly help.

{!REQUIRESCRIPT('/soap/ajax/28.0/connection.js')}

var opportunityRecord= {!GETRECORDIDS($ObjectType.OpportunityLineItem)};

if (opportunityRecord[0] == null) {
alert("Please select at least one product to traffic.") }
else {

var oppLineItemsIds = "";
//fetch opportunity Line items Ids
for(var rowNum in opportunityRecord){
oppLineItemsIds += "'"+ opportunityRecord[rowNum] + "',";
}

//remove last comma
oppLineItemsIds = oppLineItemsIds.slice(0, oppLineItemsIds.length - 1);

//Enclose the ids in round brackets
if(oppLineItemsIds.length > 1){
oppLineItemsIds = "(" + oppLineItemsIds + ")";
}


var result = sforce.connection.query("SELECT id,Trafficked__c FROM OpportunityLineItem WHERE ID in "+oppLineItemsIds);

var records = result.getArray("records");

for(var i=0;i<records.length;i++)
{

records[i].Trafficked__c = true;

}

var resultoli = sforce.connection.update(records);
if(resultoli[0].success=='true'){
window.location.reload(); }
}

Hi All,

        I have written a trigger on Standard Note object . Now this object has Owner Id field. Upon insert i want a map say

Map<id,string> OwnerMap , to get populated with Owner Id and Owner full name (First +Last). Can anyone please help me with this.

 

trigger abd on Note( after insert, after update){

List<id> OnwerIdList=new List<id>();

 for (Note ntvar : Trigger,.New){

 OnwerIdList.add(ntvar.ownerId);
 }

List <String> ownerFirstname=[Select FirstName from user where id in:OnwerIdList ];

List <String> ownerLastname=[Select LastName from user where id in:OnwerIdList ];

}

Hi All,

      I have Notes object looking up to a parent custom object . there are 3 fields on Notes object(A,B,C) and there is a custom field D__c on Custom object of text type, I want to write a trigger so that D__c = A+B+C (concantenation of 3 fields) , upon edit or insert of child Notes records.Please help me with the bulkified code.

 

Regards

Shrey Tyagi

How we can track more then 60 fields per object ? 
Hi Friends,

I written one apex class with different methods. now i call this apex class in one trigger. But It gives some error.

Apex class :

public with sharing class Account_Handler {
 public static void afterInsert (List<Opportunity> newList){
        List<Account> Updacc = new List<Account>();
      for(Opportunity opp : newList){
              List<Account> acc = [select id,Total_Open_Opportunities__c from Account where Id =: opp.AccountId]; 
              List<Opportunity > opportunity= [select id,AccountId,StageName from Opportunity where AccountId =:opp.AccountId AND ( StageName NOT IN ('Closed Won','Closed Lost')) ];
           for(Account a :acc )
           {
             a.Total_Open_Opportunities__c=opportunity.size();
             Updacc.add(a);
          }
      }update Updacc; 
   }
    
    public static void afterUpdate (List<Opportunity> newList){
          List<Account> Updacc = new List<Account>();
        for(Opportunity opp : newList){
              List<Account> acc = [select id,Total_Open_Opportunities__c from Account where Id =: opp.AccountId]; 
              List<Opportunity > opportunity= [select id,AccountId,StageName from Opportunity where AccountId =:opp.AccountId AND ( StageName NOT IN ('Closed Won','Closed Lost'))];
           for(Account a :acc )
           {
             a.Total_Open_Opportunities__c=opportunity.size();
             Updacc.add(a);
           }
       }update Updacc; 
    } 
    
    public static void afterDelete (List<Opportunity> oldList){
          List<Account> Updacc = new List<Account>();
        for(Opportunity opp : oldList){
              List<Account> acc = [select id,Total_Open_Opportunities__c from Account where Id =: opp.AccountId]; 
              List<Opportunity > opportunity= [select id,AccountId,StageName from Opportunity where AccountId =:opp.AccountId AND ( StageName NOT IN ('Closed Won','Closed Lost'))];
           for(Account a :acc )
           {
             a.Total_Open_Opportunities__c=opportunity.size();
             Updacc.add(a);
           }
       }update Updacc; 
    }   
}

This is Sample code. Its not a complete code. I have another methods also.

Trigger :

trigger AccountTrigger on Account (before insert, after insert, after update,after delete) {
  if (Trigger.isBefore) {
    if (Trigger.isInsert) {
      Account_Handler.beforeInsert(Trigger.new);
    }
  }

  if (Trigger.isAfter) {
    if (Trigger.isInsert) {
      Account_Handler.afterInsert(Trigger.new);
      Account_Handler.afterInsert(Trigger.new);
    }
    if (Trigger.isUpdate) {
        Account_Handler.afterUpdate(Trigger.new);
      Account_Handler.afterUpdate(Trigger.newMap, Trigger.oldMap);
      
    }
    if (Trigger.isDelete) {
      Account_Handler.afterDelete(Trigger.old);
    }
  }
}

Error :

Method does not exist or incorrect signature: Account_Handler.afterUpdate(List<Account>)

This error comes for afterUpdate & afterdelete methods.

Thanks in advance,
Shahid.
Hi Expert,

On the oppertunity page i want to hide a related list button if oppertunity stage changed.

User-added image
Hi,

I am getting below error on visualforce page for find query.
Please suggest the changes which I need to make in order to work with below code.

Error -- Content cannot be displayed: line 1:118 no viable alternative at character '\'


String parentIdWhereClause = parentCaseId != null ?  'AND Id <> \''+ parentCaseId +'\'': '';

string casesubjectSearch = caseSubject.replace(' ', ' OR ');

string sosl = 'FIND :casesubjectSearch IN ALL FIELDS RETURNING Case(id,CaseNumber, Subject where RecordTypeId =:recordtype '+String.escapeSingleQuotes(parentIdWhereClause)+' ORDER BY LastModifiedDate DESC) LIMIT 100';
List<List<case>> searchList = search.query(sosl);
  • April 25, 2017
  • Like
  • 0
I am attempting to create a TaskWhoRelation entry after a Task is created. IsAfter(IsInsert, isUpdate)

Has anyone successfully updated or inserted a TaskWhoRelation after task creation? I have all the information I need to create a Taskwhorelation but when I attempt to do so, it says that none of the fields are writeable.

Any help would be appreciated.

 
Hi,

I am hyaving a scheduler class for my batch class which i am getting the following error

Error: Compile Error: Constructor not defined: [ContractBatchTriggerHandler].<Constructor>() at line 5 column 43
 
MY SCHEDULER CLASS :

global class ContractBatchTriggerHandler_Schedular implements Schedulable {

        global void execute(SchedulableContext sc) {

        ContractBatchTriggerHandler opb = new ContractBatchTriggerHandler();
        Database.executeBatch(opb,100);
        }
}
 
MY BATCH CLASS :

global class ContractBatchTriggerHandler implements Database.Batchable<sObject> {
Set<Id> contractIdSet = new Set<Id>();

    // Constructor will take set of new Contract IDs
    global ContractBatchTriggerHandler (Set<Id> contractIdSet){
        this.contractIdSet = contractIdSet;
    }
 global Database.QueryLocator start(Database.BatchableContext bc) {
        // Query all Contract records that were in Trigger.new
        return Database.getQueryLocator([SELECT Status__c, Account__c FROM Contract__c WHERE Id IN :contractIdSet]);
    }

    // The execute method will call three methods
    global void execute(Database.BatchableContext bc, List<Contract__c> scope) {
        ContractfieldsupdateonAccount(scope);
        contractcommencementdate(scope);
        contractexpirydate(scope);
    }

help me what i am doing wrong here

thanks
I am getting the above error when running a flow to update records In an object.  The same object has a trigger that updates whenever a record is udated.  Is there a work around for this limit issue in this particular instance? I have a couple of flows that will need to update records on this object but the trigger is getting in the way.  thank you
trigger ServiceBillingsTrigger on Service_Billings__c (after delete, after insert, after update) {
 
  Map<String,Special_Services_Sched__c> spcMap = new Map<String,Special_Services_Sched__c>();
  List<Special_Services_Sched__c> spcList = new List<Special_Services_Sched__c>();

  Map<String,Account> acctMap = new Map<String,Account>();
  List<Account> acctList = new List<Account>();
  
  final Product2 prod = [Select Id, Name From Product2 Where RecordTypeId = '012A0000000IqewIAC' And Name = 'JC' LIMIT 1][0];
  final RecordType inSpecsRt = [Select Id From RecordType WHERE SobjectType='Special_Services_Sched__c' AND Name='Specs' LIMIT 1];
  
  if (trigger.isDelete)
  {
      for (Service_Billings__c s : trigger.old) 
      {
      if(s.Cleaner__c != null)
      {
        if(!acctMap.containsKey(s.Cleaner__c))
        {
          Account clnrAcct = new Account(Id=s.Cleaner__c);
          clnrAcct.Active_Service__c = [Select count() 
                          From Service_Billings__c 
                          Where Active__c=true 
                          And Cleaner__c=:s.Cleaner__c];
          AggregateResult[] groupedResults = [Select SUM(Cleaner_Price__c) 
                          From Service_Billings__c 
                          Where Active__c=true 
                          And Cleaner__c=:s.Cleaner__c];
          clnrAcct.Services_Total__c = Double.valueOf(groupedResults[0].get('expr0'));

          acctMap.put(s.Cleaner__c,clnrAcct);
        }
      }

      if(s.Customer__c != null)
      {
        if(!acctMap.containsKey(s.Customer__c))
        {
          Account custAcct = new Account(Id=s.Customer__c);
          custAcct.Active_Service__c = [Select count() 
                          From Service_Billings__c 
                          Where Active__c=true 
                          And Customer__c=:s.Customer__c];
          AggregateResult[] groupedResults = [Select SUM(Customer_Price__c) 
                          From Service_Billings__c 
                          Where Active__c=true 
                          And Customer__c=:s.Customer__c];
          custAcct.Services_Total__c = Double.valueOf(groupedResults[0].get('expr0'));

          acctMap.put(s.Customer__c,custAcct);
        }
        if(s.Active__c)
        {
          if(s.Service__c == prod.Id)
          {
            for(Special_Services_Sched__c spc : [Select Id 
                                From Special_Services_Sched__c 
                                Where Active__c=true 
                                  And RecordTypeId =:inSpecsRt.Id
                                  And Customer__c=:s.Customer__c])
            {
              if(spcMap.containsKey(spc.Id))
                spcMap.remove(spc.Id);
              spc.Service_Billing__c = s.Id;
              spcMap.put(spc.Id,spc);
            }
          }
        }
      } 
      }    
  } else {

    if(Trigger.isUpdate)
    {
      for(integer x = 0; x < trigger.old.size(); x++)
          {
            if(trigger.old[x].LastBilled__c != trigger.new[x].LastBilled__c)
            {
              // billing Cycle Ignore Request.
            } else {
              Service_Billings__c s = trigger.new[x];
          if(s.Cleaner__c != null)
          {
            if(!acctMap.containsKey(s.Cleaner__c))
            {
              Account clnrAcct = new Account(Id=s.Cleaner__c);
              clnrAcct.Active_Service__c = [Select count() 
                              From Service_Billings__c 
                              Where Active__c=true 
                              And Cleaner__c=:s.Cleaner__c];
              AggregateResult[] groupedResults = [Select SUM(Cleaner_Price__c) 
                              From Service_Billings__c 
                              Where Active__c=true 
                              And Cleaner__c=:s.Cleaner__c];
              clnrAcct.Services_Total__c = Double.valueOf(groupedResults[0].get('expr0'));
              
              acctMap.put(s.Cleaner__c,clnrAcct);
            }
          }
    
          if(s.Customer__c != null)
          {
            if(!acctMap.containsKey(s.Customer__c))
            {
              Account custAcct = new Account(Id=s.Customer__c);
              custAcct.Active_Service__c = [Select count() 
                              From Service_Billings__c 
                              Where Active__c=true 
                              And Customer__c=:s.Customer__c];
              AggregateResult[] groupedResults = [Select SUM(Customer_Price__c) 
                              From Service_Billings__c 
                              Where Active__c=true 
                              And Customer__c=:s.Customer__c];
              custAcct.Services_Total__c = Double.valueOf(groupedResults[0].get('expr0'));
              acctMap.put(s.Customer__c,custAcct);
            }    
            if(s.Active__c)
            {
              if(s.Service__c == prod.Id)
              {
                for(Special_Services_Sched__c spc : [Select Id 
                                    From Special_Services_Sched__c 
                                    Where Active__c=true 
                                      And RecordTypeId =:inSpecsRt.Id
                                      And Customer__c=:s.Customer__c])
                {
                  if(spcMap.containsKey(spc.Id))
                    spcMap.remove(spc.Id);
                  spc.Service_Billing__c = s.Id;
                  spcMap.put(spc.Id,spc);
                }
              }
            }
          } 
        }
          }
    }

    if(Trigger.isInsert)
    {    
        for (Service_Billings__c s : trigger.new) 
        {
        if(s.Cleaner__c != null)
        {
          if(!acctMap.containsKey(s.Cleaner__c))
          {
            Account clnrAcct = new Account(Id=s.Cleaner__c);
            clnrAcct.Active_Service__c = [Select count() 
                            From Service_Billings__c 
                            Where Active__c=true 
                            And Cleaner__c=:s.Cleaner__c];
  
            AggregateResult[] groupedResults = [Select SUM(Cleaner_Price__c) 
                            From Service_Billings__c 
                            Where Active__c=true 
                            And Cleaner__c=:s.Cleaner__c];
            clnrAcct.Services_Total__c = Double.valueOf(groupedResults[0].get('expr0'));

            acctMap.put(s.Cleaner__c,clnrAcct);
          }
        }
  
        if(s.Customer__c != null)
        {
          if(!acctMap.containsKey(s.Customer__c))
          {
            Account custAcct = new Account(Id=s.Customer__c);
            custAcct.Active_Service__c = [Select count() 
                            From Service_Billings__c 
                            Where Active__c=true 
                            And Customer__c=:s.Customer__c];
            AggregateResult[] groupedResults = [Select SUM(Customer_Price__c) 
                            From Service_Billings__c 
                            Where Active__c=true 
                            And Customer__c=:s.Customer__c];
            custAcct.Services_Total__c = Double.valueOf(groupedResults[0].get('expr0'));
            acctMap.put(s.Customer__c,custAcct);
          }  
          if(s.Active__c)
          {
            if(s.Service__c == prod.Id)
            {
              for(Special_Services_Sched__c spc : [Select Id 
                                  From Special_Services_Sched__c 
                                  Where Active__c=true 
                                    And RecordTypeId =:inSpecsRt.Id
                                    And Customer__c=:s.Customer__c])
              {
                if(spcMap.containsKey(spc.Id))
                  spcMap.remove(spc.Id);
                spc.Service_Billing__c = s.Id;
                spcMap.put(spc.Id,spc);
              }
            }
          }
        } 
        }
    }
    }
   
     if(!acctMap.isEmpty())
       acctList.addAll(acctMap.values());
    if(acctList.size() > 0)
      update(acctList);
      
    if(!spcMap.isEmpty())
      spcList.addAll(spcMap.values());
  if(spcList.size() > 0)
    update(spcList);
}

 
Hii In this line of code ....              if(mapOfUserAssigns.containsKey(userinfo.getUserId()) && !mapOfUserAssigns.get(cntObj.OwnerId).Authorized_States__r.isEmpty() && mapOfUserAssigns.get(cntObj.OwnerId).Authorized_States__r[0].Authorized_States__c != null && mapOfUserAssigns.get(cntObj.OwnerId).Authorized_States__r[0].Authorized_States__c.contains(cntObj.MailingStateCode)){
I am getting Null Pointer exception ,On one existing contact owner is inactive ,I am  just editing state field on contact and saving after saving i am getting nullpointer exception..!
 
Upon update of a date field on an Account, i would like all contacts that have the checkbox "Admin Contact" selected to update the same date field. 

i cannot see what i am doing wrong. i have looked up every single post and help forum i can find. documentation does not help. please dont post links, im sure ive seen it. 

tell me how i can get this to actually fire? 

Class:
public with sharing class AdminUsersAccount
{
	public void leadAlerts(List<Account> lstAcct)
	{
		sendAlertsPrivate(lstAcct);
	}

	private void sendAlertsPrivate(List<Account> lstAcct)
	{
		List<Contact> lstUpdateCon = new List<Contact>();
		map<Id, Contact> conMap = new map<Id, Contact>();
		for(Account a : lstAcct)
			conMap.put(a.Id, null);
		conMap.remove(null);
		conMap.putAll([SELECT Id, Admin_User__c, Account_Expiration__c FROM Contact WHERE Admin_User__c = true AND AccountId In : conMap.keySet()]);
		for(Account acc : lstAcct)
		{	
			if(conMap.containsKey(acc.Id))
			{
				if(acc.Approved_Date__c != null)
				{
					Date tdy = date.today();
					Date expire = acc.Approved_Date__c.addDays(365);
					boolean approved = expire >= tdy;
					lstUpdateCon.add(new Contact(Account_Expiration__c = approved?conMap.get(acc.Id).Account_Expiration__c: null));
				}
				else
				{
					lstUpdateCon.add(new Contact(Account_Expiration__c = null));
				}
			}
		}
		if(!lstUpdateCon.isEmpty())
			update lstUpdateCon;		
	}
}

 
Hi, 
  
   Added a recursive condition to a trigger to avoid too many soql error after than code coverage is 0% not at all improving please suggest me what might be the issue in the code. 

  Trigger : After recussive conidtion code coverage is 0%
trigger SyncRenwalQuote on Quote (After Insert, After Update, Before Delete) {

  Set<Id> setquoteid = new Set<id>();
  Set<string> setprodcode = new Set<string>();
  Set<id> setoppid = new Set<id>();
  String grecordtype;
  Boolean gsync = false;
  String gprioroppid;
  List<QuoteLineItem> listoli = new  List<QuoteLineItem> ();
  List< OpportunitylineItem> synlisoptln = new  List< OpportunitylineItem > ();
  List< OpportunitylineItem> nonsynlisoptln = new  List< OpportunitylineItem > ();
  Try 
  {
   If(SyncRenwalQuote_Recursive.runOnce()){
   
   if(trigger.isafter){
   
      for (Quote qt :  Trigger.new){
          setquoteid.add(qt.id);
       }
     
      list<Quote> Qt = [select IsSyncing ,opportunity.recordtype.name,opportunity.Prior_Year_Opportunity__c,
                                opportunityid
                           from Quote where id in :setquoteid and
                                opportunity.recordtype.name = 'Renewal Opportunity' and
                                opportunity.Prior_Year_Opportunity__c <> null
                              ];
 
         
        gsync = Qt[0].IsSyncing;
        gprioroppid = Qt[0].opportunity.Prior_Year_Opportunity__c;
      
       list<QuoteLineItem> qltln = [select id,quoteid,Prior_Discount__c,product2.productcode,
                                            quote.opportunityid,quote.opportunity.recordtype.name                   
                                     from QuoteLineItem where quoteid In :setquoteid]; 
                                     
                                      
         for(QuoteLineItem qtl : qltln){
            qtl.Prior_Discount__c = RenewalUtils.OppLineDisc(qtl.quote.opportunityid,qtl.quoteid,qtl.product2.productcode);
            qtl.Opportunity_Line_Item_ID__c = RenewalUtils.OppLineID(qtl.quote.opportunityid,qtl.quoteid,qtl.product2.productcode);
            listoli.add(qtl);
            setprodcode.add(qtl.product2.productcode);
            }
            
         if (!listoli.isEmpty()){
              update(listoli);
                                 
            }
                  
          
         if ( gsync == true){      
         
         // Uncheck opportunity product line in parent    
       list<OpportunityLineItem> opplstnonsyn = [select id, Renewed__c, opportunity.Prior_Year_Opportunity__c 
                                                    from OpportunityLineItem 
                                                    where opportunityid = :gprioroppid and 
                                                          product2.productcode <> :setprodcode];
                                                    
               for (OpportunitylineItem Oplnnonsync : opplstnonsyn){
                      Oplnnonsync.Renewed__c = false; 
                      nonsynlisoptln.add(Oplnnonsync);
                     }
                 
                    database.update(nonsynlisoptln);  
         
         // Check opportunity product line in parent                                                     
        list<OpportunityLineItem> opplstsyn = [select id, Renewed__c, opportunity.Prior_Year_Opportunity__c,
                                                    opportunity.syncedquoteid
                                            from OpportunityLineItem 
                                            where opportunityid = :gprioroppid and 
                                                  product2.productcode = :setprodcode];    
                                                  
               
               for (OpportunitylineItem Oplnsync : opplstsyn){
                      Oplnsync.Renewed__c = true; 
                      synlisoptln.add(Oplnsync);
                     }
                     
                  database.update(synlisoptln);   
      
          }    
        }
    }
 } 

catch(Exception e) {
    System.debug('The following exception has occurred: ' + e.getMessage());    
}
}
 Test Class
@isTest(seeAllData=true)
private class SyncRenwalQuote_test {

static testMethod void SyncRenwalQuote_test() {

 test.StartTest();
 
 If(SyncRenwalQuote_Recursive.runOnce()) return;

RecordType TY = [select id from RecordType  where DeveloperName = 'Standard_Opportunity' limit 1];
 
Account acc = new Account(Name = 'GMASJ + Sudhir + Sam');
insert acc;

//get standard pricebook
Pricebook2  standardPb = [select id, name, isActive from Pricebook2 where IsStandard = true limit 1];

Pricebook2 pbk1 = new Pricebook2 (Name='Test Pricebook Entry 1',Description='Test Pricebook Entry 1', isActive=true);
insert pbk1;

Product2 prd1 = new Product2 (Name='Test Product Entry 1',Description='Test Product Entry 1',productCode = 'ABC', isActive = true);
insert prd1;


PricebookEntry pbe1 = new PricebookEntry (Product2ID=prd1.id,Pricebook2ID=standardPb.id,UnitPrice=50, isActive=true);
insert pbe1;


Opportunity opp1 = new Opportunity (Name='Opp1',StageName='Stage 0 - Lead Handed Off',CloseDate=Date.today(),Pricebook2Id = pbe1.Pricebook2Id, AccountId = acc.id,recordtypeid = TY.ID);
insert opp1;


OpportunityLineItem lineItem1 = new OpportunityLineItem (OpportunityID=opp1.id,PriceBookEntryID=pbe1.id, quantity=4, totalprice=200);
insert lineItem1;

RecordType RTY = [select id from RecordType  where DeveloperName = 'Renewal_Opportunity' limit 1];

Opportunity opp2 = new Opportunity (Name='Opp1',StageName='Stage 0 - Lead Handed Off',CloseDate=Date.today(),
                                    Pricebook2Id = pbe1.Pricebook2Id, AccountId = acc.id,recordtypeid = RTY.ID,
                                    Prior_Year_Opportunity__c=opp1.id);
insert opp2;


Quote q= new Quote ();
            q.Name= 'Testq';
            q.OpportunityId= Opp2.id;
            q.BillingStreet= '123';
            q.BillingCity= 'City';
            q.BillingPostalCode= '12345';
            q.Pricebook2Id= pbe1.Pricebook2Id;
            
            
            insert q;
         
            
 QuoteLineItem qli = new QuoteLineItem(
            QuoteId = q.Id, 
            PricebookEntryid= pbe1.Id,
            Quantity = 1, 
            UnitPrice = 500,
            Discount_Percent__c = 10,
            Subscription_Terms__c = 1,
            Number_of_Nodes__c = 10
            );
        insert qli;
        
             
  opp2.SyncedQuoteId = q.id;
  opp2.Prior_Year_Opportunity__c=opp1.id;
  String str = RenewalUtils.OppLineDisc(opp2.id,q.id,'CGOLD');
  SyncRenwalQuote_Recursive.run = true;  
    update opp2;    
  
   test.StopTest(); 
                   
 
}
}

 Recursive class 
public Class SyncRenwalQuote_Recursive{
    public static boolean run = true;
    public static boolean runOnce(){
    if(run){
     run=false;
     return true;
    }else{
        return run;
    }
    }
}

Please suggest me to fix this issue. 

Thanks
Sudhir
 
  
  • March 23, 2017
  • Like
  • 0
hai i tryed to this, it doesn't populate the field values
https://ap2.salesforce.com/{!Opportunity.Id}/e?clone=1&retURL=%2F{!Opportunity.Id}&{!Opportunity.parent__c}="{!Opportunity.Account}"
I want to use disabled and html-data-toggle attributes in commandcommand, ​first i want to show error messages if no errors show modal popup

Following is not working.How can i achieve this?
<apex:commandbutton    value="Save"  rerender="frmLead" status="status" disabled="{!hasError==true}"   html-data-toggle="modal" html-data-target="#userEConsent"  ></apex:commandbutton>
This is the controller class:

public class MYAPEX_Acc
{
    public static void createcon(List<Account> lstaccforcon)
    {
        List<Contact> lstcon = new List<Contact>();
        for(Account acc : lstaccforcon)
        {
        Contact newcon = new Contact();
        newcon.AccountId = acc.Id;
        newcon.FirstName = acc.Name;
        newcon.Description = acc.Description;
        newcon.Phone = acc.Phone;
        newcon.Email = acc.Email__c;
        lstcon.add(newcon);        
        }
        try{
        INSERT lstcon;
        }
        catch(exception e)
        {
        }
    }
}


This is the trigger :

trigger AishuAccount on Account (before insert,before update,after insert,after update) 
{
    List<Account> lstacc = new List<Account>();
    List<Account> lstaccforcon = new List<Account>();
    List<Contact> lstcon = new List<Contact>();

    If(Trigger.isAfter)
        {
        If(Trigger.isInsert)
        {
      
        for(Account acc : Trigger.new)
        {
        If(acc.Phone != NULL && acc.Name != NULL)
        lstaccforcon.add(acc);
        }
        }
       
        If(lstaccforcon.size() > 0)
        {
        MYAPEX_Acc.createcon(lstaccforcon);
        }
    }
    
}


I'm unable to create a contact with this code. please help
Hi All,

I'm getting this error message when creating a VF page.

Error: Syntax error.  Found 'Opportunity.'

And below is my code.

<apex:page standardController="Opportunity">
    <apex:pageBlock title="Opportunity Details">
    <apex:pageBlockSection>
        
    <apex:outputField value="{!Opportunity. Name}"/>
    <apex:outputField value="{!Opportunity. Amount}"/>
    <apex:outputField value="{!Opportunity. Close Date}"/>
    <apex:outputField value="{!Opportunity. Account Name}"/>   
        
    </apex:pageBlockSection>
</apex:pageBlock>
</apex:page>

Kindly help.

Thank you!
Hey all,
I have a trigger something like this:

trigger ClaimData on Intake__c (after update) {

 Profile p = [ SELECT Name FROM Profile WHERE Id =: UserInfo.getProfileId() ];
if (p.Name != 'Data Manager') {
        List<Claim__c> claims = new List<Claim__c>();
        List<Id> intakeIds = new List<Id>();
        List<Claim__c> claimsToUpdate = new List<Claim__c>();
        for (Intake__c i : Trigger.new){
                intakeIds.add(i.Id);
        }
            
        claims = [SELECT fld1,fld2,fld3....,fldn from claim__c where intake__c IN: intakeIds];
        
        List<recordType> recordTypes = [select id,name from recordType where SobjectType ='claim__c' And name in ('WC','AL','PROP','GL','MR')];     
        Map<String,recordType> mapRecordTypes = new Map<String,recordType>();
        Map<Id, List<Claim__c>> claimMap= new Map<Id, List<Claim__c>>();
        
        for (recordType r: recordTypes) {
            mapRecordTypes.put(r.DeveloperName, r);
        }
        
        for (Claim__c c: claims) {
            List<Claim__c> int2Clms = claimMap.get(c.intake__c);
            if(int2Clms == null){
                claimMap.put(c.intake__c,int2Clms = new List<Claim__c>());
            }
            int2Clms.add(c);
        }
        
        for(Intake__c i : Trigger.new){
   List<Claim__c > claimsList = claimMap.get(i.Id);
                //1
                 for(Claim__c c:claimsList){
               c.fld1='value1';
        c.fld2='value2';
                 .
         .
         .    
         .        
         .
   }
}
}
}

Since this is an after update trigger and I am updating records with an external dml,it might lead to recurssion.Can anyone
please tell me how to avoid recursion in my trigger.Any help would be greatly appreciated.
Thanks!!
Hi guys.

Looking to create an Apex trigger to fire on the Opportunity to convert a Long Text Area String to opportunityLineItems. I have a pricebook set on the opportunity already, so i think i am looking for a type of map that looks at the pricebook entry from the name and supplies a PricebookEntryID, then creating a loop of Opportunity Line Items with the entrys.

E.g. On Opportunity - Product_Names__c - Product 1, Product 2, Product 3

I can have the string seperated/formated in a number of ways, semi colon, no space etc.

Does anyone have any idea how this would look? sorry, still new with Maps.

Nick
Hi. I am getting more and more strong by reading forums and practising. Here I have a problem. I have two objects one is Department and another one is Medical_Equipment. Department object is Master for Medical_Equipment. Medical_Equipment has Amount__c field. Am rendering page by pdf format. In controller, I want to calculate total amount for items(medical equipment)

Here is my controller.
public class Medical_Equipment_ControllerCls {

    public decimal totalAmount {get;set;}
    public decimal temp = 0;
    set<id> getid = new set<id>();
    public Medical_Equipment_ControllerCls(ApexPages.StandardController controller)
    {       
        Medical_Equipment__c med = new Medical_Equipment__c();
        for(Medical_Equipment__c medical : [select name, Amount__c,Equipment_for_Department__c from Medical_Equipment__c])
        {
            getid.add(medical.Equipment_for_Department__c);  
            
        }
        List<Medical_Equipment__c> lstmedical = [select Amount__c from Medical_Equipment__c where id in : getid and Amount__c !=null];
        for(Medical_Equipment__c medicalequp : lstmedical)
           {
                temp = temp + medicalequp.Amount__c;  
                totalAmount = temp;
           }
        
    }
}

It is showing nothing for Total Amount
User-added image

I think the problem on getting Departmennt id for particular medical equipment(parent id -> child)
Any discussion and ans is welcome !!!

When someone takes the time/effort to repspond to your question, you should take the time/effort to either mark the question as "Solved", or post a Follow-Up with addtional information.  

 

That way people with a similar question can find the Solution without having to re-post the same question again and again. And the people who reply to your post know that the issue has been resolved and they can stop working on it.