• LaurenP6777
  • NEWBIE
  • 115 Points
  • Member since 2012

  • Chatter
    Feed
  • 1
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 31
    Questions
  • 23
    Replies
Hi guys, 

I can't seem to get anywhere with the test code for this simple table I put within a Visualforce Email Template:

Controller:
public  class GetOpportunityProducts
{
    public Id OpportunityId {get;set;}
      public List<OpportunityLineItem> GetLineItems()
    {
        List<OpportunityLineItem> line;
        line= [SELECT Quantity,Product2.Name,TotalPrice,Net_Value__c,CurrencyISOCODE,UnitPrice FROM OpportunityLineItem WHERE OpportunityId=: OpportunityId];
        return line;
    }
}
Small Table within VS Email
 
<c:DisplayOppLineItems OppId="{!relatedTo.Id}" /><br/><br/>          
        <br/>


 
Hi guys, 

I recently recreated my Account Team related list in visualforce. The delete button is only rendered next to the users own name on the account team. This is obviously to prevent users from deleting other people off account teams. My issue is, I would also like to allow Sales Directors to delete users that report into them. My brilliant idea was to pull the user's role ID and to query all of the roles underneath them in the heirarchy. Problem is, I can't figure out how to ONLY rendered the delete button if the team member's user Id is INCLUDED in the <set>. Is there a way to do this?

Basically- I just want to say "Render IF AccountTeamMember.UserId IN <set>"
HI Everyone, 

My org is in desperate need of allowing users to delete themselves from Account Teams. HOWEVER, we don't want users to be able to delete OTHER users. I could easily write a trigger to do that but when i try, the system says I can not write triggers on the Account Team Object. My next plan was to track deletes so I could monitor users that are deleting other users- but, again, I hit a road block bc you can't report on Account Team deletes. In fact, account team deletes don't even go into the sandbox. 

Does anyone know of a way to query (within the system) all Account Team members that have been deleted? SFDC says to use the "getDeleted()" function but it seems like that is only for the SOAP Api. I just want to quickly pull a query of deleted account team members and the last modified by. 

If anyone has a solution, please let me know. THANK YOU!!!!!!!!!!!!!!!!!
Hi Everyone,

This may be my most pathetic post yet, but I can not seem to figure this out. I have used VS pages and Apex Controllers to create new records and update existing--- HOWEVER, deleting just has me stumped! 

What i would like to do is... 

Create a button called "Delete myself from Account Team" and put it on the Account Object. Upon clicking the button, i would like the system to loop thru all Account Team Members and delete the one that matches the current users's User Id. Does anyone have the code for this? 
I recently turned on Overlay Opportunity Splits in one of my sandboxes. Now Test Code that previously worked is erroring with the following:

INVALID_CROSS_REFERENCE_KEY, Unable to create an opportunity team member for new opportunity split user.: [SplitOwnerId]

As you can see the code below isn't trying to insert a Team Member or OpportunitySplit so I've been going crazy trying to fix the issue. When I create an opportunity manually, an OpportunitySplit is NOT automatically created. I am stumped. 
@isTEst
Private class TestUpdateStormStatusonOppty{

    static testMethod void  UpdateStormStatus()
    {
    //create a user to run the test as
    
    Profile p = [Select id from Profile where name = 'CDS'];


User u = new User(alias = 'mo123', email='mousey.1234@covance.com',
      emailencodingkey='UTF-8', lastname='123', languagelocalekey='en_US',
      localesidkey='en_US', profileid = p.Id, country='United States',
      CVD_Division__c='CDS', User_Type__c='AE',
      timezonesidkey='America/Los_Angeles', username='mousey.1234@covance.com');
  insert u;

 //create an oppty with required fields
  RecordType RecType = [Select Id From RecordType  Where SobjectType = 'Opportunity' and DeveloperName = 'CDS'];
  
  Opportunity o = new Opportunity(Name='TestMethodMouse1',
        AccountId='001C000000nGrv3',
        Compound__c='a08C000000Gva2H',
        RecordTypeId=RecType.Id,
        CloseDate=System.Today(),
        StageName='Prospect',
        NextStep='test',
        Study_Phase__c='PreClinical',
        Probability_of_Win__c='10%',
        Integrated_Opportunity2__c='No',
        Primary_Contact_Role_Assigned__c=true);
        insert o;

        
        RFI_Status__c CSWA = new RFI_Status__c(
        Opportunity__c=o.id,
        Storm_Status__c='Current Opportunity',
        Triage_Outcome__c='No Go');
        
        Test.startTest();
        insert CSWA;
        Test.stopTest();
        

        Opportunity op=[SELECT Related_Storm_Status__c, Id FROM Opportunity WHERE Id=:o.id];
        System.assertEquals(op.Related_Storm_Status__c,'Current Opportunity');
        
}
}
Hi guys, 

I write test code for triggers and VS pages that actually do something. I can't seem to grasp the concept of how you write a test code for a VS page that simple displays a little table. Can someone help?
 
public class OpplineItemHist{
    private List<Oppty_Line_Item_History__c> Hist;
     private Opportunity Opp;
    public OpplineItemHist(ApexPages.StandardController controller) {
        this.Opp= (Opportunity)controller.getRecord();
        
        }
        public List<Oppty_Line_Item_History__c> getHist()
        
        {
        Hist= [SELECT Action__c,Action_Date__c,name, Action_Initiated_By__c,Action_Initiated_By__r.Alias,Fixed_Variable__c,Modification__c,
        Modification_Type__c,Opportunity__c,Oppty__c,CurrencyISOCode,Product_Family__c,mod__c,Product_Name__c,Quantity__c,Dropped__c,TotalPrice__c,Sales_Price__c,Line_Item__c,Delta_Total_Price__c,
        Site__c FROM Oppty_Line_Item_History__c WHERE Opportunity__c =:opp.id ORDER BY Action_Date__c DESC];
        
        return Hist;
        }
        }

All I do is use the above code in a VS page that displays the data. That is it!

Any help woudl be greatly appreciated. Thanks. 
Hi guys, 

I wrote an email handler and test class in my sandbox. The coverage is 100%. However, when I try to deploy the email handler class and test class to production, i get the following error:

Your code coverage is 0%. You need at least 75% coverage to complete this deployment.EmailNSSOs

I don't know how I can fix this or why it is saying this. My overall production coverage is 76%. 
/**
 * Email services are automated processes that use Apex classes
 * to process the contents, headers, and attachments of inbound
 * email.
 */
