• 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;

}
}
  • February 22, 2017
  • Like
  • 0
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....
 
  • February 21, 2017
  • Like
  • 0
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..
  • February 10, 2017
  • Like
  • 0
Hi,

I am an Admin trying to learn how to write a trigger but am totally stumped trying to do this one.

I have a Parent Object: which contains fields for Start Date, Number of Months and Cost.  Once this is entered an End Date is calculated (using the Start Date * Number of Months) and also the Cost Per Month is calculated (using the Cost / Number Of Months).  Then I have a Child Object I want to insert records into.

What I would like to do is write a trigger which fires after the Parent record is entered to insert a number of Child records.  The number of Child records is basically one for each month between the start date and end date and also include the cost per month in each record.

So for example the parent record is; -
Start Date -  01/01/2016
End Date - 01/05/2016
Cost - 1000
Number of months - 4
Cost Per Month - 250

Trigger inserts 4 Child records, one for January starting on the start date then one for february, March and April all with a cost of 250

Later on I want to allow the ability to update these dates on the parent and this refreshed the child records, but one thign at a tme.  This sounds wat too complicated for me so any help would be great

Thanks

 
  • January 05, 2017
  • Like
  • 0
Hi,

I am trying to create a custom button on the lead list view which will; -
check if any records are selected else send an error and then once records are selected check the value of a picklist and if its not the value I want, send an error message, else update the field.  So far I have the below but its ignoring my validation formula to check the picklist, I am not a coder of any sort and am trying to piece this together from what I have learnt so far but not sure I understad what I am missing...I think I need to somehow loop through all the records selected and check the value of the picklist?!?

Any help would be great

{!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({!ISPICKVAL(Lead.Lead_Lifecycle_Stage__c, 'New Lead')} || {!ISPICKVAL(Lead.Lead_Lifecycle_Stage__c, 'Active')} || {!ISPICKVAL(Lead.Lead_Lifecycle_Stage__c, 'Engaged')} || {!ISPICKVAL(Lead.Lead_Lifecycle_Stage__c, 'Industry Influencer')} || {!ISPICKVAL(Lead.Lead_Lifecycle_Stage__c, 'Recycled')} || {!ISPICKVAL(Lead.Lead_Lifecycle_Stage__c, 'Disqualified')}) { 
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.Lead_Lifecycle_Stage__c = "Sales Accepted Lead (SAL)"; 

newRecords.push(l); 

result = sforce.connection.update(newRecords); 
parent.window.location.reload(); 

}
  • November 14, 2016
  • Like
  • 0
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();
}
}
  • November 10, 2016
  • Like
  • 0
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
  • November 08, 2016
  • Like
  • 0
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
  • September 16, 2016
  • Like
  • 0
 Hi,

I am relavively new to apex and triggers and this may sound a silly question.  How do I now make amendments to an existing class i have already deployed in production?
Do I amend it in sandbox and deploy the same class in a change set and it overrides the existing one?

Thanks
  • September 15, 2016
  • Like
  • 0
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
Hi,

I have 4 charts in visualforce page which I have put on the page layout of a custom object.  When a user clicks on the chart, It opens in the small visualforce window on the page, rather then oprning the filtered report in a new window....

How can I click on a chart and it opens the report in a new window, filtered.  Here is what I have so far, bearing in mind I am new to any sort of coding.  The below shows the code for the 4 charts that are on the page with filters.  I want to click on any chart and that chart opens up the full report filtered
Thanks

<apex:page standardController="pse__Proj__c">     
    <apex:pageBlock >
            <apex:pageBlockSection columns="4">        
                 <analytics:reportChart reportId="00Ow0000006woMg"
                     filter="{column:'FK_NAME',operator:'equals',value:'{!pse__Proj__c.Name}'}"
                     size="small" cacheResults="false">
                 </analytics:reportChart> 

                 <analytics:reportChart reportId="00Ow0000006woN0"
                     filter="{column:'FK_NAME',operator:'equals',value:'{!pse__Proj__c.Name}'}"
                     size="small" cacheResults="false">
                 </analytics:reportChart>

                 <analytics:reportChart reportId="00Ow0000006woMv"
                     filter="{column:'FK_NAME',operator:'equals',value:'{!pse__Proj__c.Name}'}"
                     size="small" cacheResults="false">
                 </analytics:reportChart> 
                         
                 <analytics:reportChart reportId="00O7E000000OJLH"
                     filter="{column:'CUST_NAME',operator:'equals',value:'{!pse__Proj__c.Name}'}"
                     size="small" cacheResults="false">
                 </analytics:reportChart>                                               
          </apex:pageblocksection>
    </apex:pageBlock>
