• Cushty
  • NEWBIE
  • 120 Points
  • Member since 2015

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

What am I missing fro this test class to get the % code coverage up.

I am an admin and have the below trigger which after an opportunity is set to won will update the contact role.  Its a bit long winded but what it does is count the type of product thats selected on the opportunity and then update the corresponding checkbox on the contact role once the opportunity is set to won

TRIGGER
trigger UpdateContactProduct on Opportunity (after update) {

   Set<Id> st_OppId = new Set<Id>();
List<Contact> con_List;

for(Opportunity opp :Trigger.new)
  {
     if(opp.StageName=='Won' )
         st_OppId.add(opp.id);
 }

if(st_OppId!=null && !st_OppId.isEmpty())
    {

         for(OpportunityContactRole iterating_oppConRole : [SELECT Role, 
                                                                      OpportunityId, 
                                                                      IsPrimary, 
                                                                      Id, 
                                                                      ContactId,
                                                                      Contact.Lead_Lifecycle_Stage__c ,
                                                                      Contact.X1Edit_bought__c, 
                                                                      Contact.X1Exchange_bought__c,         
                                                                      Opportunity.Count_1Edit__c,
                                                                      Opportunity.Count_1Exchange__c,
                                                                   FROM OpportunityContactRole  where OpportunityId IN : st_OppId])
                               {

                    if(iterating_oppConRole.Opportunity.Count_1Edit__c > 0)
                        {
                              iterating_oppConRole.Contact.X1Edit_bought__c = true;
                        }
                                             
                    if(iterating_oppConRole.Opportunity.Count_1Exchange__c> 0)
                        {
                              iterating_oppConRole.Contact.X1Exchange_bought__c = true;
                        }
                                           if(con_List == null)
                                           con_List = new List<Contact>();

                                          con_List.add(iterating_oppConRole.Contact);
                                }

               
           }
        
        if(con_List!=null && !con_List.isEmpty())
            update con_List;
}

TEST CLASS
@IsTest

Public Class testAddProductsBought
 {
    static testMethod void ValidateContactProduct()
    {
    
    Account a = new Account();
    a.Name ='demo';
    a.Industry = 'Education';
    a.BillingCountry = 'United Kingdom';
    insert a;
    
    
    Contact c = new Contact();
    c.FirstName = 'Lord';
    c.LastName = 'Test2';
    c.Accountid = a.id; 
    c.RecordTypeid = '012w000000063q6AAA';
    insert c;
    
    
    Contact ci = new Contact();
    ci.FirstName = 'Bob';
    ci.LastName  = 'Test';
    ci.AccountId = a.id;
    ci.RecordTypeid = '012w000000063q6AAA';
    insert ci;
    
    
    Opportunity o = new Opportunity();
    o.AccountId = a.Id;
    o.StageName = 'Won';
    o.RecordTypeid = '012w0000000ic3mAAA';
    o.Final_Price_Number__c = 2000;
    o.Business_Unit__c = '1Spatial United Kingdom';
    o.Name = 'Test';
    o.Opportunity_Type__c = 'Contract Renewal';
    O.CurrencyIsoCode ='GBP';
    o.Contract_Type__c = 'Framework';
    o.Estimated_Value_Number__c = 10000;
    o.Opportunity_Submission_Date__c = Date.TODAY();
    o.CloseDate = Date.TODAY() +2;
    o.Probability__c = '80-99%';
    o.Purchase_Order__c = '2L3454';
    o.Solution_Summary__c = 'Hardware';
    o.Description = 'Update Contact role';
    o.Opportunity_Process_Stage__c= 'Opportunity Submitted to Customer: Approved`';
    o.Ownerid = '005w0000004ExSiAAK';
    insert o;
    
        
     OpportunityContactRole cr = new OpportunityContactRole();
     cr.Opportunityid = o.id;
     cr.Role = 'Administrator';
     cr.Contactid = c.id;
     cr.IsPrimary = true;
     insert cr;
     
     OpportunityContactRole ocr1 = new OpportunityContactRole();
     ocr1.ContactId = ci.Id;
     ocr1.OpportunityId = o.Id;
     ocr1.IsPrimary = FALSE;
     ocr1.Role = 'Decision Maker';
     insert ocr1;
     
    
     Id pricebookId = Test.getStandardPricebookId();
     Product2 prod = new Product2();
     prod.Name = 'Product 2';
     prod.ProductCode = 'Pro-2';
     prod.isActive = true;
     prod.Revenue_Type__c = 'Services';
     prod.Product_Heading__c = '1Edit';
     insert prod;

     PricebookEntry pbEntry = new PricebookEntry();
     pbEntry.Pricebook2Id = pricebookId;
     pbEntry.Product2Id = prod.Id;
     pbEntry.UnitPrice = 100.00;
     pbEntry.IsActive = true;
     insert pbEntry;

     OpportunityLineItem oli = new OpportunityLineItem();
     oli.OpportunityId = o.Id;
     oli.quantity = 1;
     oli.PricebookEntryId = pbEntry.Id;
     oli.TotalPrice = oli.quantity * pbEntry.UnitPrice;
     insert oli;

    o.StageName = 'Won';
    update o;
    update cr;

}
}
Hi,

