• Raj R.
  • SMARTIE
  • 780 Points
  • Member since 2012

  • Chatter
    Feed
  • 2
    Best Answers
  • 3
    Likes Received
  • 1
    Likes Given
  • 76
    Questions
  • 101
    Replies
Hi,

I wrote a trigger to update the Project Item from Project (Parent to Child update.)

For the same, I wrote a test class also. I covered all the things in test class even though my code coverage is 50% only.

Kindly let me know where am doing the mistake.


Trigger:

trigger OI_Update_ProjItem_Status on Project__c (after update) {
    
    set<id>setprojid = new set<id>();
    list<Sale_Products__c>lstsp = new list<Sale_Products__c>();
    list<Project_Item__c>lstpi = new list<Project_Item__c>();
    
    for(Project__c proj : Trigger.New){
        if((proj.Nature_of_Case__c == 'Project Complete / Delivered - Payment Due' || proj.Nature_of_Case__c == 'Project Completed - Payment Recieved') && (proj.Project_Type__c.Contains('Indoor')
            || proj.Project_Type__c.Contains('Furniture'))){
             setprojid.add(proj.id);
        }
            
    }
    if(setprojid.size() > 0){
     
        for(Project_Item__c pi : [SELECT id, Status__c FROM Project_Item__c WHERE Project__c IN :setprojid]){
            pi.Status__c = 'Delivered';
            lstpi.add(pi);
        } 
           
        for(Sale_Products__c sp : [SELECT id, Status__c , Work_Order__c FROM Sale_Products__c WHERE Work_Order__c IN : setprojid]){
            sp.Status__c = 'Delivered';
            lstsp.add(sp);
        } 
   } 
   if(lstpi.size() > 0){
       update lstpi;
   } 
   if(lstsp.size() > 0){
       update lstsp;
   }            
}

Test Class:

@isTest(seealldata=true)
Public class TestWorkorder{
    static testMethod void TestWorkorder(){
    
       Test.startTest();  
        
        
        
        
             Profile p = [SELECT Id FROM Profile WHERE Name='Standard User'];
             
            User u = new User(Alias = 'Test', Email='Test@testorg.com', 
            EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US', 
            LocaleSidKey='en_US', ProfileId = p.Id, 
            TimeZoneSidKey='America/Los_Angeles', UserName='xyz@gmail.com');
            
            insert u;
            
            
        
       Pricebook2 pb = new Pricebook2(Name = 'Standard Price Book 2009', Description = 'Price Book 2009 Products', IsActive = true );
      insert pb;
    
    
        Product2 prod = new Product2(Name = 'SLA: Bronze', IsActive = true);
        insert prod;
    
    
// First insert a price for the standard price book

            Pricebook2 standardPB = [select id from Pricebook2 where isStandard=true];
            
            PricebookEntry standardPBE = new PricebookEntry(Pricebook2Id = standardPB.Id, Product2Id = prod.Id, UnitPrice = 1000, IsActive = true);
                insert standardPBE;
                
            PricebookEntry pbe = new PricebookEntry(Pricebook2Id = pb.Id, Product2Id = prod.Id, UnitPrice = 1000, IsActive = true);
                insert pbe;
        
        Account a = new Account(Name = 'ApprovalTest' ,Lock_record__C=FALSE ,ownerid=u.ID);
        insert a; 
       
        
        
        Opportunity opp =New Opportunity(Name='Test', accountId = a.id, StageName='Closed Won',CloseDate=Date.newInstance(2018, 04, 30));
        insert Opp; 
        
       
            
             Contact con = new COntact();
            con.email='test@fmail.co';
            con.ACCOUNTID=a.ID;
            con.ownerid=a.ownerid;
            con.lastname='test' ;
            
            insert con;
                         
            
        
       
           
            
        
        Opp.Pricebook2Id = pb.id;
        update Opp;
        
        OpportunityLineItem OL = new OpportunityLineItem(opportunityid=Opp.id, Quantity=1, unitprice=8000,  
            pricebookentryid=pbe.id);
        insert OL;  
            
        Quote Q = new Quote();
        Q.Name = 'QuoteOrbit';
        Q.OpportunityId = Opp.id; 
        Q.Quote_Count__c = 00000000;
        Q.Approved__c = true;
        Q.Quote_Number__c ='000000';
        Q.Quotation_Date__c = date.newinstance(2013,3,5);
        Q.Pricebook2Id = pb .id;
        
        insert Q;
        
        Quotelineitem QL = new Quotelineitem(quoteId=Q.id, Quantity =1, Unitprice=8000,pricebookentryid=pbe.id);
        insert QL; 
        
        Opp.SyncedQuoteId = Q.id;
        update Opp;
        
        
         
        Project__c Proj = new Project__c(name='OrbitProj', Opportunity__c = Opp.id, Quote__c = Q.id, Project_Type__c = 'New PE', Date_of_Installation__c = date.newinstance(2013,4,5),
            Nature_of_Case__c ='No Adv, Dspch & Erection Pending',Contact__C=con.ID,Customer_Name__c=a.id,Special_Instructions__c ='Test for Work order Pdf to be generated');    
            
        insert Proj;  
        
        Proj .Nature_of_Case__c = 'Project Completed - Payment Recieved';
        Proj .Nature_of_Case__c ='Project Complete / Delivered - Payment Due';
        Proj .Despatch_Date__c=Date.newInstance(2018, 04, 30);
        Proj .Delivery_Date__c=Date.newInstance(2018, 04, 30);
        
         update Proj ;
        
        
        
       
                
       
        
       
                
        Project_Item__c pi = new Project_Item__c(Project__c = Proj .id,Status__c = 'Pending',Product__c = prod.id,
                                 Technician_Member__c = 'suren; lakshmanan');
        insert pi;
        
        Project_Item__c pitm=[select ID, Status__c  from Project_Item__c  where ID=:Pi.ID];
        
        
        
        pitm.Status__c = 'Delivered' ;      
        
        update pitm;    
       
                
     
         
        
        Product_Inventory__c PInv=new Product_Inventory__c  (Product__c=prod.id);
        insert PInv;
        
        
     
        
        Sale_Products__c sp = new Sale_Products__c  (Status__c ='pending' ,Work_Order__c=Proj .id,Product_Inventory__c=PInv.ID,Quantity__c=1);
        insert sp ;
        
        Sale_Products__c Spr= [select Status__c  from Sale_Products__c  where ID=:Sp.id];
        
        Spr.Status__c ='Delivered';    
        
        update Spr;
        
       
        
         Test.stopTest();
 
        
    }
    
}

 
How can i update a check box in all parent account above the hierarchy from the child account check box?