</apex:page>
Hi,

I am very new to visualforce and apex and trying to learn!

I have created a page with 4 charts on it which will go on the detail of a custom object.  Here is the code so far: -

<apex:page standardController="pse__Proj__c">     
    <apex:pageBlock >
            <apex:pageBlockSection columns="4">        
                 <analytics:reportChart reportId="00Ow0000006woMg"
                     filter="{column:'FK_NAME',operator:'equals',value:'{!pse__Proj__c.Name}'}"
                     size="small" cacheResults="false">
                 </analytics:reportChart> 

                 <analytics:reportChart reportId="00Ow0000006woN0"
                     filter="{column:'FK_NAME',operator:'equals',value:'{!pse__Proj__c.Name}'}"
                     size="small" cacheResults="false">
                 </analytics:reportChart>

                 <analytics:reportChart reportId="00Ow0000006woMv"
                     filter="{column:'FK_NAME',operator:'equals',value:'{!pse__Proj__c.Name}'}"
                     size="small" cacheResults="false">
                 </analytics:reportChart> 
                         
                 <analytics:reportChart reportId="00O7E000000OJLH"
                     filter="{column:'CUST_NAME',operator:'equals',value:'{!pse__Proj__c.Name}'}"
                     size="small" cacheResults="false">
                 </analytics:reportChart>                                               
          </apex:pageblocksection>
    </apex:pageBlock>
</apex:page>

This looks good and shows 4 charts in line.