global class EmailNSSOs implements Messaging.InboundEmailHandler {

    global Messaging.InboundEmailResult handleInboundEmail(Messaging.InboundEmail email,
    Messaging.InboundEnvelope envelope) {

        Messaging.InboundEmailResult result = new Messaging.InboundEmailresult();

        String myPlainText= '';
  
  // Add the email plain text into the local variable 
 
  myPlainText = email.plainTextBody;
 String EmailFrom = 'Sender: '+email.FromAddress;
 String EmailTo = 'To: '+email.toAddresses;
 String Emailcc= 'Cc: '+email.ccAddresses;
 String EmailHeaders = 'Detail: '+email.headers;
 String FullDescription = EmailFrom+'\n'+EmailTo+'\n'+Emailcc+'\n'+myPlainText;
 
  String mysubject = email.subject;
  String Numb = mysubject.substringBetween('NSSO-',' ');
  String NSSONumber = 'NSSO-'+Numb;
  
 

 Task[] newTask = new Task[0];
 
  { 
  

  // Try to lookup any users based on the email from address
 
  
   NSSO_Parent__c vUS = [Select Id, Name
    From NSSO_Parent__c
    Where Name = :NSSONumber 
    Limit 1];
  
  User vUser = [Select Id, Email FROM User WHERE Username=:email.fromAddress LIMIT 1];
  
  
  // Add a new Task to the contact record we just found above.
  newTask.add(new Task(Description =  FullDescription,
       Priority = 'Normal',
       Status = 'Completed',
       Type = 'System Generated Email',
        Subject = email.subject,
        IsReminderSet = true,
        OwnerId=vUser.Id,
        ActivityDate=System.today(),
        ReminderDateTime = System.now()+1,
        WhatId =  vUS.Id));

 // Insert the new Task 
 insert newTask;

  

                if (email.binaryAttachments != null && email.binaryAttachments.size() > 0) {
      for (integer i = 0 ; i < email.binaryAttachments.size() ; i++) {
        Attachment attachment = new Attachment();
        // attach to the newly created contact record
        attachment.ParentId = vUS.Id;
        attachment.Name = email.binaryAttachments[i].filename;
        attachment.Body = email.binaryAttachments[i].body;
        insert attachment;
    }
            }
     
      
    result.success = true;
        return result;
    }
    
   } 
   }
 
@isTest
private class testEmailAlertEmailNSSOs{

static testMethod void testMe() {

 Profile p = [Select id from Profile where name = 'System Administrator'];


User u = new User(alias = 'mo123', email='mousey.1234@covance.com',
      emailencodingkey='UTF-8', lastname='123', languagelocalekey='en_US',
      localesidkey='en_US', profileid = p.Id, country='United States',
      CVD_Division__c='ED', User_Type__c='AE',
      timezonesidkey='America/Los_Angeles', username='mousey.1234@covance.com');
  insert u;
  
             
        
        NSSO_Parent__c q = new NSSO_Parent__c();
        q.Requestor_s_Name__c='Lauren Hanna';
        q.Requestor_s_E_mail__c='lauren.hanna@covance.com';
        q.Sponsor_s_Name__c='mouse';
        q.Protocol_Name__c='TEST';
        q.Total_Duration_in_months__c=10;
        q.KRD_Date__c=Date.newInstance(2017,01,01);
        q.Ownerid=u.id;
        

    Database.insert(q);
    
    
    
    Test.StartTest();

  // create a new email and envelope object
  Messaging.InboundEmail email = new Messaging.InboundEmail() ;
  Messaging.InboundEnvelope env = new Messaging.InboundEnvelope();
  
  
  NSSO_Parent__c insertedQt = [SELECT name FROM NSSO_Parent__c WHERE ID = :q.Id];

  // setup the data for the email
  email.subject = 'test '+insertedQt.name+' Account';
  email.fromname = 'FirstName LastName';
  email.fromAddress = 'mousey.1234@covance.com';

  
   // add an attachment
  Messaging.InboundEmail.BinaryAttachment attachment = new Messaging.InboundEmail.BinaryAttachment();
  attachment.body = blob.valueOf('my attachment text');
  attachment.fileName = 'textfile.txt';
  attachment.mimeTypeSubType = 'text/plain';

  email.binaryAttachments =
    new Messaging.inboundEmail.BinaryAttachment[] { attachment };

  

  // call the email service class and test it with the data in the testMethod
  EmailNSSOs emailProcess = new EmailNSSOs(); 
  emailProcess.handleInboundEmail(email, env);
  
   
  
  
Test.StopTest();

  // query for the contact the email service created
    
      Task Tsk2 = [select id, Type, status, subject, whatid from Task
    where whatid=:q.id];

 
 
    System.assertEquals(Tsk2.Status,'Completed');
  System.assertEquals(Tsk2.Type,'System Generated Email');
  

 
}
}
Hi Everyone, 

I have written many VS email template that include Opportunities and Opportunity Line Items. However, I am struggling when it comes to writing a VS email template that includes Opportunity, Opportunity Line Items, and Contact Role. 

Does anyone have a sample VS email and Apex Controller Component that would accomplish something similar? All I have been able to find online is example where they are querying the entire system in the controller (i.e. All acounts that have the word "Smith"). That is not what i am looking for- I am looking to query based on a records related to a SPECIFIC Opportunity. 

Any help would be greatly appreciated. 
Hi guys, 

I just wrote a quick trigger that will link a child record (NSSO_Parent__c) to an Opportunity based on matching Protocol Number fields. This is working fine but there will be instances when multiple opportunities has the same Protocol Number. In this case, i would like to link the record to the Parent Opportunity - i would know the record is the parent opportunity IF the field "Parent_Opportunity__c" is blank. 

Basically I want a nice way of saying "Run this query and ONLY IF it returns multiple results, loop back thru and choose the one that has "Parent_Opportunity__c = null"

Here is my trigger. Any help would be greatly appreciated!!!!
trigger UpdateParentonNSSO on NSSO_Parent__c (before insert, before update)
{

      for(NSSO_Parent__c n : trigger.new) { 

                if(n.Opportunity__c == null &&n.Protocol_Number__c!=null) { 

                           Opportunity SOpp = [SELECT Id from Opportunity where Protocol_Number__c = :n.protocol_number__c]; 

                            n.Opportunity__c=SOpp.Id; 

     } 
        } 
           }


 
Hi guys, 

I just wrote a quick trigger that will link a child record (NSSO_Parent__c) to an Opportunity based on matching Protocol Number fields. This is working fine but there will be instances when multiple opportunities has the same Protocol Number. In this case, i would like to link the record to the Parent Opportunity - i would know the record is the parent opportunity IF the field "Parent_Opportunity__c" is blank. 

Basically I want a nice way of saying "Run this query and ONLY IF it returns multiple results, loop back thru and choose the one that has "Parent_Opportunity__c = null"

Here is my trigger. Any help would be greatly appreciated!!!!
trigger UpdateParentonNSSO on NSSO_Parent__c (before insert, before update){ 


    
  
    for(NSSO_Parent__c n : trigger.new)
    {

      if(n.Opportunity__c == null &&n.Protocol_Number__c!=null)
          {
     
           Opportunity SOpp = [SELECT Id from Opportunity where Protocol_Number__c = :n.protocol_number__c];
     
   
   
   
       
        n.Opportunity__c=SOpp.Id;
       
        }
 
 
}

}



 
I have many products in my org that have the same name but different descriptions. I can't change this because we integrate with another system. I really need the users to be able to see the product description on the multilineitem layout (after they select the product). 

Is there any work around for this that does not involve recreating the Product Selection page? I am fine with doing a visualforce page for just the Multilineitem layout but redoing the Product Selector is over my head. THanks. 
Hi Everyone, 

I have been trying to create an Apex Controller that will allow users to click a "Send Email" button and have an email alert fire to the current opportunity owner AND all child opportunity owners. I keep getting the following error:

Method does not exist or incorrect signature: [Messaging.SingleEmailMessage].setToAddresses(List<Opportunity>) at line 25 column 4

Can someone explain how I can change the email addresses in my query to a list of String emails?
Public with sharing class Sendemail{

   public Opportunity Opp;
   
   public LIst<Opportunity> Oppty;
   
   public Sendemail(Apexpages.StandardController controller) {
   this.Opp=(Opportunity)controller.getRecord();
   
   }
 
  
 Public void sendEmailFunction(){
 
  
   List<Opportunity> Owners =[Select Owner.Email FROM Opportunity where Id=:opp.id OR Parent_Opportunity__r.Id=:opp.Id];   
   
    
  

   
   Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
  
  
   mail.setToAddresses(Owners);
  


   mail.setReplyTo('myemail@mail.com');
   mail.setSenderDisplayName('My Name');
  mail.setPlainTextBody('A related Opportunity has been won');
  mail.setHtmlBody('A related Opportunity has been won');
   mail.setBccSender(false);
   mail.setUseSignature(false);
  
   //mail.setHtmlBody('<b> This is HTML body </b>' );
   Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
 } 

}