I am having a crack at creating a very simply visualforce page where a user can Set a reason for Recycling a lead or Disqualifying a lead..

The user would click a button on the lead object which redirects them to a simple page which shows two fields (dependant picklist) of the Stage and then a reason of that lead.
They only see one option from the picklist and select a reason then click save where thery are redirected back to the lead which is updated.

A bit like closing a lead...

Here is the page; -

<apex:page standardController="Lead">
    <apex:form >
        <apex:pageBlock title="Recycled Reason">
                     <apex:pageblockbuttons >
                     <apex:commandbutton action="{!save}" value="Save"></apex:commandbutton>
                     <apex:commandbutton action="{!cancel}" value="Cancel"></apex:commandbutton>
                     </apex:pageblockbuttons>
                     
                <apex:pageBlockSection columns="1">
            <apex:inputField value="{!Lead.Lead_Lifecycle_Stage__c}" required="true"/>
            <apex:inputField value="{!Lead.Recycle_Reasons__c}" required="true"/>
             </apex:pageBlockSection>
        </apex:pageBlock>
    </apex:form>
</apex:page>

So far I just have two fields on a page which are the picklist and the picklist reason....
 
Hi,

I am trying to write an apex trigger to update contact fields from a won opportunity (opportunity contact role) and have little knowledge of how to do so (admin background).

All products sit under a main 'product category'.  I have also added these categories as individual check boxes on the contact page.  
What I am trying to do is once the opportuntiy is closed Won, look at the opportunity products purchased and for each category they sit under, update the Contact Roles (Contact) record, setting each category checkbox to true.  Obviously there maybe more than once product bought from the same category so the checkbox only needs checking once

Here is what I attempted so far.  I created a rollup summary field (example Product category1) on the Opportunity object which counts how many products there are of Product category1.  Then the below trigger to fires after the Opportunity is closed won, checks there is more than 0 of Product category1 and updates the correctonding contact role (contact) checkbox.

trigger UpdateContactProduct on Opportunity (after update) {

        OpportunityContactRole ocr;
        Contact contact;
        Opportunity opp = Trigger.new[0];
        list<Contact> listToUpdate = new list<Contact>();
        if(opp.StageName == 'Won' && opp.Count_1Edit__c > 0){

          for(OpportunityContactRole iterating_oppConRole : [SELECT o.Role, 
                                                                      o.OpportunityId, 
                                                                      o.IsPrimary, 
                                                                      o.Id, 
                                                                      o.ContactId,
                                                                      o.Contact.Lead_Lifecycle_Stage__c 
                                                              FROM OpportunityContactRole o where o.OpportunityId =: opp.id])
                                                              {
               Contact tempContact = new Contact(id=iterating_oppConRole.ContactId, 
                X1Edit_bought__c = true);
                listToUpdate.add(tempContact);
               
           }
        }
        if(!listToUpdate.isEmpty())
            update listToUpdate;
}

This seems I am going the wrong way about it as I would have to create a roll summary field for each category and triggers for each when I am hoping it can be done in one trigger checking the products in th eopportunity and updating the categories on the contact record.

Thanks for any help that comes my way..
Hi,

I have created a custom button in java on the Lead List view and cannot get it to work properly.

As its a button on the list view it first checks you have selected a record, otherwise shows an error and then once records are selected it needs to check that a picklist field is 'MQL' and if so changes the value of a few fields.  If the picklist is anything else other than MQL it displays and error.

I am nearly there but the error on th epicklist shows regardless of the picklist value....

{!REQUIRESCRIPT ("/soap/ajax/24.0/connection.js")}
{!REQUIRESCRIPT("/soap/ajax/24.0/apex.js")} 
var records = {!GETRECORDIDS($ObjectType.Lead)};

var newRecords = [];