Hi, I have the following schedulable class below and i wanted to be able to schedule it to run at 12am through the UI by navigating to schedule apex and then setting it to run every day at 12am. However, after this job has ran, i want it to schedule a subsequent job (same class) to run in the next hour. Is this possible?

The goal is to only schedule it through the UI to run at 12 Am and then it will automatically schedule the remaining jobs 1 hour later.
 

global class SampleClass implements Schedulable{
    global void execute(SchedulableContext alistContext) {
        Database.executeBatch('myBatchClass', 100);

       //when database executebatch is done, I want to schedule the same job 1 hour later
       String cron_exp = '0 0 1 * * ?';
       String jobName = 'somename';
       System.Schedule(jobName, cron_exp, new SampleClass())
    }
}
Hi,

I have an optimization and batch apex question. We will have to make HTTP callout from a batch class and the query that we will be passing in is below. In terms what is better for optimization and what would be easier, would the following be recommended? Is there another way to do this?
 
//query

String query = 'Select Name, Id, OwnerId From Account Where ID IN: (Select AccountId From AccountHistory)';
 
//batch class
SendAccounts sender = new SendAccounts(query)
Database.executeBatch(sender);


//batch class definition
global class SendAccounts implements Database.Batchable<sObject>, Database.AllowCallouts{

   global final String Query;

   global SendAccounts (String qry){

      Query=qry; 
   }

   global Database.QueryLocator start(Database.BatchableContext BC){
      return Database.getQueryLocator(query);
   }

   global void execute(Database.BatchableContext BC, List<sObject> scope){
     //perform logic

     //make 1 http callout
    }

   global void finish(Database.BatchableContext BC){
   }
}

 
Hi,

We have a need to keep sending HttpRequests to a particular endpoint until the server responds with a particular status code or if the endpoint is not available at all. We were thinking we can complish this by either doing a for loop or a do-while loop. When we make the HttpRequest we wanted to ensure that is done in a try-catch statement so that we can capture any callout exceptions appropriately. 

Would it be advisable to do a try-catch in a for or do-while loop? I have yet to see any performance degradations but just wanted to be sure. 