Thanks!

 

Hello, 

I am trying to create a visualforce page that displays all of the current User's Opportunities. I would like to include Opportunities that they own AND all Opportunities where they are a member of the OpportunityTEam. 

My first attempt was to do a query like this:

MyOpTeam =[SELECT id, Record_Type_Name__c,  Name, StageName, Amount,  Owner.Id FROM Opportunity WHERE id IN (SELECT OpportunityId FROM OpportunityTeamMember WHERE (UserId=:UserInfo.getUserId() )OR (Opportunity.OwnerId=:UserInfo.getUserId())];  
*** PROBLEM: this only pulled opportunities that had team members. Any opportunities that I owned that did not have a team member record were excluded. 

Could anyone look at my current code and tell me how I can go about getting these two SEPARATE queries into one list? 
public class Oppsownerteam {
public Oppsownerteam(ApexPages.StandardController controller) {
        
}
    
 Id Mouse = Userinfo.getUserId();
 public List<Opportunity> MyOwnedOpps;
 public List<Opportunity> MyTEamOpps;
 

            Public Integer Get MyOwnedOpps()
               {
                  MyOwnedOpps =[SELECT id, Record_Type_Name__c,  Name, StageName, Amount,  Owner.Id FROM Opportunity WHERE ownerid =:Mouse];  
                return   MyOwnedOpps;       
                }
            

             Public List<Opportunity> GetMyTEamOpps()
               {                        
                MyTEamOpps =[SELECT id, Record_Type_Name__c,  Name, StageName, Amount,  Owner.Id FROM Opportunity WHERE id IN (SELECT OpportunityId FROM OpportunityTeamMember WHERE UserId=:Mouse)];  
                   
                return MyTEamOpps;                               
                 }
            
  



}

 
Hi guys, 

I have a custom object called User_Support__c in SFDC. I have an "Intake" record type that is the default for all users. Depending on there answer to a single field, i would like a trigger to change the record type. I have a formula field called "Record_Type_Conversion_Controller__c" that will determine the name of the record type i would like the record to be changed to. 

I get the following error when I try it : ConvertRecordType: execution of AfterInsert caused by: System.QueryException: List has no rows for assignment to SObject Trigger.ConvertRecordType: line 8, column 1 


Trigger ConvertRecordType on User_Support__c (after insert) {
User_Support__c u= Trigger.new[0];{
   

         //hold current User Support Fields
         u = [select Id, Record_Type_Conversion_Controller__c,Issue_Type__c, Name FROM User_Support__c WHERE Id=:u.id];
         
        RecordType RecType = [Select Id From RecordType Where SobjectType = 'Opportunity' and DeveloperName=:u.Record_Type_Conversion_Controller__c];
         

         If(u.Issue_Type__c =='License Request')
         u.name='License Request';
         If(u.Issue_Type__c !='License Request')
         u.name='';
         
        
         u.RecordTypeId=RecType.Id;
         
         update u;
         
         }
         }


If anyone could help it woudl be greatly appreciated!!!!
Good Afternoon, 

I have been using the Controller below as a deep clone on the Opportunity object. I would like to use FieldSets to determine which fields on the Opportunity Object should be included in the deep clone. This way, any administrator can update the FieldSet, hence updating the controller. Unfortunately, i can't see to grasp the concept and am having trouble replacing the list of fields with my fieldset.

Can someone show me how to replace the query under "//COPY THE OPPORTUNITY - ONLY INCLUDE THE FIELDS YOU WANT TO CLONE" with a query that uses the FieldSet :"ECD_WSC_Field_Set"?

Thank you!
 
public class AddWSCECDController {
 
    //added an instance varaible for the standard controller
    private ApexPages.StandardController controller {get; set;}
     // add the instance for the variables being passed by id on the url
    private Opportunity o {get;set;}
    // set the id of the record that is created -- ONLY USED BY THE TEST CLASS
    public ID newRecordId {get;set;}
 
    // initialize the controller
    public  AddWSCECDController(ApexPages.StandardController controller) {
 
        //initialize the stanrdard controller
        this.controller = controller;
        // load the current record
        o = (Opportunity)controller.getRecord();
 
    }
 
    // method called from the VF's action attribute to clone the po
    public PageReference AddWSCECD() {
 
         // setup the save point for rollback
         Savepoint sp = Database.setSavepoint();
         Opportunity newO;
 
 
         try {
 
              //COPY THE OPPORTUNITY - ONLY INCLUDE THE FIELDS YOU WANT TO CLONE
             
o = [select Id,
              name,    
              parent_opportunity__c,
              Parent_Opportunity__r.Name, 
              Parent_Opportunity__r.id,           
               Compound_Name__c,
              Compound__r.Id,
              StageName,
              LeadSource,
              Account.Name,
              AccountId,
              CurrencyISOCode,
              CloseDate,                        
              Original_Lead_Inquiry_Date__c,
              Protocol_Number__c,
              Protocol_Title__c,
              Therapeutic_Area__c,
              Therapeutic_Indication__c,
              Therapeutic_Indication_Other__c,
              High_Risk_Compound_GCP__c,
              General_Requests_Comments__c,
              Description,
              Route__c,
 Study_Phase__c,
              of_Covance_Sites__c,
Sites_per_country__c,
of_Subjects_Enrolled__c,
Special_Procedure_Requested__c,
If_Other_enter_here__c,
Assigned_Client_Manager__c,
Bill_Code__c,
Client_Flexible_on__c,
Site_GCP__c,
CMS_Number__c,
COMS_Number__c,
Contract_Analyst__c,
Covance_Study__c,
ERT_Collaboration_N__c,
ERT_Collaboration_Other__c,
ERT_Collaboration__c,
Est_CTA_Regulatory_Application_Date__c,
Estimated_LSLV__c,
Expected_Dosing_Treatment_Duration__c,
Financial_Check__c,
First_in_Human_Study__c,
FPI_Date__c,
GCP_Triage_notes__c,
Go_to_Bid_Defense_2nd_3rd_Round__c,
Government_Contract__c,
Government_Funding__c,
If_No_Why__c,
Please_Provide_Details_GCP_Non_Standard__c,
Please_Provide_Details_GCP_Bid_Defence__c,
RFP_RFI_Received__c,
Last_Subject_Visit__c,
Mode_of_Response_GCP__c,
MSA__c,
New_Oppty_Pull_Through_or_Rescue_Study__c,
Operational_questionnaire_required__c,
Patients_Healthy_Volunteers__c,
Potential_use_of_WOCBP_M3__c,
Proposed_Funding_by_Client__c,
Protocol_Synopsis_Available_Attached_GCP__c,
Pull_Through_Compound__c,
Push_Through_Compound__c,
Questionnaire_Completion_Date__c,
Region_Important_to_Client__c,
Required_Level_of_Costing_Detail__c,
RFP_RFI_Sent_to_Triage__c,
Screening_Start__c,
Services_Requested__c,
Special_Patient_Population__c,
Other_Special_Patient_Population__c,
Test_Material_Owner__c,
Trials_Ongoing_with_Client_in_CDS_Labs__c,
Trials_Ongoing_with_Client_in_CPS__c,
Customer_Status__c,
Operational_Site_Selected__c,
Differentiator_1_GCP__c,
Differentiator_2_GCP__c,
Differentiator_3_GCP__c,
Differentiator_4_GCP__c,
Differentiator_5_GCP__c,
Differentiator_6_GCP__c,
Differentiator_7_GCP__c,
Differentiator_8_GCP__c,
Differentiator_9_GCP__c,
ForecastCategoryName,
Therapeutic_Area_Group__c,
CMS_Parent_Oppty_Number__c,
Strategy_for_this_Project_Proposal__c,
Any_feedback_on_RBM_specifically__c,
Any_special_unusual_tasks_requested__c,
CLS_Proposal_Requirement__c,
Cost_Director__c,
Costing_Associate__c,
Countries__c,
Director__c,
ECD_Senior_Director__c,
Executive_Sponsor_if_required__c,
Expected_Study_Duration_FPI_to_LPO__c,
Feasibility_Information__c,
Finance_notes__c,
Inpatient_requirement__c,
Is_Japan_included_in_Country_Selection__c,
Legal_Rep_Required__c,
Level_of_Response__c,
MDG_Targeted_Opportunity__c,
Mechanism_of_action__c,
Opportunity_Type__c,
OS_P_Director__c,
Patients__c,
Physician__c,
Project_Region__c,
Proof_of_Concept__c,
Proposal_Associate__c,
Region__c,
RFP_RFI__c,
Scope_of_Services__c,
Study_Conduct_Location__c,
Test_Material_Owner__r.Id,
Time_Zone__c,
type_of_compound__c,
Was_RBM_proposed__c,
Was_RBM_requested__c from Opportunity where id = :o.id];
             
             newO = o.clone(false);
             
             Datetime DateMouse = Datetime.now();
             String ConvertedMouseDate = DateMouse.format('MM/dd/yy h:mm a');
             RecordType RecType = [Select Id From RecordType  Where SobjectType = 'Opportunity' and DeveloperName = 'ECD'];
             
             
             if(o.Parent_Opportunity__c==null){
             newo.Parent_Opportunity__c = o.Id;
             newo.WSC__c=true;
             newo.name=o.name+' WSC '+ConvertedMouseDate;
             newo.RecordTypeid=RecType.id;
             newo.NextStep='WSC';
             newo.Integrated_Opportunity2__c='No'; 
             newo.Stagename='Prospect';}
               
                     
             
             if(o.Parent_Opportunity__c!=null){
             newo.Parent_Opportunity__c = o.Parent_Opportunity__c;
             newo.RecordTypeid=RecType.id;
             newo.Stagename='Prospect';
             newo.WSC__c=true;
             newo.NextStep='WSC';  
             newo.Integrated_Opportunity2__c='No';     
             newo.name=o.Parent_Opportunity__r.Name+' WSC '+ConvertedMouseDate; }
           
              
           
             
             insert newO;
             
 
             // set the id of the new po created for testing
               newRecordId = newO.id;
               
                    // copy over oppty teams - ONLY INCLUDE THE FIELDS YOU WANT TO CLONE
             List<OpportunityTeamMember> oppteam = new List<OpportunityTeamMember>();
             for (OpportunityTeamMember tr : [Select r.Id, r.UserId, r.OpportunityId,r.TeamMemberRole From OpportunityTeamMember r where User.IsActive=true AND OpportunityId = :o.id]) {
                  OpportunityTeamMember newtr = tr.clone(false);
                  newtr.OpportunityId = newO.id;                  
                  oppteam.add(newtr);

             }
             insert oppteam;

               
                   // copy over Operational Team - ONLY INCLUDE THE FIELDS YOU WANT TO CLONE
             List<Operational_Team__c> team = new List<Operational_Team__c>();
             for (Operational_Team__c op : [Select p.Id, p.name, p.role__c, p.Lead_Site__c, p.Opportunity__c, p.Opportunity__r.Id From Operational_Team__c p where Opportunity__r.Id = :o.id]) {
                  Operational_Team__c newop =op.clone(false);
                  newop.Opportunity__c = newO.id;                  
                  team.add(newop);
             }  
               
 
             // copy over the line items - ONLY INCLUDE THE FIELDS YOU WANT TO CLONE
             List<OpportunityContactRole> items = new List<OpportunityContactRole>();
             for (OpportunityContactRole cr : [Select r.Id, r.ContactId, r.OpportunityId, r.Isprimary, r.role From OpportunityContactRole r where OpportunityId = :o.id]) {
                  OpportunityContactRole newcr = cr.clone(false);
                  newcr.OpportunityId = newO.id;                  
                  items.add(newcr);

             }
             insert items;
             insert team;
            
             
         } catch (Exception e){
             // roll everything back in case of error
            Database.rollback(sp);
            ApexPages.addMessages(e);
            return null;
         }


        Opportunity ooppss = [SELECT shortid__c FROM opportunity WHERE id = :newO.id];
 
        return new PageReference('/'+newo.id+'/e?&saveURL='+newo.id+'&retURL='+o.id);
    }
 
}

 
Hi All, 

I created the Email Handler class below to create a new task on a custom object (User_Support__c). The email will link to the appropriate record by matching the email subject to an auto-number field (Support__c) on the custom object. Unfortunately, I can't get the test method to work. I continually get an error that their are no rows for assignment. Can anyone tell me what I am doing wrong? 


/**
 * Email services are automated processes that use Apex classes
 * to process the contents, headers, and attachments of inbound
 * email.
 */
global class EmailtoSalesForce implements Messaging.InboundEmailHandler {

    global Messaging.InboundEmailResult handleInboundEmail(Messaging.InboundEmail email,
    Messaging.InboundEnvelope envelope) {

        Messaging.InboundEmailResult result = new Messaging.InboundEmailresult();

        String myPlainText= '';
  
  // Add the email plain text into the local variable 
 
  myPlainText = email.plainTextBody;
 
  // New Task object to be created
 
  Task[] newTask = new Task[0];
  {
 
  // Try to lookup any contacts based on the email from address
  // If there is more than 1 contact with the same email address,
  // an exception will be thrown and the catch statement will be called.
  
   User_Support__c vUS = [Select Id, Support__c, Name
    From User_Support__c
    Where Support__c = :email.subject
    Limit 1];
  
  // Add a new Task to the contact record we just found above.
  newTask.add(new Task(Description =  myPlainText,
       Priority = 'Normal',
       Status = 'Completed',
       Type = 'Email',
        Subject = email.subject,
        IsReminderSet = true,
        ReminderDateTime = System.now()+1,
        WhatId =  vUS.Id));
 
 // Insert the new Task 
 insert newTask;
 

                if (email.binaryAttachments != null && email.binaryAttachments.size() > 0) {
      for (integer i = 0 ; i < email.binaryAttachments.size() ; i++) {
        Attachment attachment = new Attachment();
        // attach to the newly created contact record
        attachment.ParentId = vUS.Id;
        attachment.Name = email.binaryAttachments[i].filename;
        attachment.Body = email.binaryAttachments[i].body;
        insert attachment;
    
            }
        }

    result.success = true;
        return result;
    }
    }
}


TEST CLASS
@isTest
private class testusersupportattach{

static testMethod void testMe() {

 Profile p = [Select id from Profile where name = 'GCP'];


User u = new User(alias = 'mo123', email='mousey.1234@covance.com',
      emailencodingkey='UTF-8', lastname='123', languagelocalekey='en_US',
      localesidkey='en_US', profileid = p.Id, country='United States',
      CVD_Division__c='ED', User_Type__c='AE',
      timezonesidkey='America/Los_Angeles', username='mousey.1234@covance.com');
  insert u;
  
 
  
User_Support__c us= New User_Support__c(name='attach email to User Support Case',
    Ideal_completion_date__c=System.Today(),
    Request_Type__c='Development',
    Priority_Level__c='Low',
    RecordTypeId='012C0000000I7wx',
    Requested_By__c=u.id);
    
    insert us;
    
    
    
    Test.StartTest();

  // create a new email and envelope object
  Messaging.InboundEmail email = new Messaging.InboundEmail() ;
  Messaging.InboundEnvelope env = new Messaging.InboundEnvelope();

  // setup the data for the email
  email.subject = us.support__c;
  email.fromname = 'FirstName LastName';
  env.fromAddress = u.email;
  

  // call the email service class and test it with the data in the testMethod
  EmailtoSalesForce emailProcess = new EmailtoSalesForce();
  emailProcess.handleInboundEmail(email, env);
Test.StopTest();

  // query for the contact the email service created
  Task Tsk = [select id, Type, status, subject, whatid from Task
    where whatid =:us.id];

  System.assertEquals(Tsk.Subject,us.name);
  System.assertEquals(Tsk.Status,'Completed');
  System.assertEquals(Tsk.Type,'Email');

 
}
}
Hello, 

Awhile ago, I followed instructed posted on this forum to put a dashboard within an Iframe. The post explained how to add some Jquery code to get the hyperlinks within the dashboard reports to work properly. This was great until the Summer 14 release when we noticed that users could no longer drill down to the dashboard report and click a hyperlink to a specific Opportunity. 

Does anyone know why this code would no longer work? 

<apex:page >

<script src="http://code.jquery.com/jquery-1.9.1.min.js">
jQuery( function ($) {

     $('#iframeID').load( function() {             
         var $frameDoc = this.contentWindow.document,
             urlMatch = /srcUp\(%27(.*)%27\)/;

         $('a[href*="srcUp"]', $frameDoc).each( function () {
             this.href = decodeURIComponent(this.href.match(urlMatch)[1]);
         });
     });

});
</script>

<!-- the rest of your page goes here -->

<iframe id="iframeID" src="/01ZC0000001Okk7?isdtp=vw" scrolling="true" height="100%" width="100%"/>

</apex:page>

I am having alot of trouble writing a test class for this trigger. It is a simply trigger that stops a user from delete an oppty product if the Opportunity is a certain record type and in the stage "Closed Won". Can someone help? Thanks!

 

 

trigger NOEDDELETES on OpportunityLineItem (before Delete) {

for (OpportunityLineItem oli: trigger.old)

if(oli.Oppty_Stage__c=='Closed Won - Order'&&(oli.Related_Oppty_Record_Type__c=='BIOA'||oli.Related_Oppty_Record_Type__c=='BIOTECH'||oli.Related_Oppty_Record_Type__c=='DM'||oli.Related_Oppty_Record_Type__c=='CMC'||oli.Related_Oppty_Record_Type__c=='TOX'))

{

OLI.adderror('For Opportunities in stage Closed Won - Order, deleting products in not allowed. You must use the Dropped Product Process. Post Final Quote, you must use the Modification Process');

}
}

Hi Everyone, 

 

I have recently scheduled an apex class to run via the Schedule Apex interface that will create new records in a custom object called "Oppty_Line_Item_History" when certain criteria is met on the standard object "OpportunityLineItem". The class works via trigger (although it does a weird duplicate thing because of workflows) but it does not seem to run when I schedule it it to run every night.  I also can't even figure out WHERE I can see what went wrong. 

 

Here is the class I want to run:

 

public class OpptyLineItemHISTORY{

public void method1(List<OpportunityLineItem> changes){
//List to hold LineItemHistory
List <Oppty_Line_Item_History__c> insertHIST = new List <Oppty_Line_Item_History__c>();



for (OpportunityLineItem o: changes){

if (o.priorvalues__c=='Yes'&& o.LastModifiedDate==date.today())
{
changes.add(o);

Oppty_Line_Item_History__c IH = new Oppty_Line_Item_History__c();

IH.Action_Date__c=o.lastmodifieddate;
IH.Action__c = 'Product Updated';
IH.Oppty_Line_Item_id__c = o.id;
IH.Opportunity__c = o.OpportunityId;
IH.Product_Name__c=o.Product_Name_in_TEXT__c;
IH.Oppty__c=o.opptytrigger__c;
IH.Line_Item__c=o.Line_Item_Id__c;
IH.Product_Family__c = o.Product_Family__c;
IH.Site__c=o.Site__c;
IH.fixed_Variable__c=o.fixed_Variable__c;
IH.discount__c=o.discount__c;

IH.Modification__c=o.Modification__c;
IH.Modification_Type__c= o.Modification_Type__c;
IH.Quantity__c=o.Quantity;
IH.Sales_Price__c = o.UnitPrice;
IH.Total_Price__c = o.Total__c;

insertHIST.add(IH);

insert IH;

}



//once loop is done, you need to insert new records in SF
//DML operations might cause an error, so you need to catch it with try/catch block.
} //once loop is done, you need to insert new records in SF
// dml operations might cause an error, so you need to catch it with try/catch block.

insert insertHIST;

}
}

 

Here is my schedulable class:

 

global class ScheduleLineItemHistory implements Schedulable {
global void execute (SchedulableContext SC) {

lineitemhistoryHELPER HELPER = new lineitemhistoryHELPER();

HELPER.CreateHistoryasNeeded();

}
}

 

 

I have been working with this trigger for some time and just can't seem to get it to stop adding mutliple records so I am resorting to the boards!

 

I am just trying to create a simple trigger on OpportunityLineItem that creates a custom object record when certain fields are updated. I am sure that I am using Trigger.old & Trigger.new in the wrong way. When I make certain changes- two records are inserted instead of one.

 

Could someone tell me what I am doing wrong?

 

trigger Itemupdated on OpportunityLineItem (before update) {

 

//List to hold LineItemHistory
List <Oppty_Line_Item_History__c> insertHIST = new List <Oppty_Line_Item_History__c>();
Oppty_Line_Item_History__c IH;

for (OpportunityLineItem o: Trigger.new) {

OpportunityLineItem oldoli = Trigger.oldMap.get(o.ID);
if (o.site__c != oldoli.site__c||o.fixed_Variable__c != oldoli.fixed_Variable__c||o.UnitPrice != oldoli.UnitPrice||
o.quantity != oldoli.quantity||o.Modification_Type__c != oldoli.Modification_Type__c)
{



IH= new Oppty_Line_Item_History__c ();
IH.Action_Initiated_by__c=o.lastmodifiedbyId;
IH.Action_Date__c=o.lastmodifieddate;
IH.Action__c = 'Product Updated';
IH.Oppty_Line_Item_id__c = o.id;
IH.Opportunity__c = o.OpportunityId;
IH.Product_Name__c=o.Product_Name_in_TEXT__c;
IH.Oppty__c=o.opptytrigger__c;
IH.Line_Item__c=o.Line_Item_Id__c;
IH.Product_Family__c = o.Product_Family__c;
IH.Site__c=o.Site__c;
IH.fixed_Variable__c=o.fixed_Variable__c;
IH.Discount__c=o.Discount__c;
IH.Modification__c=o.Modification__c;
IH.Modification_Type__c= o.Modification_Type__c;
IH.Quantity__c=o.Quantity;
IH.Sales_Price__c = o.UnitPrice;
IH.Total_Price__c = o.Total__c;

insertHIST.add(IH);

}



//once loop is done, you need to insert new records in SF
//DML operations might cause an error, so you need to catch it with try/catch block.
try {
insert insertHIST;
}
catch (system.Dmlexception e) {
system.debug(e);
}

 

 

}}

 

HI Everyone, 

My org is in desperate need of allowing users to delete themselves from Account Teams. HOWEVER, we don't want users to be able to delete OTHER users. I could easily write a trigger to do that but when i try, the system says I can not write triggers on the Account Team Object. My next plan was to track deletes so I could monitor users that are deleting other users- but, again, I hit a road block bc you can't report on Account Team deletes. In fact, account team deletes don't even go into the sandbox. 

Does anyone know of a way to query (within the system) all Account Team members that have been deleted? SFDC says to use the "getDeleted()" function but it seems like that is only for the SOAP Api. I just want to quickly pull a query of deleted account team members and the last modified by. 

If anyone has a solution, please let me know. THANK YOU!!!!!!!!!!!!!!!!!
I recently turned on Overlay Opportunity Splits in one of my sandboxes. Now Test Code that previously worked is erroring with the following:

INVALID_CROSS_REFERENCE_KEY, Unable to create an opportunity team member for new opportunity split user.: [SplitOwnerId]

As you can see the code below isn't trying to insert a Team Member or OpportunitySplit so I've been going crazy trying to fix the issue. When I create an opportunity manually, an OpportunitySplit is NOT automatically created. I am stumped. 
@isTEst
Private class TestUpdateStormStatusonOppty{

    static testMethod void  UpdateStormStatus()
    {
    //create a user to run the test as
    
    Profile p = [Select id from Profile where name = 'CDS'];


User u = new User(alias = 'mo123', email='mousey.1234@covance.com',
      emailencodingkey='UTF-8', lastname='123', languagelocalekey='en_US',
      localesidkey='en_US', profileid = p.Id, country='United States',
      CVD_Division__c='CDS', User_Type__c='AE',
      timezonesidkey='America/Los_Angeles', username='mousey.1234@covance.com');
  insert u;

 //create an oppty with required fields
  RecordType RecType = [Select Id From RecordType  Where SobjectType = 'Opportunity' and DeveloperName = 'CDS'];
  
  Opportunity o = new Opportunity(Name='TestMethodMouse1',
        AccountId='001C000000nGrv3',
        Compound__c='a08C000000Gva2H',
        RecordTypeId=RecType.Id,
        CloseDate=System.Today(),
        StageName='Prospect',
        NextStep='test',
        Study_Phase__c='PreClinical',
        Probability_of_Win__c='10%',
        Integrated_Opportunity2__c='No',
        Primary_Contact_Role_Assigned__c=true);
        insert o;

        
        RFI_Status__c CSWA = new RFI_Status__c(
        Opportunity__c=o.id,
        Storm_Status__c='Current Opportunity',
        Triage_Outcome__c='No Go');
        
        Test.startTest();
        insert CSWA;
        Test.stopTest();
        

        Opportunity op=[SELECT Related_Storm_Status__c, Id FROM Opportunity WHERE Id=:o.id];
        System.assertEquals(op.Related_Storm_Status__c,'Current Opportunity');
        
}
}
Hi guys, 

I just wrote a quick trigger that will link a child record (NSSO_Parent__c) to an Opportunity based on matching Protocol Number fields. This is working fine but there will be instances when multiple opportunities has the same Protocol Number. In this case, i would like to link the record to the Parent Opportunity - i would know the record is the parent opportunity IF the field "Parent_Opportunity__c" is blank. 

Basically I want a nice way of saying "Run this query and ONLY IF it returns multiple results, loop back thru and choose the one that has "Parent_Opportunity__c = null"

Here is my trigger. Any help would be greatly appreciated!!!!
trigger UpdateParentonNSSO on NSSO_Parent__c (before insert, before update)
{

      for(NSSO_Parent__c n : trigger.new) { 

                if(n.Opportunity__c == null &&n.Protocol_Number__c!=null) { 

                           Opportunity SOpp = [SELECT Id from Opportunity where Protocol_Number__c = :n.protocol_number__c]; 

                            n.Opportunity__c=SOpp.Id; 

     } 
        } 
           }


 
Hi Everyone, 

I have been trying to create an Apex Controller that will allow users to click a "Send Email" button and have an email alert fire to the current opportunity owner AND all child opportunity owners. I keep getting the following error:

Method does not exist or incorrect signature: [Messaging.SingleEmailMessage].setToAddresses(List<Opportunity>) at line 25 column 4

Can someone explain how I can change the email addresses in my query to a list of String emails?
Public with sharing class Sendemail{

   public Opportunity Opp;
   
   public LIst<Opportunity> Oppty;
   
   public Sendemail(Apexpages.StandardController controller) {
   this.Opp=(Opportunity)controller.getRecord();
   
   }
 
  
 Public void sendEmailFunction(){
 
  
   List<Opportunity> Owners =[Select Owner.Email FROM Opportunity where Id=:opp.id OR Parent_Opportunity__r.Id=:opp.Id];   
   
    
  

   
   Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
  
  
   mail.setToAddresses(Owners);
  


   mail.setReplyTo('myemail@mail.com');
   mail.setSenderDisplayName('My Name');
  mail.setPlainTextBody('A related Opportunity has been won');
  mail.setHtmlBody('A related Opportunity has been won');
   mail.setBccSender(false);
   mail.setUseSignature(false);
  
   //mail.setHtmlBody('<b> This is HTML body </b>' );
   Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
 } 

}

Thanks!
Hi guys, 

I have a custom object called User_Support__c in SFDC. I have an "Intake" record type that is the default for all users. Depending on there answer to a single field, i would like a trigger to change the record type. I have a formula field called "Record_Type_Conversion_Controller__c" that will determine the name of the record type i would like the record to be changed to. 

I get the following error when I try it : ConvertRecordType: execution of AfterInsert caused by: System.QueryException: List has no rows for assignment to SObject Trigger.ConvertRecordType: line 8, column 1 


Trigger ConvertRecordType on User_Support__c (after insert) {
User_Support__c u= Trigger.new[0];{
   

         //hold current User Support Fields
         u = [select Id, Record_Type_Conversion_Controller__c,Issue_Type__c, Name FROM User_Support__c WHERE Id=:u.id];
         
        RecordType RecType = [Select Id From RecordType Where SobjectType = 'Opportunity' and DeveloperName=:u.Record_Type_Conversion_Controller__c];
         

         If(u.Issue_Type__c =='License Request')
         u.name='License Request';
         If(u.Issue_Type__c !='License Request')
         u.name='';
         
        
         u.RecordTypeId=RecType.Id;
         
         update u;
         
         }
         }


If anyone could help it woudl be greatly appreciated!!!!
Hi All, 

I created the Email Handler class below to create a new task on a custom object (User_Support__c). The email will link to the appropriate record by matching the email subject to an auto-number field (Support__c) on the custom object. Unfortunately, I can't get the test method to work. I continually get an error that their are no rows for assignment. Can anyone tell me what I am doing wrong? 


/**
 * Email services are automated processes that use Apex classes
 * to process the contents, headers, and attachments of inbound
 * email.
 */
global class EmailtoSalesForce implements Messaging.InboundEmailHandler {

    global Messaging.InboundEmailResult handleInboundEmail(Messaging.InboundEmail email,
    Messaging.InboundEnvelope envelope) {

        Messaging.InboundEmailResult result = new Messaging.InboundEmailresult();

        String myPlainText= '';
  
  // Add the email plain text into the local variable 
 
  myPlainText = email.plainTextBody;
 
  // New Task object to be created
 
  Task[] newTask = new Task[0];
  {
 
  // Try to lookup any contacts based on the email from address
  // If there is more than 1 contact with the same email address,
  // an exception will be thrown and the catch statement will be called.
  
   User_Support__c vUS = [Select Id, Support__c, Name
    From User_Support__c
    Where Support__c = :email.subject
    Limit 1];
  
  // Add a new Task to the contact record we just found above.
  newTask.add(new Task(Description =  myPlainText,
       Priority = 'Normal',
       Status = 'Completed',
       Type = 'Email',
        Subject = email.subject,
        IsReminderSet = true,
        ReminderDateTime = System.now()+1,
        WhatId =  vUS.Id));
 
 // Insert the new Task 
 insert newTask;
 

                if (email.binaryAttachments != null && email.binaryAttachments.size() > 0) {
      for (integer i = 0 ; i < email.binaryAttachments.size() ; i++) {
        Attachment attachment = new Attachment();
        // attach to the newly created contact record
        attachment.ParentId = vUS.Id;
        attachment.Name = email.binaryAttachments[i].filename;
        attachment.Body = email.binaryAttachments[i].body;
        insert attachment;
    
            }
        }

    result.success = true;
        return result;
    }
    }
}


TEST CLASS
@isTest
private class testusersupportattach{

static testMethod void testMe() {

 Profile p = [Select id from Profile where name = 'GCP'];


User u = new User(alias = 'mo123', email='mousey.1234@covance.com',
      emailencodingkey='UTF-8', lastname='123', languagelocalekey='en_US',
      localesidkey='en_US', profileid = p.Id, country='United States',
      CVD_Division__c='ED', User_Type__c='AE',
      timezonesidkey='America/Los_Angeles', username='mousey.1234@covance.com');
  insert u;
  
 
  
User_Support__c us= New User_Support__c(name='attach email to User Support Case',
    Ideal_completion_date__c=System.Today(),
    Request_Type__c='Development',
    Priority_Level__c='Low',
    RecordTypeId='012C0000000I7wx',
    Requested_By__c=u.id);
    
    insert us;
    
    
    
    Test.StartTest();

  // create a new email and envelope object
  Messaging.InboundEmail email = new Messaging.InboundEmail() ;
  Messaging.InboundEnvelope env = new Messaging.InboundEnvelope();

  // setup the data for the email
  email.subject = us.support__c;
  email.fromname = 'FirstName LastName';
  env.fromAddress = u.email;
  

  // call the email service class and test it with the data in the testMethod
  EmailtoSalesForce emailProcess = new EmailtoSalesForce();
  emailProcess.handleInboundEmail(email, env);
Test.StopTest();

  // query for the contact the email service created
  Task Tsk = [select id, Type, status, subject, whatid from Task
    where whatid =:us.id];

  System.assertEquals(Tsk.Subject,us.name);
  System.assertEquals(Tsk.Status,'Completed');
  System.assertEquals(Tsk.Type,'Email');

 
}
}
Hello, 

Awhile ago, I followed instructed posted on this forum to put a dashboard within an Iframe. The post explained how to add some Jquery code to get the hyperlinks within the dashboard reports to work properly. This was great until the Summer 14 release when we noticed that users could no longer drill down to the dashboard report and click a hyperlink to a specific Opportunity. 

Does anyone know why this code would no longer work? 

<apex:page >

<script src="http://code.jquery.com/jquery-1.9.1.min.js">
jQuery( function ($) {

     $('#iframeID').load( function() {             
         var $frameDoc = this.contentWindow.document,
             urlMatch = /srcUp\(%27(.*)%27\)/;

         $('a[href*="srcUp"]', $frameDoc).each( function () {
             this.href = decodeURIComponent(this.href.match(urlMatch)[1]);
         });
     });

});
</script>

<!-- the rest of your page goes here -->

<iframe id="iframeID" src="/01ZC0000001Okk7?isdtp=vw" scrolling="true" height="100%" width="100%"/>

</apex:page>

Hi Everyone, 

 

I have recently scheduled an apex class to run via the Schedule Apex interface that will create new records in a custom object called "Oppty_Line_Item_History" when certain criteria is met on the standard object "OpportunityLineItem". The class works via trigger (although it does a weird duplicate thing because of workflows) but it does not seem to run when I schedule it it to run every night.  I also can't even figure out WHERE I can see what went wrong. 

 

Here is the class I want to run:

 

public class OpptyLineItemHISTORY{

public void method1(List<OpportunityLineItem> changes){
//List to hold LineItemHistory
List <Oppty_Line_Item_History__c> insertHIST = new List <Oppty_Line_Item_History__c>();



for (OpportunityLineItem o: changes){

if (o.priorvalues__c=='Yes'&& o.LastModifiedDate==date.today())
{
changes.add(o);

Oppty_Line_Item_History__c IH = new Oppty_Line_Item_History__c();

IH.Action_Date__c=o.lastmodifieddate;
IH.Action__c = 'Product Updated';
IH.Oppty_Line_Item_id__c = o.id;
IH.Opportunity__c = o.OpportunityId;
IH.Product_Name__c=o.Product_Name_in_TEXT__c;
IH.Oppty__c=o.opptytrigger__c;
IH.Line_Item__c=o.Line_Item_Id__c;
IH.Product_Family__c = o.Product_Family__c;
IH.Site__c=o.Site__c;
IH.fixed_Variable__c=o.fixed_Variable__c;
IH.discount__c=o.discount__c;

IH.Modification__c=o.Modification__c;
IH.Modification_Type__c= o.Modification_Type__c;
IH.Quantity__c=o.Quantity;
IH.Sales_Price__c = o.UnitPrice;
IH.Total_Price__c = o.Total__c;

insertHIST.add(IH);

insert IH;

}



//once loop is done, you need to insert new records in SF
//DML operations might cause an error, so you need to catch it with try/catch block.
} //once loop is done, you need to insert new records in SF
// dml operations might cause an error, so you need to catch it with try/catch block.

insert insertHIST;

}
}

 

Here is my schedulable class:

 

global class ScheduleLineItemHistory implements Schedulable {
global void execute (SchedulableContext SC) {

lineitemhistoryHELPER HELPER = new lineitemhistoryHELPER();

HELPER.CreateHistoryasNeeded();

}
}

 

 

I have been working with this trigger for some time and just can't seem to get it to stop adding mutliple records so I am resorting to the boards!

 

I am just trying to create a simple trigger on OpportunityLineItem that creates a custom object record when certain fields are updated. I am sure that I am using Trigger.old & Trigger.new in the wrong way. When I make certain changes- two records are inserted instead of one.

 

Could someone tell me what I am doing wrong?

 

trigger Itemupdated on OpportunityLineItem (before update) {

 

//List to hold LineItemHistory
List <Oppty_Line_Item_History__c> insertHIST = new List <Oppty_Line_Item_History__c>();
Oppty_Line_Item_History__c IH;

for (OpportunityLineItem o: Trigger.new) {

OpportunityLineItem oldoli = Trigger.oldMap.get(o.ID);
if (o.site__c != oldoli.site__c||o.fixed_Variable__c != oldoli.fixed_Variable__c||o.UnitPrice != oldoli.UnitPrice||
o.quantity != oldoli.quantity||o.Modification_Type__c != oldoli.Modification_Type__c)
{



IH= new Oppty_Line_Item_History__c ();
IH.Action_Initiated_by__c=o.lastmodifiedbyId;
IH.Action_Date__c=o.lastmodifieddate;
IH.Action__c = 'Product Updated';
IH.Oppty_Line_Item_id__c = o.id;
IH.Opportunity__c = o.OpportunityId;
IH.Product_Name__c=o.Product_Name_in_TEXT__c;
IH.Oppty__c=o.opptytrigger__c;
IH.Line_Item__c=o.Line_Item_Id__c;
IH.Product_Family__c = o.Product_Family__c;
IH.Site__c=o.Site__c;
IH.fixed_Variable__c=o.fixed_Variable__c;
IH.Discount__c=o.Discount__c;
IH.Modification__c=o.Modification__c;
IH.Modification_Type__c= o.Modification_Type__c;
IH.Quantity__c=o.Quantity;
IH.Sales_Price__c = o.UnitPrice;
IH.Total_Price__c = o.Total__c;

insertHIST.add(IH);

}



//once loop is done, you need to insert new records in SF
//DML operations might cause an error, so you need to catch it with try/catch block.
try {
insert insertHIST;
}
catch (system.Dmlexception e) {
system.debug(e);
}

 

 

}}

 

Can someone help me? This button sits on the OpportunitLineItem related list on the Opportunity page.  I would like to add an "if else" that stops the button from firing if the field "Modification__c" on the opportunitylineitem (that is checked of course) = true. I can not figure out how to query for this. Thanks!

 

{!REQUIRESCRIPT("/soap/ajax/20.0/connection.js")}
{!REQUIRESCRIPT("/soap/ajax/20.0/apex.js")}

var IdsToClone, cloneLength, IdToClone;

IdsToClone = {!GetRecordIDs($ObjectType.OpportunityLineItem)};

cloneLength = IdsToClone.length;

if(cloneLength == 0) {
alert("You must choose at least one product to clone");
}
else if(cloneLength > 1) {
alert("You can't clone more than one product at a time");
}

else{
IdToClone = IdsToClone[0];
window.open("/apex/cloneamendment?id="+IdToClone);
}

I would like to direct users to a visualforce page that clones the opportunity AFTER they choose a record type. 

 

Is there a way that I can rewrite the button code to somehow "detour" to the opportunity record type selection page prior to going to the vf page? 

 

/apex/addstudyED?id={!Opportunity.Id}

 

OR  

 

Can i somehow add code to the controller that will allow the user to stop at the record type selection page?

 

 

 

public class AddSTudyEDController {

//added an instance varaible for the standard controller
private ApexPages.StandardController controller {get; set;}
// add the instance for the variables being passed by id on the url
private Opportunity o {get;set;}
// set the id of the record that is created -- ONLY USED BY THE TEST CLASS
public ID newRecordId {get;set;}

// initialize the controller
public AddStudyEDController(ApexPages.StandardController controller) {

//initialize the stanrdard controller
this.controller = controller;
// load the current record
o = (Opportunity)controller.getRecord();

}

// method called from the VF's action attribute to clone the po
public PageReference AddStudyED() {

// setup the save point for rollback
Savepoint sp = Database.setSavepoint();
Opportunity newO;


try {

//copy the purchase order - ONLY INCLUDE THE FIELDS YOU WANT TO CLONE
o = [select Id, RFI__c,Molecule_Size__c, Name,AccountId, Parent_Opportunity__r.Record_Type_Name__c,Parent_Opportunity__c,Compound_Name__c, Compound__r.Id, StageName, Currency_To_Quote__c,CloseDate, Program_Managed__c,Integrated_Opportunity2__c,funding_approved__c from Opportunity where id = :o.id];
newO = o.clone(false);

if(o.Parent_Opportunity__c==null)
newo.Parent_Opportunity__c = o.Id;

if(o.Parent_Opportunity__r.Record_Type_Name__c=='ED - ADMIN TEST'
||o.Parent_Opportunity__r.Record_Type_Name__c=='BIOA'
||o.Parent_Opportunity__r.Record_Type_Name__c=='TOX'
||o.Parent_Opportunity__r.Record_Type_Name__c=='BIOTECH'
||o.Parent_Opportunity__r.Record_Type_Name__c=='DM'
||o.Parent_Opportunity__r.Record_Type_Name__c=='CMC')
newo.Parent_Opportunity__c = o.Parent_Opportunity__c;

if(o.Parent_Opportunity__r.Record_Type_Name__c!='ED - ADMIN TEST'
&&o.Parent_Opportunity__r.Record_Type_Name__c!='BIOA'
&&o.Parent_Opportunity__r.Record_Type_Name__c!='TOX'
&&o.Parent_Opportunity__r.Record_Type_Name__c!='BIOTECH'
&&o.Parent_Opportunity__r.Record_Type_Name__c!='DM'
&&o.Parent_Opportunity__r.Record_Type_Name__c!='CMC')
newo.Parent_Opportunity__c = o.id;


newo.Name = 'pending - must overwrite';
newo.Stagename = 'Prospect';


insert newO;

// set the id of the new po created for testing
newRecordId = newO.id;

// copy over the line items - ONLY INCLUDE THE FIELDS YOU WANT TO CLONE
List<OpportunityContactRole> items = new List<OpportunityContactRole>();
for (OpportunityContactRole cr : [Select r.Id, r.ContactId, r.OpportunityId, r.IsPrimary, r.role From OpportunityContactRole r where OpportunityId = :o.id]) {
OpportunityContactRole newcr = cr.clone(false);
newcr.OpportunityId = newO.id;
items.add(newcr);
}


// copy over the line items - ONLY INCLUDE THE FIELDS YOU WANT TO CLONE
List<OpportunityTeamMember> teams = new List<OpportunityTeamMember>();
for (OpportunityTeamMember tm : [Select m.Id, m.OpportunityAccessLevel, m.OpportunityId, m.UserId, m.IsDeleted, m.TeamMemberRole From OpportunityTeamMember m where OpportunityId = :o.id]) {
OpportunityTeamMember newtm = tm.clone(false);
newtm.OpportunityId = newO.id;
teams.add(newtm);
}
insert items;
insert teams;

} catch (Exception e){
// roll everything back in case of error
Database.rollback(sp);
ApexPages.addMessages(e);
return null;
}

return new PageReference('/'+newO.id+'/e?retURL='+O.id+'&saveURL='+newO.id);
}

}

 

 

 

I am trying to add a command button to my visualforce page that clones an opportunity IF certain criteria is met- if it is not met, I would like an error message to appear. This works fine via javascript in the standard UI but when I add it to my visualforce page it acts weird. 

 

Instead of firing "onclick" of the command button it fires as soon as the page loads (and if I click the button). Can someone help me? THank you. 

 

 

Here is my code:

 

<apex:commandButton value="New Integrated Opportunity" onclick="mouse();"/>
<script>
function mouse(){

if("{!Opportunity.Integrated_Opportunity2__c}"=='No'){

alert('Please select Yes for Integrated Opportunity?');
}
else
{
window.location="/{!Opportunity.Id}/e?clone=1&retURL=%2f{!Opportunity.Id}&00Nc0000000QhbH=1&00NC00000050hhz={!Opportunity.Id}";}}

mouse();
</script>

Hi Everyone, 

 

I have almost completed a large project I am working on and, of course, I am hung up on my last small task. I need to create a custom button on my visualforce page that clones the current opportunity and automatically sets some field values. I would like to do this as simply as possibly. 

 

I can do it very easily with an outputlink:

 

<apex:outputlink

value="/{!Opportunity.Id}/e?clone=1&retURL=%2f{!Opportunity.Id}&00Nc0000000QhbH=1&00NC00000050hhz={!Opportunity.Id}"> New Child Opportunity

</apex:outputlink>

 

Can someone explain how to do this simple link using a PageBlockButton or CommandButton? Thank you!