if (records[0] == null) {
alert("Please select at least one row");

} else {

if('{!Lead.Lead_Lifecycle_Stage__c}' != "Marketing Qualified Lead (MQL)") {
alert("You cannot Take Ownership of this lead until it has reached the Marketing Qualified Lead (MQL) stage.\n\n If you would like this lead fast tracked to MQL, please contact Marketing.");

} else {

for (var n=0; n<records.length; n++) {
var l = new sforce.SObject("Lead");l.id = records[n];
l.OwnerId ="{!$User.Id}";
l.Status = "Open";
l.Lead_Lifecycle_Stage__c = "Sales Accepted Lead (SAL)";

newRecords.push(l);
}
result = sforce.connection.update(newRecords);
parent.window.location.reload();
}
}
Hi,

I am new to apex and an trying to write a trigger that will update a contact field after an opportunity is closed won.  These contacts are those contact roles attached to the opportunity.

I have a custom field on the contact and also the account object called Lifecycle Status and would like these to update to 'Customer' upon the opportunity becoming closed won.

First here is my bad code for trying to update the contact role on the opportunity to 'customer': 

trigger UpdateContact on Opportunity (after insert, after update) {

        OpportunityContactRole ocr;
        Contact contact;
        
        Opportunity opp = Trigger.new[0];
            if(opp.StageName == 'Won' && opp.Number_Of_Contact_Roles__c > 0)
            
          ocr = [Select o.Role, o.OpportunityId, o.IsPrimary, o.Id, o.ContactId 
         From OpportunityContactRole o where o.OpportunityId =: opp.id];

          contact = [Select c.OwnerId, c.Id, c.AccountId,c.name,c.Lead_Lifecycle_Stage__c 
          From Contact c where c.id =: ocr.ContactId ];
         
                {
                    contact.Lead_Lifecycle_Stage__c = 'Customer';
                    update contact;      
                }
}


I am getting a null error and asuming because its looking for the contact role upon saving the opportunity when its not there.  How do I list or map the associated contact roles to the opportunity and then upon one fire the update of the contact field and account field (although the account field maybe a separate trigger

Thanks for any help
Hi,

When an opportunity is created from a contact, I want this contact to them become the contact role on that opportunity.

I know this is standard functionality in salesforce but I have to created a custom button to create a new opportunity as it updates a few fields so lost this functionality......unless there is an easier way to keep the origional New button and then default some fields before the report is created?

Thanks
Hi,

I am struggling to combine two validation rules on a custom java button in salesforce.  I want the validation to check if a picklist value equals "procurement"and also that a number field is blank/null, if so display a message.  Below is what I have which doesn't do aything because I do not know how to check for a null/blank value (it works if I stated the number field equals a specific number, just doesn't work if equals null).