What I am trying to do is if a user clicks on one of the charts it opens the report in a new window (filtered as i've set it).  Currently when I click on a chart on the page it opens the report in the existing visualforce window which is annoying

thanks for any help

Nick
 
Hi,
I created a related list of Opportuinity Approval History, purely to remove the Submit for approval button.

Now this sits in the detail of the opportnuity page but when someone clicks on the Recall/Approve/Reject links it opens the page within the visualforce and not in a new window.
Does anyone know how I can open these links in a new tab or page
Thanks

Code:
<apex:page StandardController="Opportunity">
      <apex:relatedList list="ProcessSteps" ></apex:relatedList>
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script> 
<script>

 $(document).ready(function() {  
 $("input[name='piSubmit']").hide();
        }); 
 </script>
</apex:page>
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
 
  • April 26, 2016
  • Like
  • 0
Hi,

I have a custom button on opportunities which when clicked runs approval processes depending on fields creitera.  I am trying to check if certain fields are filled out before the button is clicked and getting stuck on a multiple if statement with AND all being true.  Basically if a URL field is blank, a picklist is 'tender' and a number field is greater than 99999: -

if('{!Opportunity.Field_1__c}' == "" && '{!Opportunity.Field_2__c}' == "Tender" && '{!Opportunity.Field_3__c}' > 99999) {
     alert('You need to enter the Final Pricing Sharepoint URL for this Tender before submitting for approval');
} else {

Field_1__c - URL field
Field _2__c - Picklist
Field_3__c - Number field

I get no errors on the Java and also there is no error message shows when the button is clicked and all of the above is met

Any Ideas...
Thanks
 
  • March 09, 2016
  • Like
  • 0
Hi,
I am trying to update a newly created quote with the line items from the opportuntiy it was created on.

This is for annual opportunities for support contracts and I have used a flow to create the new opportunity when it reaches 30 days before its close date which works fine.  I then got stuck trying to create the quote, add the line items and also create a pdf template of the quote, so turned to try and do it via triggers.

So far, once the new opportunity is created, I have a trigger to create a new quote......how do I now update that quotes line items with the opportunity line items.  Heres what I have so far and an new to development with apex and struggling as can be seen withthe mess below of how far away I am...: -


trigger addquotelineitems on Quote (after insert) {

Quote qot =trigger.new[0];
 
Opportunity oppId=[select id from Opportunity where id=:qot.OpportunityId];
 
List<OpportunityLineItem> opplines=[select id, quantity, PriceBookEntry.Product2Id
from OpportunityLineItem where OpportunityId=:oppId.id];
 
    for(OpportunityLineItem oppline:opplines){
         
        QuoteLineItem qli = new QuoteLineItem();
        qli.UnitPrice = oppline.UnitPrice;
        qli.Product2Id = oppline.PriceBookEntry.Product2Id;
        qli.Quantity = oppline.Quantity;
        qli.Description = oppline.Description;
        insert qli;
    }
 
}

After that I need to create a quote pdf using a template, but no idea if this is possible let alone how its done, I guess via a class or some sort

Thanks
  • February 18, 2016
  • Like
  • 0
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
 
  • February 17, 2016
  • Like
  • 0
Hi,

I have a flow which creates a new opportuntiy and adds the opportunity line items.  What I would like is to have the new opportnuity name to contain the Account name - a few dates.  
The dates are fine and I can get the Account ID to show but I want the account name instead to appear.
  • February 12, 2016
  • Like
  • 0
HI,

I am new to apex and having ago at my first trigger.

We have a set of support contracts that need new opportunities each year and I would like to try and automate this so once an opporuntity is set to closed won, a new opportunity, with the type of 'renewal', creates a new opportunity and eventually a quote also...

I have tried my first trigger and test class as below and getting an error that no rows are found so think I maybe missing a select statement or somethign obvious: -

trigger NewOppAndQuote on Opportunity (After Insert, After Update) {

    List<Opportunity> ListOpp = New List<Opportunity>();
    for(Opportunity o  : Trigger.new)
    {
        If(o.Opportunity_Type__c == 'Contract Renewal' &&
           o.StageName == 'Won' &&
           o.Remaining_Opportunity_Days__c == 73) 
     {
     
     Opportunity OppNew = New Opportunity();
     OppNew.Name = 'Opportunity.Account + TODAY()';
     OppNew.StageName = 'Pipeline';
     OppNew.AccountId = o.AccountId;
     OppNew.Opportunity_Type__c = 'Contract Renewal';
     OppNew.Estimated_Value__c = 100;
     OppNew.Opportunity_Submission_Date__c = Date.TODAY();
     OppNew.CloseDate = Date.TODAY() + 365;
     OppNew.Probability__c = '80-100%';
     OppNew.Solution_Summary__c = 'Maintinence';
     OppNew.Description = 'Renewal Contract for the next financial year';
     OppNew.Outcome_Status__c = 'Bid Submission Approved';
     
         ListOpp.add(OppNew);
          }
       }
     if (listOpp.size() > 0)
     insert listOpp;
}

test class which errors no rows are found: -

@IsTest

Private Class testNewOppAndQuote {
    static testMethod void testNewOppAndQuote(){
    
    Account a = [select Id from Account];
    Opportunity o = new Opportunity();
    
    o.AccountId = a.Id;
    o.StageName = 'Pipeline';
    o.Name = 'Opportunity.Account + TODAY()';
    o.Opportunity_Type__c = 'Contract Renewal';
    o.Estimated_Value__c = 100;
    o.Opportunity_Submission_Date__c = Date.TODAY();
    o.CloseDate = Date.TODAY() + 365;
    o.Probability__c = '80-100%';
    o.Solution_Summary__c = 'Maintinence';
    o.Description = 'Renewal Contract for the next financial year';
    o.Outcome_Status__c = 'Bid Submission Approved';
    
    insert o;
    
}

}

Any help appreciated and also any useful books or sourced to learn this a bit more is also good as although this is not workingI am enjoying doing it
Thanks
  • February 09, 2016
  • Like
  • 0
Hi,

I am new to Apex and visualforce and having ago!

I have managed to create a small visualforce page to show charts on my projects page which filters fine using the following code (section of): -
<apex:page StandardController="pse__Proj__c">
   <apex:pageblock >
        <apex:pageblockSection columns="4">
               <analytics:reportChart reportId="00OJ0000000hi2k" 
                    filter="{column:'pse__Proj__c.Name', operator:'equals', value:'{!pse__Proj__c.Name}'}" size="small">
        </analytics:reportChart>

When I click on this it opens the report within the small visualforce section and I would like this chart, when clicked to open in a new window, or even in a new tab.

Do I need a controller for this or is it simple code like open.window...parent etc ...
Thanks

Me
  • February 05, 2016
  • Like
  • 1
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;

}
}
  • February 22, 2017
  • Like
  • 0
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....
 
  • February 21, 2017
  • Like
  • 0
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..
  • February 10, 2017
  • Like
  • 0
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();
}
}
  • November 10, 2016
  • Like
  • 0
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
  • November 08, 2016
  • Like
  • 0
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
  • September 16, 2016
  • Like
  • 0
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
 
  • April 26, 2016
  • Like
  • 0
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
 
  • February 17, 2016
  • Like
  • 0

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.