For loop example
//for loop
for() {
       try {
             HttpRequest request = new HttpRequest();
             //build request by setting headers
             HttpResponse response = http.send(request);
       catch(CallOutException callOutEx) {
            //handle exception
       }
}//end for

Do-while example:
do{
       try {
             HttpRequest request = new HttpRequest();
             //build request by setting headers
             HttpResponse response = http.send(request);
       catch(CallOutException callOutEx) {
            //handle exception
       }
}while(response.getStatusCode() == 200);

 
Hi,

We have a need to call a queueable apex class from a trigger after insert. Would it be possible to do the following below as we need to also do chaining? We need to perform updates to different objects in consecutive order so wanted to use a queue. 
trigger SomeTrigger on CustomObject__c (after insert) {
       System.enqueuejob(new  QueueClass1(Trigger.new))
}

public class QueueClass1 implements Queueable {
              private List<CustomOBject__c> objs;
              
              public QueueClass1(List<CustomObject> recs) {
                            this.objs = recs;
              }
              
               public void execute(QueueableContext queCont) {
                            //execute some logic on objs list
                            //perform update

                          //call second queueable apex job
                         System.enqueueJob(new QueueClass2(recs));
               }

}

public class QueueClass2 implements Queueable {
              private List<CustomOBject__c> objs;
              
              public QueueClass2(List<CustomObject> recs) {
                            this.objs = recs;
              }
              
               public void execute(QueueableContext queCont) {
                            //execute other logic on objs list
                            //create records for another objects
                            List<Account> acnts; //acnts list is populated based on logic executed in the "other logic"
                             insert acnts;
               }

}

 
  • April 03, 2017
  • Like
  • 0
Hi,

We have a need to schedule a batch that will perform some action if the user has not logged in in the last 24hours. On the User object, there is a LastLoginDate field which is a DateTime field. 

I want to write a SOQL query that will filter out (not select) users who have logged in with last 24hours. I am having difficulty understanding the correct syntex and need help determining what would be the best approach. What would be the recommended way to do this?
 
/*
 *i tried this but it was giving very weird response.
  *if today = 3/30/2017, when i do the following below i see that in the debug statements that it pulling users with a lastlogindate of 2017-03-30T07:XX:XX values
 * if i print DateTime.Now() i am getting a result of 2017-03-31T01:05:53 (if i were to run it on 3/30/2017 6:05pm PT
  */
List<User> usrs = [Select Id, LastLoginDate, IsActive, Name 
                                  From User
                                  Where LastLoginDate = TODAY];

The goal is to get the set of records where all user.lastlogindate >= 3/29/2017T18:05:53 and user.LastLoginDate <=3/30/2017T18:05:53 (basically within the last 24hours when the logic is ran). Any thoughts?
  • March 31, 2017
  • Like
  • 0
Hi,

We had an apex class that originally worked on Salesforce classic. Now we have added "@AuraEnabled" so that it can work with lightning. However we are finding that the apex class is no longer being called as expected while in classic.

Is it possible to write one apex class (with 1 method) to work on both classic and lightning? I would prefer not to write the same method twice, one for classic and one for lightning.
  • January 17, 2017
  • Like
  • 0
Hi,

We have a custom metadata type (CustomMetadata__mdt). When a record of CustomMetatdata__mdt is inserted we want to call a trigger that will append extra characters to the end of the field's values. 

How would we create a trigger that will run whenever a new record is inserted for CustomMetadata__mdt?
  • January 17, 2017
  • Like
  • 0
Hi,

FOr now we have hardcoded credentials that are used to connect to an external endpoint. We have to generate a customized body in json so we are unable to use named credentials and any other out of box way so we had to create an apex class. However we are storing the values in the code.

What is the recommended way to store and retrieve the credentials so that they are in a secure location outside of the apex code?
  • January 13, 2017
  • Like
  • 0
Hi,

We have a need to create a button that on click will take the current Opportunity data (some fields) and pass it into the apex class (that is a future callout) so it can execute the logic in the class. 

How would i do this?
 
//class that does future callout to some endpoint

class Sample {

            @future(callout=true)
             public sendCallOut() {
                       //some action using the current opportunity
                      HttpRequest req = new HttpRequest();
                      //add the appropriate headers
                      ///put opportunity data in the body of request

                     HTTPResponse resp = new HTTPResponse();
                     //send and process request
             }//end sendCallOut()
}//end Sample

 
  • January 12, 2017
  • Like
  • 0
Hi,

We have a need to post data from Salesforce on click of a button to AWS. We have created a class that will do this but we are finding that we are getting the following error message below. ANy thoughts as to what the appropriate way would be to get the signature?

"The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method. Consult the service documentation for details.
  • January 05, 2017
  • Like
  • 0
Hi,

I have a batch class that is supposed to update the user objet and a custom object called "cobj1". 

When the two separate update calls are made, i am getting MIXED_DML_OPERATION" DML operation on setup is not permitted after you have updated a non-setup object. What is the recommended way to update two objects in one batch class?

Sample code:
global class batchJob implements Database.Batchable<sObject>{

   global final String Query;

   global batchJob(String q,){

      Query=q; 
   }

   global Database.QueryLocator start(Database.BatchableContext BC){
      return Database.getQueryLocator(query);
   }

   global void execute(Database.BatchableContext BC, List<sObject> scope){
      List<cobj1> cobjs = new List<cobj1>();
      List<ID> usrIds = new LIst<Id>();
      //get list from scope
       for(sObject sob : scope){
          cobj1 cb = (cobj1)sob;
          //update some field on cb
          //store user's created by id
           usrIds.add(cb.CreatedBy);
          cobjs.add(cb);
     }
      update cobjs;

      List<User> users = [Select Id, Name from user where Id IN: usrIds];
      for(User u : users) {
        //perform some field update
        u.CustomField = <some new value>
      }
       update users;
    }

   global void finish(Database.BatchableContext BC){
   }
}

 
  • December 11, 2016
  • Like
  • 0
Hi,

We have to create a lightning page that has a set of checkboxes that a user is allowed to set to true or false. There is also a button that based on the checkboxes that are selected, it will perform some action through an apex classes. A sample scenario is below. What is the recommended way to accomplish this as i am trying to optimize and keep things simple?

Example scenario (assume 20 checkboxes exists)
  1. checkbox1=true
  2. checkbox2=true
  3. checkbox3=true
  4. checkbox10=true
  5. all other checkboxes are false
  6. On click of a button, the input should be passed to an apex class which will take the input and run some action based on what is selected as true
  • December 06, 2016
  • Like
  • 0
Hi,

We have a VF page that has a button which is supposed to trigger some action. How would we create a button on the VF page that will call a future class once clicked?

The objective is to click the button, then initiate a future class to perform some action that will run in the background while the user is able to proceed. 
  • December 04, 2016
  • Like
  • 0
Hi,

We have an application that uses VF pages and apex classes to create records for a custom object. We are providing access to the application (page and classes), but not the custom object.

How would we assign the application to just the chatter user profile so that they can create and view records for the custom object?
  • November 28, 2016
  • Like
  • 0
Hi, i am attempting to finish Add Business Logic for Build a Battle Station app and have been running into the following error message:

Challenge Not yet complete... here's what's wrong: 
There was an unexpected error while verifying this challenge. Usually this is due to some pre-existing configuration or code in the challenge Org. We recommend using a new Developer Edition (DE) to check this challenge. If you're using a new DE and seeing this error, please post to the developer forums and reference error id: VOBJIKYJ

I need help to figure out how to resolve this issue. I have enabled feed tracking for the battle station object, but still running issues. 
  • November 22, 2016
  • Like
  • 0
HI,

We are using the standard Account page layouts. I was wondering what it would take to make a button conditionally show if a specific criteria was met. I am unable to find anything that allows a button to show up on a page layout conditionally. I know we can create custom page layouts and assign it per profile, but that is not the scenario. Ideally, based on the field values, the button should display or disappear. 

What is the recommended way to accomplish this?
Hi,

We have recently refreshed our sandbox from the production org. As per latest requests, we have made the following changes in the sandbox and eventually we want to deploy to production.

Changes:
  • Contact Layout A
    • Added two new fields
    • Added new section
  • Lead Layout A
    • Added two new fields
    • added new section
  • Added two fields to both Contacts and Leads
    • field1
    • field2
  • Updated permissions for multiple profiles (after adding two fields)
    • profile1
    • profile2
    • profile3
Hi,
We are trying to automate the exporting of a report to xls file rather than manually doing it through the UI. 

I am currently using the Ant Migration Tool to export the metadata for a particular report (i.e. "ExampleReport") and save the metadata in file "ExampleReport.report" file. The ".report" file is basically an xml format and contains the columns and filter for the report. 

How can i use this ExampleReport.report file to extract the data resulting from the report and save it as an xls file? Would i be able to use the Ant migration tool or would i have to use something like java to do this?

ExampleReport.report file
<?xml version="1.0" encoding="UTF-8"?>
<Report xmlns=".../metadata">
         <columns>
                   <field>Account_Name</field>
         <columns>

         <filter>
                <booleanFilter> 1 OR 2 </booleanFilter>
                <criteriaItems>
                          <columns> Opportunity.Name</columns>
                                  <operator>contains</operator>
                         <value>some_value</value>
              <criteriaItems>
                          <columns> Account.Name</columns>
                                  <operator>contains</operator>
                         <value>some_value</value>
             </criteriaItems>
         </filter>

         /* there are some other items, but for the sake of the length, i am omitting for now */
</report>

 
  • April 27, 2016
  • Like
  • 0
Hi,

I have a situation where we have contact name's with characters such as an apostrophe in the Name field. What is the best way to still query the contact's name that contain an apostrophe?

Example scenario:
  • Contact.Name = "John D'oe";
  • Contact.Name = "John O'doe'
Current SOQL query:
//assume it is a single contact
String nm = contact.Name;

Select Id, Name From Contact Where Name =: nm;

The current error message: uncaught exception malformed query
  • April 26, 2016
  • Like
  • 0
Hi,

I am using the following code below to get the day of the week from the DateTime field, but I am finding that the day of the week is wrong. Essentially i am getting the ((day of the week) - 1) 

For example:
  • For a DateTime value of 4/9/2016, i am getting Friday (when it is really on a Saturday)
  • For a DateTime value of 4/12/2016, i am getting Monday (when it is really on a Tuesday)
Any thoughts on how i can get the correct day of the week?
//for simplicity assume dt variable is defined and set to 2016-04-09 00:00:00. 
String dateStr = dt.format('EEEE'); 

//use for debugging
System.debug('Day of Campaign: '+dateStr+ ' Time: '+dt);

 
  • February 26, 2016
  • Like
  • 0
Hi,

We have a VisualForce (VF) page that renders as a pdf. I have an automated email that is going to be trigger when criteria A, b, and C are met. 

How can i attach the pdf from the VF page as an email attachment in the automated email that is sent from an apex trigger or class?
  • October 25, 2015
  • Like
  • 1
Hi,
How can i create a one to many relationship between a campaign and campaign members? The setup is as follows: whenever a lead or contact is added to a campaign, it is considered a campaign member. I want to be able to check if a particular lead or contact is a campaign member already. If not, then I want to make it a campaign member of a campaign when a certain criteria is met.

how can I do this in an apex class/trigger?
Hi,
I am new ant migration tool. I am able to retrieve my desired triggers and classes perfectly fine. Lets say I make an update to only 1 out of 10 triggers and 2 our 15 classes in my codepkg folder. Does the Ant migration tool know which one it needs to update or will it update all 10 triggers and 15 classes because they are in my codepkg folder?

How does the Ant migration tool know which triggers and classes to update? Is there a particular command that I can use that specifies which ones to only update on the server? Also, if I update both the trigger and the trigger's metadata (xml) file, will that also be updated on the server?
  • March 01, 2014
  • Like
  • 1
Hi Everyone,

I'm having problem with heap size error
We have a trigger from the trigger we are calling so any classes,if we do any changes in the record it showing heap size 

Please help 
Thanks in advance 

Regards
Rathod
I  have picklist field called "Novated_opportunity__c", when 'yes' is selected, need to hide "Outline_of_the_Novated_opportunity__c"

I am using below script, no error's however no result.

<apex:page standardController = "Pricing_Request__c" showHeader="true" >
    <apex:form>
        <apex:outputPanel id="t1">
            <apex:pageBlock>
                <apex:pageBlockSection title="Novated leases">
                    <apex:inputField value="{!Pricing_Request__c.Novated_opportunity__c}" >
                    
                        <apex:actionSupport event="onchange" rerender="t1" />
                    </apex:inputField>
                </apex:pageBlockSection>
                
                <apex:pageBlockSection title="Novated leases">
                    <apex:inputField value="{!Pricing_Request__c.Outline_of_the_Novated_opportunity__c}" rendered="{!IF( Pricing_Request__c.Novated_opportunity__c == 'Yes', true, false )}" >
                        <apex:actionSupport event="onchange" rerender="t1" />
                    </apex:inputField>
                    
                </apex:pageBlockSection>
            </apex:pageBlock> 
        </apex:outputPanel>
    </apex:form>
</apex:page>


Thanks,
Vinod

Here's what I've been staring at for 16 minutes so far. 

User-added image

Deployed via SFDX, specifying a single apex test to run, which has less than 40 lines of code. Takes only a fraction of a second to run in scratch org or sandbox.

But when I deploy to Production, all components are validated within a minute or two, then the status switches to 'Running {testname}'.... and stays that way. For literally 15 minutes or more. Before the test is even started. 

I'm not finding a lot of posts on this issue. Plenty of people talking about the time it takes to actually run the test. But I'm talking about the time it takes to start running the tests. This isn't a one time thing, but it also isn't consistent. Sometimes the tests will begin running pretty much immediately. Sometimes I'll end up cancelling and redeploying because a 30 minute delay to START testing seems ridiculous even given Salesforce's standards. And when I do cancel and redeploy? Good chance it'll take a fifth of the time, for no apparent reason.

What I'd really like is some better communication during this process. Why is my test run delayed? What was prioritized ahead of it? How can I anticipate deployment times so it's not a complete crapshoot regardless of build size? 

Hi Developers,

I have a requirement to integrate Salesforce with Azure Queue. I want to write a batch class to hit the queue and if there is any record in the queue, then insert/update in the salesforce. Any code/Document for reference will be much helpful.

Thanks,
Rishabh
Hi,

I wrote a trigger to update the Project Item from Project (Parent to Child update.)

For the same, I wrote a test class also. I covered all the things in test class even though my code coverage is 50% only.

Kindly let me know where am doing the mistake.


Trigger:

trigger OI_Update_ProjItem_Status on Project__c (after update) {
    
    set<id>setprojid = new set<id>();
    list<Sale_Products__c>lstsp = new list<Sale_Products__c>();
    list<Project_Item__c>lstpi = new list<Project_Item__c>();
    
    for(Project__c proj : Trigger.New){
        if((proj.Nature_of_Case__c == 'Project Complete / Delivered - Payment Due' || proj.Nature_of_Case__c == 'Project Completed - Payment Recieved') && (proj.Project_Type__c.Contains('Indoor')
            || proj.Project_Type__c.Contains('Furniture'))){
             setprojid.add(proj.id);
        }
            
    }
    if(setprojid.size() > 0){
     
        for(Project_Item__c pi : [SELECT id, Status__c FROM Project_Item__c WHERE Project__c IN :setprojid]){
            pi.Status__c = 'Delivered';
            lstpi.add(pi);
        } 
           
        for(Sale_Products__c sp : [SELECT id, Status__c , Work_Order__c FROM Sale_Products__c WHERE Work_Order__c IN : setprojid]){
            sp.Status__c = 'Delivered';
            lstsp.add(sp);
        } 
   } 
   if(lstpi.size() > 0){
       update lstpi;
   } 
   if(lstsp.size() > 0){
       update lstsp;
   }            
}

Test Class:

@isTest(seealldata=true)
Public class TestWorkorder{
    static testMethod void TestWorkorder(){
    
       Test.startTest();  
        
        
        
        
             Profile p = [SELECT Id FROM Profile WHERE Name='Standard User'];
             
            User u = new User(Alias = 'Test', Email='Test@testorg.com', 
            EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US', 
            LocaleSidKey='en_US', ProfileId = p.Id, 
            TimeZoneSidKey='America/Los_Angeles', UserName='xyz@gmail.com');
            
            insert u;
            
            
        
       Pricebook2 pb = new Pricebook2(Name = 'Standard Price Book 2009', Description = 'Price Book 2009 Products', IsActive = true );
      insert pb;
    
    
        Product2 prod = new Product2(Name = 'SLA: Bronze', IsActive = true);
        insert prod;
    
    
// First insert a price for the standard price book

            Pricebook2 standardPB = [select id from Pricebook2 where isStandard=true];
            
            PricebookEntry standardPBE = new PricebookEntry(Pricebook2Id = standardPB.Id, Product2Id = prod.Id, UnitPrice = 1000, IsActive = true);
                insert standardPBE;
                
            PricebookEntry pbe = new PricebookEntry(Pricebook2Id = pb.Id, Product2Id = prod.Id, UnitPrice = 1000, IsActive = true);
                insert pbe;
        
        Account a = new Account(Name = 'ApprovalTest' ,Lock_record__C=FALSE ,ownerid=u.ID);
        insert a; 
       
        
        
        Opportunity opp =New Opportunity(Name='Test', accountId = a.id, StageName='Closed Won',CloseDate=Date.newInstance(2018, 04, 30));
        insert Opp; 
        
       
            
             Contact con = new COntact();
            con.email='test@fmail.co';
            con.ACCOUNTID=a.ID;
            con.ownerid=a.ownerid;
            con.lastname='test' ;
            
            insert con;
                         
            
        
       
           
            
        
        Opp.Pricebook2Id = pb.id;
        update Opp;
        
        OpportunityLineItem OL = new OpportunityLineItem(opportunityid=Opp.id, Quantity=1, unitprice=8000,  
            pricebookentryid=pbe.id);
        insert OL;  
            
        Quote Q = new Quote();
        Q.Name = 'QuoteOrbit';
        Q.OpportunityId = Opp.id; 
        Q.Quote_Count__c = 00000000;
        Q.Approved__c = true;
        Q.Quote_Number__c ='000000';
        Q.Quotation_Date__c = date.newinstance(2013,3,5);
        Q.Pricebook2Id = pb .id;
        
        insert Q;
        
        Quotelineitem QL = new Quotelineitem(quoteId=Q.id, Quantity =1, Unitprice=8000,pricebookentryid=pbe.id);
        insert QL; 
        
        Opp.SyncedQuoteId = Q.id;
        update Opp;
        
        
         
        Project__c Proj = new Project__c(name='OrbitProj', Opportunity__c = Opp.id, Quote__c = Q.id, Project_Type__c = 'New PE', Date_of_Installation__c = date.newinstance(2013,4,5),
            Nature_of_Case__c ='No Adv, Dspch & Erection Pending',Contact__C=con.ID,Customer_Name__c=a.id,Special_Instructions__c ='Test for Work order Pdf to be generated');    
            
        insert Proj;  
        
        Proj .Nature_of_Case__c = 'Project Completed - Payment Recieved';
        Proj .Nature_of_Case__c ='Project Complete / Delivered - Payment Due';
        Proj .Despatch_Date__c=Date.newInstance(2018, 04, 30);
        Proj .Delivery_Date__c=Date.newInstance(2018, 04, 30);
        
         update Proj ;
        
        
        
       
                
       
        
       
                
        Project_Item__c pi = new Project_Item__c(Project__c = Proj .id,Status__c = 'Pending',Product__c = prod.id,
                                 Technician_Member__c = 'suren; lakshmanan');
        insert pi;
        
        Project_Item__c pitm=[select ID, Status__c  from Project_Item__c  where ID=:Pi.ID];
        
        
        
        pitm.Status__c = 'Delivered' ;      
        
        update pitm;    
       
                
     
         
        
        Product_Inventory__c PInv=new Product_Inventory__c  (Product__c=prod.id);
        insert PInv;
        
        
     
        
        Sale_Products__c sp = new Sale_Products__c  (Status__c ='pending' ,Work_Order__c=Proj .id,Product_Inventory__c=PInv.ID,Quantity__c=1);
        insert sp ;
        
        Sale_Products__c Spr= [select Status__c  from Sale_Products__c  where ID=:Sp.id];
        
        Spr.Status__c ='Delivered';    
        
        update Spr;
        
       
        
         Test.stopTest();
 
        
    }
    
}

 
Hi,

I am looking for an Apex Class + Trigger to --> when I create an opportunity from a custom object record (very much like an account) with associated contacts, I'd like to automatically create X number of contact roles per contacts related to the custom object record and tie those Opportunities to the newly created Opportunity.

The account custom obejct record works very similar like the relationship for Account -- Opportunity -- Contact. 

I'd love to have the code also to prevent Duplicate Contact Roles (based on the contact Id) in the Opportunity Contact Role. Provided below is the Apex Trigger I have so far. The problem is the Trigger doesn't prevent duplicate Opportunity contact roles from being created, and I dont have an Apex class for it.

AccountSpecific__c --> custom object record
Accountspecificid__c --> custom field on the Contact
AccountSpecificOppId__c --> custom field on the Opportunity
trigger createOpportunityContactRoles on Opportunity (after insert) {

    Set<Id> accSpecificIds = new Set<Id>();
    List<OpportunityContactRole> ocrList = new List<OpportunityContactRole>();
    Map<Id, List<Contact>> accountSpecificContacts = new Map<Id, List<Contact>>();
    
    for(Opportunity o: Trigger.New) {
        if(o.AccountSpecificOppId__c != Null) 
            accSpecificIds.add(o.AccountSpecificOppId__c);
    }
    
    for(Contact con: [select id, AccountSpecificId__c from Contact 
                    where AccountSpecificId__c in: accSpecificIds]) {
        if(!accountSpecificContacts.containsKey(con.AccountSpecificId__c)) 
            accountSpecificContacts.put(con.AccountSpecificId__c, new List<Contact>());
        accountSpecificContacts.get(con.AccountSpecificId__c).add(con);
    }
    
    for(Opportunity opp: Trigger.New) {
        if(accountSpecificContacts.containskey(opp.AccountSpecificOppId__c) 
            && accountSpecificContacts.get(opp.AccountSpecificOppId__c) != NULL) {
            Boolean isFirstContact = true;
            for(Contact c: accountSpecificContacts.get(opp.AccountSpecificOppId__c)) {
                OpportunityContactRole ocr = new OpportunityContactRole(ContactId = c.Id, 
                                                                        OpportunityId = opp.id);
                if(isFirstContact) {
                    ocr.IsPrimary = true;
                    isFirstContact = false;
                }
                ocrList.add(ocr);
            }
        }           
    }
    
    if(ocrList.size() > 0)
        insert ocrList;
}

 
  • May 02, 2018
  • Like
  • 0
How can i update a check box in all parent account above the hierarchy from the child account check box?
Hi All,
            Noticed that after perparing and before processing,Total Batches field will be updated.

            Want to understand if preparing is the status where START method query is executed and 
            based on batch size total batches gets calculated ? All this happend during perparing state of batch job ?
            Can we understand if perparing is done means START method has completed successfully ?
            And BEGIN method won't start executing when status is perparing?

           Please comment on my above understandings.

Thanks
D
HI all - 

I have Opportunity Products configured via workflow + field update so based on Billing Frequency (Monthly, Quarterly, Yearly, One Time) my Standard Field Sales Price (aka UnitPrice) will calculate. I have tried this in Process Builder and it didn't work well either.
We have Subscription and Non-Subscription line items on Opportunity Products line items and customer may be billed differently for each line item.
Below is a view of Products I've chosen based on a 24 month contract:
User-added image
I created a custom field called "Unit Price" to hold the original amount input
I then wrote the following formulas to update the standard field called Sales Price (aka UnitPrice):

SUBSCRIPTION Update Field Sales Price:

IF(CONTAINS(Billing_Frequency__c, "Monthly"), Unit_Price__c *1, 
IF(CONTAINS(Billing_Frequency__c, "Quarterly"), Unit_Price__c *3, 
IF(CONTAINS(Billing_Frequency__c, "Yearly"), Unit_Price__c *12, 
IF(CONTAINS(Billing_Frequency__c, "One Time"), Unit_Price__c *1, null))))

NON-SUBSCRIPTION Field Update Sales Price:

IF(CONTAINS(Billing_Frequency__c, "Monthly"), 
Unit_Price__c * Quantity / Contract_Terms__c, 
IF(CONTAINS(Billing_Frequency__c, "Quarterly"), 
Unit_Price__c * Quantity / Contract_Terms__c *3, 
IF(CONTAINS(Billing_Frequency__c, "Yearly"), 
Unit_Price__c * Quantity / Contract_Terms__c * 12, 
IF(CONTAINS(Billing_Frequency__c, "One Time"), 
Unit_Price__c *1, null))))

Then, for the Total Contract Amount I create these two formula for updating the fields:

SUBSCRIPTION Field Update Total Contract Value:
TotalPrice / Billing_Frequency_Number__c * Contract_Terms__c

NON-SUBSCRIPTION Field Update Total Contract Value:
IF(CONTAINS(Billing_Frequency__c, "Monthly"), 
UnitPrice * Opportunity.Contract_Term_Number__c / 1, 
IF(CONTAINS(Billing_Frequency__c, "Quarterly"), 
UnitPrice * Opportunity.Contract_Term_Number__c / 3, 
IF(CONTAINS(Billing_Frequency__c, "Yearly"), 
UnitPrice * Opportunity.Contract_Term_Number__c / 12, 
IF(CONTAINS(Billing_Frequency__c, "One Time"), 
TotalPrice, null))))

My challenge is that the Contract Term updates just fine but the change doesn't trigger a recalculation. What am I doing wrong?
I have Evaluation Criteria as: Evaluate the rule when a record is created, and any time it's edited to subsequently meet criteria
I even checked the boxed on each Field Update that says: Re-evaluate Workflow Rules after Field Change
Even if I go into the Opportunity Product Line item record and make a change, re-calculations still don't happen. 

Thanks in advance to anyone who can help me with this!!
down vote favorite
I am trying to update a lookup field(Benefit_ID in Customer object) with the below code, The code works fine for single record but it is failing for multiple records:
Error: "caused by: System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, "
trigger updatelookupfield_Customer on Customer__c (before insert,before update) {
    Set<String> Bundle = new Set<String>();

    for (Customer__c Cust : Trigger.new) {
        Bundle.add(Cust.Bundle__c);
    }
List<Benfit__c> BenfitList = [SELECT id, Bundle__c FROM Benfit__c WHERE Bundle__c IN :Bundle];

    Map<String, Benfit__c> ASSIGN_BENEFIT = new Map<String, Benfit__c>();

    for (Benfit__c c : BenfitList) {
        ASSIGN_BENEFIT.put(c.Bundle__c, c);
    }

    for (Customer__c o : Trigger.new) {
              if (o.Bundle__c != null) {
            o.Benefit_ID__c = ASSIGN_BENEFIT.get(o.Bundle__c).id;
        }
        else {
            o.Benefit_ID__c = null;
        }
    }
    }
Just to highlight i am using multiple triggers on this object, not sure that is the reason for this issue.
 
Hello! 
I need to show on the VF page (table) results of the 3 SOQL requests:

I have 2 objects: Users and related SyncLog__c

I need to see on the table
First column: Users list
Second column: Is there records created before 10 AM YES/NO
Third column: Is there records created after 6 PM YES/NO



 
Hi Expert,

I need to create a Label type field on opportunity page layout:
As per below image i need "Security 4" Label in stanard page layout.

 User-added image

Please confirm

Regard
Mukesh
I currently am working on creating an Apex Class that initiially pulls a specific set of Placements (jstcl__Placement__c) and puts them in a list. 
It then takes that list of Placement Ojects and edits a relevant field called TimecardEnddateAudit__c field. I keep getting errors saying that the field jstcl__Timesheet_Period__c that exists in some of my if logic does not exist. Logically it should edit fields according to the logic:" If the jstcl__Timesheet_Period__c field is equal to 'Weekly Split' then add .5, else add 1. 
public class CamstimecardEndDateAudit{
public static void auditTimeCards(){

List<sObject> placements = [SELECT jstcl__Placement__r.Name
                            FROM jstcl__TG_Timesheet__c 
                            WHERE jstcl__Placement__r.ts2__Status__c IN ('Active') 
                             AND jstcl__Week_Ending__c = LAST_N_DAYS:15
                             AND jstcl__Status__c = 'Pending'];
                             
    for(List<sObject> A : placements){

        if(A.jstcl__Timesheet_Period__c = 'Weekly Split'){
        
        TimecardEndDateAudit__c = TimecardEndDateAudit__c + 0.5;}
        
        else{
        
        TimecardEndDateAudit__c = TimecardEndDateAudit__c ++;
}
}
}}

 
Hi,

Is there any way to get description of all fields of an object in apex code?
Able to query inline text help, label, api name, length etc, but not the description.
Any workaround/trick ?

Thanks
Sid