if({!ISPICKVAL(Opportunity.Contract_Type__c, "Procurement") && Opportunity.Final_Price_Number__c == null}) {
     alert('You need to enter the Final Price.............

Anyone can help, thanks..
Hi,

I have created a custom button on the Opportunity object.  When clicked it runs a class which in turn starts off the approval process. 

This works fine in my developer sandbox but is not deploying due to code coverage issues.  I wonder if anyone can help, bearing in mind I have got as far as I can with some research as I am not a programmer and wanting to learn

Thanks

Class code with no coverage: -

global class Opportunity_Approval_to_PrepBid {

        public String myopi {get; set;}
        Webservice static String callApproval(String myopi) {

        Opportunity op = new Opportunity(Id=myopi);
        update op;

                Approval.ProcessSubmitRequest req1 = new Approval.ProcessSubmitRequest();
                req1.setComments('Submitted for Approval');
                req1.setObjectId(myopi);
                Approval.ProcessResult res = Approval.Process(req1);   
                
                return null;
              
    }
}


Test class I tried: -

@IsTest

Public Class testApprovePrepare
 {
    static testMethod void testApprovePrepare()
    {
    
    Account a = new Account();
    a.Name ='demo';
    a.Industry = 'Education';
    a.BillingCountry = 'United Kingdom';
    insert a;
    
    Opportunity o = new Opportunity();
    o.AccountId = a.Id;
    o.StageName = 'Pipeline';
    o.Business_Unit__c = '1Spatial United Kingdom';
    o.Name = 'Test';
    o.Opportunity_Type__c = 'Contract Renewal';
    o.Contract_Type__c = 'Framework';
    o.Estimated_Value_Number__c = 10000;
    o.Opportunity_Submission_Date__c = Date.TODAY();
    o.CloseDate = Date.TODAY() +2;
    o.Probability__c = '80-99%';
    o.Purchase_Order__c = 'PO Pending';
    o.Solution_Summary__c = 'Hardware';
    o.Description = 'Renewal Contract for the next financial year';
    o.Opportunity_Process_Stage__c= 'Qualified Opportunity';
    insert o;
    
    Approval.ProcessSubmitRequest req1 = new Approval.ProcessSubmitRequest();
                req1.setComments('Submitted for Approval');
                req1.setObjectId(o.Id);
                req1.setProcessDefinitionNameOrId('Auto_Approval_to_Prepare_Bid');
                Approval.ProcessResult res = Approval.Process(req1); 
                
                try{
            res = Approval.process(req1);
        }catch(Exception e){
            System.debug('No approval process has been setup yet.');


     }
}
}

Any help would be appreciated in getting this deployed to production

Many Thanks
If statement on custom button syntax

Hi,
I am trying to do some validaton checks on some fields via a custom button and am getting stuck on a number field.  Basically I want to check.....does an opportunity type = Tender, the final price is less than 100,000 and the sharepoing link is blank  Here is the code: -

if({!ISPICKVAL(Opportunity.Opportunity_Type__c, "Tender")} && '{!Opportunity.Final_Price_Number__c}' > "100,000.00" && '{!Opportunity.Final_Pricing_Sharepoint_Link__c}' == "") {
     alert('You need to enter the Final Pricing Sharepoint URL for this Tender before submitting for approval');

The final price field is a number field and I think its this thats not working.  I am getting the error message all the time when I only need it when the figure typed in is less than 100,000

Thanks
 
Hi,

I have created a flow and process builder which will clone an Opportunity and add the line items, works fine.  What I want to do now is once that new opportunity is created, create a quote on it and add the quote line items (add the opportunity line items, the same as it does normally if you created a quote on an Opp) and then create a pdf on that quote.

I have tried to create another flow to add to my process builder for the quote creation and quote line items to create the quote and add the line items but nothing happens, no quote created, no line items, so I need to know what I am doing wrong, no error message.....I need to know how to do this so I can find out where I am going wrong. 

I have also tried writing a trigger for this quote creationa nd line items and got as far as creating the quote, but do not know how to add the line items to that quote noce its created and then create a PDF template on that quote.

Would it be best to go down the trigger route or should I try and get my flow working if that way is possible?
Thanks
 

Hey All , 

 

We are using SAP as our ERP . I have created a custom button in salesforce.com on Account Record namely , "SAPRequest" . Whenever user clicks on this button, record should be submitted for approval (WE DONT CARE ABOUT THE APPROVERS , IT SHOULD JUST BE SUBITTED FOR APPROVAL ) . I created a apex class and javascript for this below:

 

Apex class:

 

global class SAPRequest {

WebService static void SendApprovalRequest(string id) {

// create the new approval request to submit
Approval.ProcessSubmitRequest req = new Approval.ProcessSubmitRequest();
req.setComments('Submitted for approval. Please approve.');
// submit the approval request for processing
Approval.ProcessResult result = Approval.Process(req);
// display if the reqeust was successful
System.debug('Submitted for approval successfully: '+result.isSuccess());

}
}

 

 

Javascript&colon;

 

{!REQUIRESCRIPT("/soap/ajax/24.0/connection.js")} 
{!REQUIRESCRIPT("/soap/ajax/24.0/apex.js")} 
sforce.apex.execute("SAPRequest","SendApprovalRequest", {id:"{!Account.Id}"}); 
window.alert("Record sent for approval" );

 

 

But when I click the SAPRequest Button , I get this error in dialogue box:

 

A problem with OnClick JavaScript for this button or link was encountered:

{faultcode:'soapenv:client',
faultstring:'System.DMLException:Process failed.First
exception on row 0,first error :REQUIRED_FIELD_MISSING,
missing required field;[]

class.SAPRequest.SendApprovalRequest: line 9, column 1',}

 

Please help me in fixing this . I will really be grateful to you guys..

 

Regards

I'd like to have a program that would automatically connect all contacts associated with an account to an opportunity as contact roles. I already know that if you create an opportunity from a contact, that the contact is assigned as the contact role. However, I have multiple contacts associated with some of my accounts and I need them to be connected to the opportunity as well. I've created a flow to make opportunity entry easier for the office staff, however getting them to remember to go back and add the contact roles after they have created the opportunities is a pain. It would be so much nicer if this could be done behind the scenes with programing.  Is it possible to do this with a flow? I'm using the desktop flow developer, and I see you can make a data source/target with an opportunitycontactrole table. But I'm not sure how to go about adding this to my flow. I'm assuming I'd have to add another lookup element, have the person find the contact to attach, selected it and assign the role.  The problem with this, is that the operator, has to know who to add to the opportunity, which opens up a possbility of adding the wrong people. If there was a way to make it automatic, it would remove the potential for operator error.