• pmozz01
  • NEWBIE
  • 50 Points
  • Member since 2004

  • Chatter
    Feed
  • 2
    Best Answers
  • 2
    Likes Received
  • 0
    Likes Given
  • 35
    Questions
  • 54
    Replies

I need to have a validation rule that does the following:

 

If  picklist field Type=Claim*, then require that picklist field Resolution, picklist field Product Quantity and number field Amount are completed. I have put into place the validation rule below, however it does not let me save even if all 4 fields have values in it.  I think it is the way the field Type=Claim* is written, but I have not been successful in figuring this out.

 

Thanks!

 

AND(
OR(
(ISPICKVAL( Type, "Claim*")),
ISPICKVAL ( Resolution__c , ""),
ISPICKVAL( Product_Size__c , ""),
(Amount__c <> 0)))

 

I am trying to create a formula field that takes a text field and only displays the values after the hyphen.  For example, the text field contains XXX XX-ZZZ ZZZZ.  I only want the values ZZZ ZZZZ and want to remove the hyphen and everything before it.  This is the formula I have tried but it does not find the hyphen"

 

TRIM(RIGHT(Owning_Org__c, FIND("-",Owning_Org__c)))

 What this formula gives me is:  XX-ZZZ ZZZZ.  To complicate this further, the text is not the same length after or before the hyphen.  Any ideas on how to accomplish would be much appreciated!!!

I have previously posted a request for help, received a reply, but am still unable to get this code to work.  What is happening is as soon as the opportunity custom clone button is clicked the new opportunity clone is created and, if someone cancels, the clone remains and does not rollback.  As I click the custom clone button to clone an opportunity, I see the new opportunity created in the sidebar "Recent Items" list. 

 

I would greatly appreciate some help with this.  I have something wrong with my savepoint that I cannot get it to rollback.

 

Thanks!

 

public class OppCloneController {  
    private ApexPages.StandardController controller {get; set;}  
//DECLARE SAVEPOINT AS INSTANCE VARIABLE   
    public Savepoint sp;
    public Opportunity opp {get;set;} 
    public List<OpportunityLineItem> items = new List<OpportunityLineItem>();
    Schema.DescribeSObjectResult R = Opportunity.SObjectType.getDescribe();
    List<Schema.RecordTypeInfo> RT = R.getRecordTypeInfos();
    
    // set the id of the record that is created -- ONLY USED BY THE TEST CLASS  
    public ID newRecordId {get;set;}  

//OVERRIDE THE DEFAULT CANCEL METHOD
public PageReference cancel()
{
 
Database.rollback(sp);

return null;
 
}
     // initialize the controller  
    public OppCloneController(ApexPages.StandardController controller) {  
     //initialize the standard controller  
      this.controller = controller;  
    // load the current record  
         opp = (Opportunity)controller.getRecord(); 
            // setup the save point for rollback  
         sp = Database.setSavepoint(); 
     }  
    
        
    // method called from the VF's action attribute to clone the opp 
    public PageReference cloneWithItems() {  
 
        Opportunity newOP;  
         try {  
          //copy the opportunity - ONLY INCLUDE THE FIELDS YOU WANT TO CLONE  
             opp = [select Id, Name, Account.Name, AccountID, StageName, CloseDate, OwnerID, Type_of_Job__c, 
             Invoice_Requirements__c, Customer_Account__c, Contact_Name__c, Customer_E_mail__c, RecordTypeID,
             Phone__c, fax__c, Pricebook2Id
             from Opportunity where id = :opp.id]; 
             
 
             newOP = opp.clone(false);  
           //check to see if the opportunity name contains DTV or DirecTV, if so apply the appropriate record type,
           //otherwise use standard record type
                          
                    
   
                      // VALUE MAPPING 
            newOp.Name = opp.Name;
            newOp.Account.Name = opp.Account.Name;     
            newOp.AccountId = opp.AccountId;
            newOp.CloseDate = opp.CloseDate;
            newOp.StageName = 'New Work Order';
            newOp.OwnerID = opp.OwnerID;
            newOp.Type_of_Job__c = opp.Type_of_Job__c;
            newOp.Invoice_Requirements__c = opp.Invoice_Requirements__c;
            newOp.Customer_Account__c = opp.Customer_Account__c;
             newOp.RecordTypeId = opp.RecordTypeId;      
            newOp.Contact_Name__c = opp.Contact_Name__c;
            newOp.Customer_E_mail__c = opp.Customer_E_mail__c;
            newOp.Phone__c = opp.Phone__c;
            newOp.fax__c = opp.fax__c;
            newOp.Pricebook2Id = opp.Pricebook2Id;
            
             If (newOp.Name.contains('DirecTV'))
            newOp.RecordTypeId = [Select Id From RecordType RT Where RT.Name='DTV New Standard' limit 1].Id;
  
            else if (newOp.Name.contains('DTV'))
            newOp.RecordTypeId = [Select Id From RecordType RT Where RT.Name='DTV New Standard' limit 1].Id;
             else 
                newOp.RecordTypeID = [Select ID From RecordType r Where r.Name='New Standard' limit 1].ID;
                
                   insert newOP;  
             // set the id of the new opp created for testing  
              newRecordId = newOP.id;  
 
  // copy over the line items - ONLY INCLUDE THE FIELDS YOU WANT TO CLONE 
               
               for(OpportunityLineItem oli : [Select ID, OpportunityID,  
               UnitPrice, Quantity, PricebookEntryID
               
               from OpportunityLineItem oliList where OpportunityID = :opp.id]
               )
           
               {
               OpportunityLineItem newOli = new OpportunityLineItem();
                   newOli.PricebookEntryID = oli.PricebookEntryID;
                   newOli.Quantity = oli.Quantity;
                   newOli.UnitPrice = oli.UnitPrice;
                   newOlI.OpportunityID=newOP.id;
              
                   items.add(newOli);
                   } //end loop
                   
                   insert items;
           
         } catch (Exception e){  
              // roll everything back in case of error  
             Database.rollback(sp); 
             //delete newOp; 
             ApexPages.addMessages(e);
             opp = opp.clone(false);


  
             return null;  
         }  
        return new PageReference('/'+newOp.id+'/e?retURL=%2F'+newOp.id);  
     }  
    
 }

 

 

I am not sure what I am doing wrong with my savepoint.  It seems no matter where I put it, the cloned opportunity still saves despite the user clicking cancel.  Is there something else that I am missing?  Should I have a custom cancel method in my VF page? 

<apex:page standardController="Opportunity" extensions="OppCloneController" 
    action="{!cloneWithItems}">  
    <apex:pageMessages />  

</apex:page>

 

 

 

Thanks!

Pat

 

 

public class OppCloneController {  


    private ApexPages.StandardController controller {get; set;}  

    public Opportunity opp {get;set;} 
    public List<OpportunityLineItem> items = new List<OpportunityLineItem>();
    Schema.DescribeSObjectResult R = Opportunity.SObjectType.getDescribe();
    List<Schema.RecordTypeInfo> RT = R.getRecordTypeInfos();
    

    // set the id of the record that is created -- ONLY USED BY THE TEST CLASS  

    public ID newRecordId {get;set;}  

     // initialize the controller  

    public OppCloneController(ApexPages.StandardController controller) {  

     //initialize the standard controller  

      this.controller = controller;  

    // load the current record  

         opp = (Opportunity)controller.getRecord(); 
          


     }  

    // setup the save point for rollback  
    
        Savepoint sp = Database.setSavepoint();
        
    // method called from the VF's action attribute to clone the opp 

    public PageReference cloneWithItems() {  



        Opportunity newOP;  


         try {  


          //copy the opportunity - ONLY INCLUDE THE FIELDS YOU WANT TO CLONE  

             opp = [select Id, Name, Account.Name, AccountID, StageName, CloseDate, OwnerID, Type_of_Job__c, 
             Invoice_Requirements__c, Customer_Account__c, Contact_Name__c, Customer_E_mail__c, RecordTypeID,
             Phone__c, fax__c, Pricebook2Id
             from Opportunity where id = :opp.id]; 
             
 
             newOP = opp.clone(false);  
           //check to see if the opportunity name contains DTV or DirecTV, if so apply the appropriate record type,
           //otherwise use standard record type
                          
                    
   
                      // VALUE MAPPING 

            newOp.Name = opp.Name;
            newOp.Account.Name = opp.Account.Name;     
            newOp.AccountId = opp.AccountId;
            newOp.CloseDate = opp.CloseDate;
            newOp.StageName = 'New Work Order';
            newOp.OwnerID = opp.OwnerID;
            newOp.Type_of_Job__c = opp.Type_of_Job__c;
            newOp.Invoice_Requirements__c = opp.Invoice_Requirements__c;
            newOp.Customer_Account__c = opp.Customer_Account__c;
             newOp.RecordTypeId = opp.RecordTypeId;      
            newOp.Contact_Name__c = opp.Contact_Name__c;
            newOp.Customer_E_mail__c = opp.Customer_E_mail__c;
            newOp.Phone__c = opp.Phone__c;
            newOp.fax__c = opp.fax__c;
            newOp.Pricebook2Id = opp.Pricebook2Id;
            
             If (newOp.Name.contains('DirecTV'))
            newOp.RecordTypeId = [Select Id From RecordType RT Where RT.Name='DTV New Standard' limit 1].Id;
  
            else if (newOp.Name.contains('DTV'))
            newOp.RecordTypeId = [Select Id From RecordType RT Where RT.Name='DTV New Standard' limit 1].Id;
             else 
                newOp.RecordTypeID = [Select ID From RecordType r Where r.Name='New Standard' limit 1].ID;
                
                   insert newOP;  

             // set the id of the new opp created for testing  

              newRecordId = newOP.id;  
 



  // copy over the line items - ONLY INCLUDE THE FIELDS YOU WANT TO CLONE 
               
               for(OpportunityLineItem oli : [Select ID, OpportunityID,  
               UnitPrice, Quantity, PricebookEntryID
               
               from OpportunityLineItem oliList where OpportunityID = :opp.id]
               )
           

               {
               OpportunityLineItem newOli = new OpportunityLineItem();
                   newOli.PricebookEntryID = oli.PricebookEntryID;
                   newOli.Quantity = oli.Quantity;
                   newOli.UnitPrice = oli.UnitPrice;
                   newOlI.OpportunityID=newOP.id;
              
                   items.add(newOli);
                   } //end loop
                   
                   insert items;
           
         } catch (Exception e){  

              // roll everything back in case of error  

             Database.rollback(sp);  
             ApexPages.addMessages(e);
             opp = opp.clone(false);
  
             return null;  

         }  
         
    

         return new PageReference('/'+newOp.id+'/e?retURL=%2F'+newOp.id);  

     }  

    

 }

 

 

The business' needs for their custom opprotunity cloning has changed and they need the cloned opportunity to be cloned to edit mode, with the correct Record Type based upon the opportunity name.  I am struggling on how to do this.    This is my code, but it generates errors on the if statement.  Should I be doing this in a different way?  Also, is there a conditional operator "like" that I can use for the opportunity name is like or the opportunity name contains?  Should I be doing 2 select statements?  Thanks for any suggestions.

 

 

public class OppCloneController {  

    private ApexPages.StandardController controller {get; set;}  

    public Opportunity opp {get;set;} 
    public List<OpportunityLineItem> items = new List<OpportunityLineItem>();
 

    // set the id of the record that is created -- ONLY USED BY THE TEST CLASS  

    public ID newRecordId {get;set;}  

     // initialize the controller  

    public OppCloneController(ApexPages.StandardController controller) {  

     //initialize the stanrdard controller  

      this.controller = controller;  

       // load the current record  

         opp = (Opportunity)controller.getRecord();  
     }  

    // method called from the VF's action attribute to clone the opp 

    public PageReference cloneWithItems() {  


          // setup the save point for rollback  

        Savepoint sp = Database.setSavepoint();  

        Opportunity newOP;  


         try {  


          //copy the opportunity - ONLY INCLUDE THE FIELDS YOU WANT TO CLONE  

             opp = [select Id, Name, Account.Name, AccountID, StageName, CloseDate, OwnerID, Type_of_Job__c, 
             Invoice_Requirements__c, Customer_Account__c, Contact_Name__c, Customer_E_mail__c, RecordTypeID,
             Phone__c, fax__c, Pricebook2Id
             from Opportunity where id = :opp.id]; 
 
 			
             newOP = opp.clone(false);  
           //check to see if the opportunity name contains DTV or DirecTV, if so apply the appropriate record type,
           //otherwise use standard record type
                         
             if (opp.Name = 'DirecTv' || 'DTV'){
             	newOpp.RecordTypeID = 'DTV New Standard';
                }else {
             	newOpp.RecordType = opp.RecordTypeId;
             }	
             		

 

 

I have working apex code to clone specific fields on an opportunity and opportunity line items.  I am now being asked to clone the opportunity, keeping it in edit mode, but changing the record type based on the name of the opportunity (before it opens in edit mode).  I am at a loss as to how to do this.  Would it just be an "if Opportunity Name contains blah blah, then record type id ='special rt' otherwise standard record type?

 

In addition (although I have not seen this happen), users claim that if they click on the clone button and then cancel instead of save, the cloned opportunity is kept anyway.  Any thoughts or ideas about this is appreciated!

 

Thanks!

 

 

I am attempting to write a trigger to add contacts that meet the qualifications, to a campaign as a campaign member.  I keep getting an error that I cannot seem to fix that says "AND operator can only be applied to Boolean expressions".  The line of code presenting the error is:

 

 

       if (account.RecordTypeId = '012800000007aDe' && contact.Email_Opt_In__c = 'true' && contact.CampaignMember.CampaignID != '70180000000jlhi' ) 

 

 

The rest of the code is posted below.  I appreciate any recommendations or explanations of this error.  Thanks!

 

 

trigger triggerContactCreateCampMember on Contact (after insert, after update) {

   List<CampaignMember> CampaignMember = new List<CampaignMember>();
   List<Contact> ContactsToAdd = new List<Contact>();
	
    Set<Id> conIds = new Set<Id>();
	 if(Trigger.isInsert || Trigger.isUpdate)
    //Store Contact ID
    for(Contact contact: Trigger.new)
    {
       if (account.RecordTypeId = '012800000007aDe' && contact.Email_Opt_In__c = 'true' && contact.CampaignMember.CampaignID != '70180000000jlhi' ) 
       conIds.add(contact.ID);
    }
		List<Contact> c = new List<Contact> ([SELECT c.Id,c.AccountId From Contact c
		WHERE Id IN :conIds]);

		for (Contact con : c) {

	if(conIds.size() > 0)
	
	{CampaignMember.add(new CampaignMember
		(      
                
                ContactId = c.Id,
                CampaignId = '70180000000jlhi'));

             
              insert CampaignMember;
        }
        }
}

 

 

My trigger is working the way I need it to EXCEPT I need to exclude opportunities that are closed from being updated regardless of the values of the workorder.  I cannot figure out how to include this.  This trigger is already in production and I urgently need to correct the issue as it is updating opportunities that were marked closed-won to the stage of job compled!  Any suggestions?

 

 

Trigger CheckOpportunityWorkorders on Work_Order__c (before insert, before update) {

    List<Opportunity> opportunitiesToUpdate = new List<Opportunity>();
	
    Set<Id> oppIds = new Set<Id>();
	 if(Trigger.isInsert || Trigger.isUpdate)
    //Store Opportunity Id for each Work_Order__c
    for(Work_Order__c workOrder : Trigger.new)
    {
       if (workOrder.stage__c == 'Work Order Closed - Quickbooks' ||  workOrder.stage__c == 'Job Completed' ) 
       
       
       oppIds.add(workOrder.Opportunity__c);
    }
    
	if(oppIds.size() > 0)
	{
		//Retrieve all the Opportunities and related Work Orders regardless the status
		List<Opportunity> opportunities = new List<Opportunity> ([SELECT Id, StageName, (SELECT Id, Opportunity__c, Stage__c FROM Work_Orders__r) FROM Opportunity WHERE Id IN :oppIds]);

		for (Opportunity opportunity : opportunities) {

			Boolean allCompleted = true;
			for(Work_Order__c workOrder:opportunity.Work_Orders__r)
			{	if(workOrder.stage__c != 'Work Order Closed - Quickbooks' && workOrder.stage__c != 'Job Completed')
				{					
					allCompleted = false;
					break;
				}
			}
			
			if(allCompleted == true) 
			{
				opportunity.StageName = 'Job Completed';
				opportunitiesToUpdate.add(opportunity);
			}
		}
	}
	
	if(opportunitiesToUpdate.size() > 0) 
	update opportunitiesToUpdate;
	
}

 

 

Our business has a functionality need that I am not sure is doable.  After identifying a subset of contractors from a proximity map, they would like to be able to (with a click of a button!) send an emai lto the subset list that is detailing fields from a custom object.  So far, this I think I can do with apex and visualforce.  They'd like a link or a button in the email that allows the contractor to accept a job (whoever pushes the button first), and then is able to view the job in our customer portal.  So, it seems a lot of things would have to happen here, although at this point, I am not sure what link or button functionality can be provided in an email that (1) makes the contractor who pushed the button/link the "owner" of the job, (2) makes the job visible to the contractor in the portal.  Has anyone run into anything similar?  I was thinking it would be similar to the functionality of the "stay in touch" button?

 

 

Hi All,

 

I am at the end of my patience with myself here, cause I cannot figure out what I am missing. 

 

This is a custom object, Work Order, that has a look up to an Opportunity.  There can be many Work Orders related to the same opportunity.

 

Trigger fires when

  • the Work Order stage field is updated to either one of the closed values;
  • if all of the Work Orders related to that opportunity are closed, then update the opportunity stage, if not, do nothing.

I can get this to save, run the test, but it never updates anything.  I have changed this code so many times, I have no idea where I am screwing up and would appreciate some pointer.

 

At present - I am getting an error on line 24:         Map <ID, Opportunity> updateOpps = new Map <ID, Opportunity> ([SELECT id, stageName, (select ID, Opportunity__c from Work_Orders__r)
        from Opportunity where id in :affectedOpps]);

 

Error reads:  IN Operator must be used with iterable expression.

 

I am stil very much a beginner, so please be explicit if you are telling me something I need to do:)

 

Thanks!!!!

 

 

Trigger CheckOpportunityWorkorders on Work_Order__c (after insert, after update) {

   set<id> oppids = new set<id>();

     	
	    if(Trigger.isInsert || Trigger.isUpdate)
   		    	for (Work_Order__c wo: Trigger.new) {
            if (wo.stage__c == 'Work Order Closed - Quickbooks' ||  wo.stage__c == 'Job Completed' ){
      		oppids.add(wo.Opportunity__c);
      		String oid = wo.Opportunity__c;
      		
 	    if(oppIDs .size() > 0) {
 
  Map <ID, Opportunity> affectedOpps = new Map <ID, Opportunity> ([select id, stageName, (select id, Opportunity__c from Work_Orders__r 
  	where Work_Order__c.stage__c != 'Work Order Closed - Quickbooks' OR stage__c != 'Job Completed') 
	from Opportunity where id in :oppids]);

	
	System.debug('Opportunity: '+affectedOpps.get(oid).StageName);     		
   

      	if (affectedOpps .size()==0){	
		
		Map <ID, Opportunity> updateOpps = new Map <ID, Opportunity> ([SELECT id, stageName, (select ID, Opportunity__c from Work_Orders__r)
		from Opportunity where id in :affectedOpps]);
		String upID = wo.Opportunity__c;
		 	if(updateOpps.containskey(upID))
		 	
 //       	d = updateOpps.get(upID);
				 
			upID.stageName = 'Job Complete';
			
			update updateOpps;
      	}
		
		
 
}
}
}
}

 

public with sharing class testCheckOpportunityWorkOrders {

    static testMethod void myTest() {

		Account a = new Account(name='test', type = 'customer');
		insert a;
       //Insert a test opportunity
		
       Opportunity o = new Opportunity();
       o.AccountId = a.id;
       o.StageName='Target';
       o.Name='test';
       o.closeDate=Date.today();

       insert o;
       
       system.debug('opportunity id' + Opportunity.ID);
       
         //Insert a Work_Order

       Work_Order__c wo = new Work_Order__c();

       wo.Opportunity__c = o.id;
       
       wo.Stage__c = 'Job Completed';
       wo.Close_Date_WO__c=Date.today();

  
       insert wo;
 		system.debug('workorder' + wo.ID);
 		      
       Work_Order__c ww = new Work_Order__c();

       ww.Opportunity__c = o.id;
       
       ww.Stage__c = 'Return Trip Needed';
       ww.Close_Date_WO__c=Date.today();
  
       insert ww;
       
       ww.Stage__c = 'Work Order Closed - Quickbooks';
       update ww;
       
       wo.Stage__c = 'Work Order Closed - Quickbooks';
       update wo;
       
		system.debug('workorder' + ww.ID + ww.Stage__c);
		
       Opportunity updated_Opportunity = [SELECT ID, WO_Count__c FROM Opportunity WHERE Id = :o.Id];

       //Verify that the values of the opp were changed by the trigger
       
  //System.assertEquals(opportunity, [Select WO_Count__c from Opportunity Where ID = :o.ID].wo_count__c);
  
 
     }
static testMethod void testBulkInsert() {

  List<Opportunity> opps = new List<Opportunity>();
  
 }

}

 

 

 

Good morning, I am hoping someone can set me straight on what I am attempting to do here. 

 

  • I have a custom object Work Order that has a lookup relationship to Opportunity. 
  • There can be many Work Orders related to one opportunity. 
  • On Opportunity, I have a custom field that is populated via a trigger to count all of the Work Orders associated

I have a second trigger that is meant to

  • identify those Work Orders that are closed and,
  • if the count of Closed Work Orders = the count of all Work Orders
  • update the Opportunity Stage to Completed

I am getting lost on how to write the logic to compare the COUNT of the closed Work Orders to the value in the Opportunity field.  I'd appreciate any help!!!  Thanks.

 

trigger trigWorkorderCloseOpp on Work_Order__c (after insert, after update) {

    //************************************************
    // Build a LIST of Opportunity ID's that may
    // need closing
    //************************************************

	set <id> oppIDs = new set <id>();
	list <Opportunity> opportunity = [SELECT ID FROM Opportunity WHERE ID in:oppIDs];

	
    if(Trigger.isInsert || Trigger.isUpdate){
        for(Work_Order__c w : trigger.new){
            if(w.Opportunity__c != null && w.stage__c == 'Work Order Closed - Quickbooks')
            {oppIDs.add(w.Opportunity__c);
            } else if (w.Opportunity__c != null && w.stage__c == 'Job Completed')
            {oppIDs.add(w.Opportunity__c);
            
            }

	        }

      // INSERT/UPDATE Trigger

    if(Trigger.isDelete || Trigger.isUpdate){
        for(Work_Order__c w : trigger.old){
           if(w.Opportunity__c != null && w.stage__c == 'Work Order Closed - Quickbooks')
            {oppIDs.add(w.Opportunity__c);
            } else if (w.Opportunity__c != null && w.stage__c == 'Job Completed')
            {oppIDs.add(w.Opportunity__c);
             }
        }
    }

    if(oppIDs .size() > 0) {
    
        Map<ID, Opportunity> oppMap = new Map<ID, Opportunity>([Select id, WO_Count__c, StageName from Opportunity Where Id in :oppIds]);  	
    	
    	Opportunity d = null;
    		
    	for (AggregateResult ar : [SELECT ID, Opportunity__c, COUNT(Id)total FROM Work_Order__c WHERE Opportunity__c in: oppIds GROUP BY Opportunity__c])
    	
    		{
    			String dID = (String)dr.get('Opportunity__c');
    			Integer a = Integer.valueOf(ar.get('total'));
    			if(oppMap.get(dID) == null)
    			 d = new Opportunity(ID=string.valueOf(ar.get('Opportunity__c')));
    			
    			else
    			if(oppMap.containskey(dID)&& a.equals(Opportunity.WO_Count__c))
        		d = oppMap.get(dID);
    			
    			
    		}

    		d = opps.get(dID);
    		d.StageName = 'Job Completed';
    		
    		update opps.values();
    		
    }
    }
}		

 

 

 

I have a trigger that updates 1 field on the opportunity that is a summary of several fields on a custom object that has a lookup relation.  I cannot change this to a master-detail relationship, because the custom object needs exposure in the customer portal.  The problem I am running into that there are several validation rules running on the opportunity that disallow saving.  I cannot figure out how to get this field updated on the opportunity while leaving the validation rules in place.  Any ideas?  Its like I want to tell the valuation rule to ignore the rule if the update is due to the trigger.

I am new to apex code but have written a trigger that updates a custom revenue field on the opportunity and that works as desired until the opportunity being updated has a close date in the past.  This is due to a validation rule that does fires whenever the close date is less than today.  I see that this is a common issue by searching these boards, but I have not found a solution.  Is there way to writer the validation rule so that it does not fire if a particular field is being updated, or if the update is caused by the trigger?

 

With my limited knowledge, I cannot figure out a way around this error and subsequently no update by the trigger.  I'd really appreciate some ideas on how to manage this issue.  Thanks!

 

This is the validation rule:

 

AND(
OR (
ISPICKVAL(StageName ,"Job Dispatched"),
ISPICKVAL(StageName ,"Waiting for Approval"),
ISPICKVAL(StageName ,"Searching for sub"),
ISPICKVAL(StageName ,"Waiting for Approval"),
ISPICKVAL(StageName ,"Approval Received - Need Contractor"),
ISPICKVAL(StageName ,"Priority - Searching for Sub"),
ISPICKVAL(StageName ,"Proposal/Price Quote")),
CloseDate < TODAY(),
IF(OR(ISNEW(), ISNULL(Id)), if(ConnectionReceivedId =null, TRUE, FALSE),NOT(AND(ISCHANGED(ConnectionReceivedId), NOT(ConnectionReceivedId = null)))),



NOT(Contains($User.Alias, "pnet"))
)

 

 

My trigger is working as desired however, I have issues with not enough test coverage.  I would appreciate some suggestions on how to test some of this code.  The lines NOT COVERED are those in Red and large font below.  I am really unsure how to procedd with testing these lines of code???

 

 

 

 

trigger triggerWorkorderOppUpdate on Work_Order__c (after insert, after update, after delete) {

//************************************************
// Build a LIST of Opportunity ID's that will
// need recalculating
//************************************************
set <id> oppIDs = new set <id>();
list <Opportunity> opportunity = [SELECT ID FROM Opportunity WHERE ID in:oppIDs];

if(Trigger.isInsert || Trigger.isUpdate){
for(Work_Order__c w : trigger.new){
if(w.Opportunity__c != null){
if(!oppIDs.contains(w.Opportunity__c))
oppIDs.add(w.Opportunity__c);

}

}
}
// INSERT/UPDATE Trigger

if(Trigger.isDelete || Trigger.isUpdate){
for(Work_Order__c w : trigger.old){
if(w.Opportunity__c != null){
if(!oppIDs.contains(w.Opportunity__c))
oppIDs.add(w.Opportunity__c);

}
// w = [select ID, Opportunity__c from Work_Order__c where Opportunity__c in :oppIds];
}
} // DELETE/UPDATE Trigger

if(oppIDs .size() > 0) {

Map<ID, Opportunity> opps = new Map<ID, Opportunity>([Select id, Estimated_Cost__c from Opportunity Where Id in :oppIds]);

Opportunity d = null;

for (AggregateResult dr : [SELECT Opportunity__c, SUM(Cost_WO__c) SubPO FROM Work_Order__c WHERE Opportunity__c in :oppIds GROUP BY Opportunity__c]) {


String dID = (String)dr.get('Opportunity__c');
//get record or create one

if(opps.get(dID) == null)
d = new Opportunity (ID=dID,
Estimated_Cost__c = 0);

else
if(opps.containskey(dID))
d = opps.get(dID);


// update the summary total fields on the opportunity
Decimal po = (Decimal)dr.Get('SubPO');

d.Estimated_Cost__c = po;

opps.put(dID, d);
}
//commit the changes to Salesforce

update opps.values();

}

}

 

 

Test Code

 

 

public with sharing class testTriggerWorkorderOppUpdate {



    static testMethod void myTest() {

       //Insert a test opportunity
		Account a = [select Id, account.OwnerId, account.Name from Account limit 1];
		system.debug('Account' + Account.ID);
		
       Opportunity o = new Opportunity();
       o.OwnerID = a.OwnerId;
       o.AccountId = a.id;
       o.StageName='Target';
       o.Name='TestOp';
       o.closeDate=Date.today();

       insert o;
       system.debug('opportunity id' + Opportunity.ID);
       
         //Insert a Work_Order

       Work_Order__c wo = new Work_Order__c();

       wo.Opportunity__c = o.id;
       
       wo.Close_Date_WO__c = Date.today();

       wo.Cost_WO__c = 55.00;

 
       insert wo;
       
       wo.Cost_WO__c = 75.00;
       update wo;
       
		system.debug('workorder' + wo.ID);
		
       Opportunity updated_Opportunity = [SELECT ID, Estimated_Cost__c FROM Opportunity WHERE Id = :o.Id];

       //Verify that the values of the opp were changed by the trigger
       
  System.assertEquals(wo.Cost_WO__c,[Select Estimated_Cost__c From Opportunity Where Id = :o.Id].Estimated_Cost__c);
       
 
     }
static testMethod void testBulkInsert() {

  List<Opportunity> opps = new List<Opportunity>();
  
 }
}

 

 

Not sure what I am doing wrong here.  This is my first attempt of Aggregate functions.  I have a custom Work Order that contains a lookup relationship to an opportunity.  There can be multiple work orders on a single opportunity.  I need specific $ value fields on the work order to be summed and updated on the opportunity.  I cannot get any update to occur at all.  The test runs fine and I have 100% coverage, so I must be writing this wrong :(

 

Here is my trigger:

 

 

trigger triggerWorkorderOppUpdate on Work_Order__c (after insert, after update, after delete) {

    Set<String> oppIDs = new Set<String>();

    //************************************************
    // Build a LIST of Opportunity ID's that will
    // need recalculating
    //************************************************
    if(Trigger.isInsert || Trigger.isUpdate){
        for(Work_Order__c w : trigger.new){
            if(w.Opportunity__c != null){
                if(!oppIDs.contains(w.Opportunity__c)) oppIDs.add(w.Opportunity__c);
            }
        }
    }  // INSERT/UPDATE Trigger

    if(Trigger.isDelete || Trigger.isUpdate){
        for(Work_Order__c w : trigger.old){
            if(w.Opportunity__c != null){
                if(!oppIDs.contains(w.Opportunity__c)) oppIDs.add(w.Opportunity__c);
            }
        }
    }  // DELETE/UPDATE Trigger

    if(oppIDs .size() > 0) {

        Map<ID, Opportunity> opps = new Map<ID, Opportunity>([
        	Select o.id, o.Total_Travel_Costs__c, o.Total_Out_of_Scope__c,o.Total_Hourly_Labor__c,
		 o.Total_Flat_Rate__c, o.Total_Materials__c
		 FROM Opportunity o
		 WHERE ID IN :oppIDs]);
        Opportunity d = null;

        for (AggregateResult dr : [SELECT Opportunity__c, SUM(Total_Travel_Costs__c) Travel, SUM(Total_Out_of_Scope__c)Oscope,
		SUM(Total_Hourly_Labor__c)Labor, SUM(Total_Flat_Rate__c) Flat, SUM(Total_Materials__c)Materials
        FROM Work_Order__c GROUP BY Opportunity__c]) {

            String dID = (string)dr.Get('Opportunity__c');
            if (opps.get(dID) != null)

               d = opps.get(dID);

            // update the total fields
            Decimal trv = (Decimal)dr.Get('Travel');
            Decimal scp = (Decimal)dr.Get('Oscope');
            Decimal lbr = (Decimal)dr.Get('Labor');
            Decimal flt = (Decimal)dr.Get('Flat');
            Decimal mat = (Decimal)dr.Get('Materials');
        }
	LIST<Opportunity> OppUpdate = new LIST<Opportunity>();
				for (Opportunity ou:opps.values()) {				
				
			d.Total_Travel_Costs__c = opps.get(ou.id).Total_Travel_Costs__c;
			d.Total_Out_of_Scope__c = opps.get(ou.id).Total_Out_of_Scope__c;
			d.Total_Hourly_Labor__c = opps.get(ou.id).Total_Hourly_Labor__c;	
			d.Total_Flat_Rate__c = opps.get(ou.id).Total_Flat_Rate__c;
			d.Total_Materials__c = opps.get(ou.id).Total_Materials__c;
						
        }

        //commit the changes to Salesforce
        update opps.values();

    }

}

 

 

Here is my test:

 

 

public with sharing class testTriggerWorkorderOppUpdate {



    static testMethod void myTest() {

       //Insert a test opportunity

       Opportunity test_opportunity = new Opportunity(StageName='Target',Name='TestOp', closeDate=Date.today());

       insert test_opportunity;
       
       //Insert a Work_Order

       Work_Order__c wo = new Work_Order__c();

       wo.Opportunity__c = test_opportunity.id;
       
       wo.Close_Date_WO__c = Date.today();

       wo.Travel_Cost_Total__c = 55.00;

       wo.Out_of_Scope_Total__c = 10.00;

  //     wo.Total_Hourly_Labor__c = '2.00';
       
  //     wo.Total_Flat_Rate__c = '0.00';

       insert wo;

       //Insert an Invoice with Line Items
       
       Tech_Invoice__c inv = new Tech_Invoice__c();
       inv.Invoice_Number__c = 'ABC123';
       inv.Work_Order__c = wo.id;
       
       insert inv;
       
       Invoice_Line_Item__c lih = new Invoice_Line_Item__c();
       lih.Contractor_Invoice__c = inv.id;
       lih.type__c = 'Hourly Labor';
       lih.Item_Name__c = 'item 1';
       lih.Quantity__c = 20;
       lih.unitprice__c = 5.00;
       insert lih;
       
      
       Invoice_Line_Item__c lim = new Invoice_Line_Item__c();
       lim.Contractor_Invoice__c = inv.id;
       lim.type__c = 'Materials';
       lim.Item_Name__c = 'item 2';
       lim.Quantity__c = 5;
       lim.unitprice__c = 3.00;
       insert lim;
        
     
       Invoice_Line_Item__c lit = new Invoice_Line_Item__c();
       lit.Contractor_Invoice__c = inv.id;
       lit.type__c = 'Travel';
       lit.Item_Name__c = 'item 3';
       lit.Quantity__c = .75;
       lit.unitprice__c = .32;
       insert lit;
     

       Opportunity updated_Opportunity = [SELECT ID, Total_Travel_Costs__c, Total_Out_of_Scope__c,
		Total_Hourly_Labor__c, Total_Flat_Rate__c FROM Opportunity WHERE Id = :test_opportunity.Id];

       //Verify that the values of the contact were changed by the trigger
 
     }

 }

 

Any assistance is greatly appreciated.

 

Hi, I am hoping someone here can help me to figure out the best way to accomplish this.  I have a custom object that is a child of the Opportunity.  I want to be able to expose that child object to multiple customer portal users, but cannot figure out a way to do this.  If I break the master-detail relation between the opportunity and the child, and create an object in between, how do I keep that relationship without forcing my users to create an additional object?  Has anyone had to do something like this in the past?  Thanks for any ideas!

 

Very similar to the VF Cookbook Opportunity Wizard example, I have created an opportunity creation wizard because my users complain about too many clicks when creating an opportunity, adding products, etc.  My question is when the user clicks on Save, I would like to save the opportunity but instead of redirecting to the saved opportunity detail, go directly to the standard add products page.  I do not want to add the button to the VF page, just redirect to the standard add products search functionality.

 

I have been trying to set the addProductsURL as the page reference after saving the opportunity and have tried it a couple of ways in my controller without success.

public PageReference addProductsURL(){ PageReference p = new PageReference('/'+SelectSearch?addTo={!Opportunity.ID} ); p.getParameters().put('addTo',opportunity.Id); p.setRedirect(true); return p; This is how I tried to return the addProductsURL after saving opportunity: PageReference addProduct = Page.addProductsURL; addProduct.getParameters().put('id',this.controller.getId()); addProduct.setRedirect(true); return addProduct;

 

Thanks!  Any ideas are appreciated :)

 

I have a problem trying to get the numbers to line up by decimal points in a column.  I have tried text align for the whole table as well as for each individual column with no success.  Any suggestions? I don't know javascript as someone else suggested.

 

Thanks!

Does anyone have a suggestion on how to align currency values in a pageBlockTable column?  I can only seem to get right, left, center , but cannot figure out how to get the decimal to align without throwing off the whole column from the header.

 

Thanks!

Pat

Hi, I need to return a value so that it looks like currency ($1.00), but instead end up with 1.0.  Can anyone help?

 

Thanks!

Pat

 

private static string DecimaltoCurrency(Decimal val) { if (val==0) return '0.00'; string str = val.divide(1,2,RoundingMode.HALF_UP).format()+'00'; integer dec = str.lastindexOf('.'); system.debug('-------DecimaltoCurrency: -str/dec/len------------->'+str + '/'+dec+'/'+str.length()); if (dec==-1 ) return str.substring(0,str.length()-2)+'.00'; //else if (dec==str.length()-1) return str+'0'; else return str.substring(0,dec+3); } public double getTotalAmount() { double rtn=0.00; system.debug('newItems:'+newItems); if (newItems!=null && newItems.size()>0) { for (LineItem li : newItems.values()) { if (li.item!=null) rtn+=(li.item.UnitPrice__c * li.item.Quantity__c); } }

 

 

 

I am not sure what I am doing wrong with my savepoint.  It seems no matter where I put it, the cloned opportunity still saves despite the user clicking cancel.  Is there something else that I am missing?  Should I have a custom cancel method in my VF page? 

<apex:page standardController="Opportunity" extensions="OppCloneController" 
    action="{!cloneWithItems}">  
    <apex:pageMessages />  

</apex:page>

 

 

 

Thanks!

Pat

 

 

public class OppCloneController {  


    private ApexPages.StandardController controller {get; set;}  

    public Opportunity opp {get;set;} 
    public List<OpportunityLineItem> items = new List<OpportunityLineItem>();
    Schema.DescribeSObjectResult R = Opportunity.SObjectType.getDescribe();
    List<Schema.RecordTypeInfo> RT = R.getRecordTypeInfos();
    

    // set the id of the record that is created -- ONLY USED BY THE TEST CLASS  

    public ID newRecordId {get;set;}  

     // initialize the controller  

    public OppCloneController(ApexPages.StandardController controller) {  

     //initialize the standard controller  

      this.controller = controller;  

    // load the current record  

         opp = (Opportunity)controller.getRecord(); 
          


     }  

    // setup the save point for rollback  
    
        Savepoint sp = Database.setSavepoint();
        
    // method called from the VF's action attribute to clone the opp 

    public PageReference cloneWithItems() {  



        Opportunity newOP;  


         try {  


          //copy the opportunity - ONLY INCLUDE THE FIELDS YOU WANT TO CLONE  

             opp = [select Id, Name, Account.Name, AccountID, StageName, CloseDate, OwnerID, Type_of_Job__c, 
             Invoice_Requirements__c, Customer_Account__c, Contact_Name__c, Customer_E_mail__c, RecordTypeID,
             Phone__c, fax__c, Pricebook2Id
             from Opportunity where id = :opp.id]; 
             
 
             newOP = opp.clone(false);  
           //check to see if the opportunity name contains DTV or DirecTV, if so apply the appropriate record type,
           //otherwise use standard record type
                          
                    
   
                      // VALUE MAPPING 

            newOp.Name = opp.Name;
            newOp.Account.Name = opp.Account.Name;     
            newOp.AccountId = opp.AccountId;
            newOp.CloseDate = opp.CloseDate;
            newOp.StageName = 'New Work Order';
            newOp.OwnerID = opp.OwnerID;
            newOp.Type_of_Job__c = opp.Type_of_Job__c;
            newOp.Invoice_Requirements__c = opp.Invoice_Requirements__c;
            newOp.Customer_Account__c = opp.Customer_Account__c;
             newOp.RecordTypeId = opp.RecordTypeId;      
            newOp.Contact_Name__c = opp.Contact_Name__c;
            newOp.Customer_E_mail__c = opp.Customer_E_mail__c;
            newOp.Phone__c = opp.Phone__c;
            newOp.fax__c = opp.fax__c;
            newOp.Pricebook2Id = opp.Pricebook2Id;
            
             If (newOp.Name.contains('DirecTV'))
            newOp.RecordTypeId = [Select Id From RecordType RT Where RT.Name='DTV New Standard' limit 1].Id;
  
            else if (newOp.Name.contains('DTV'))
            newOp.RecordTypeId = [Select Id From RecordType RT Where RT.Name='DTV New Standard' limit 1].Id;
             else 
                newOp.RecordTypeID = [Select ID From RecordType r Where r.Name='New Standard' limit 1].ID;
                
                   insert newOP;  

             // set the id of the new opp created for testing  

              newRecordId = newOP.id;  
 



  // copy over the line items - ONLY INCLUDE THE FIELDS YOU WANT TO CLONE 
               
               for(OpportunityLineItem oli : [Select ID, OpportunityID,  
               UnitPrice, Quantity, PricebookEntryID
               
               from OpportunityLineItem oliList where OpportunityID = :opp.id]
               )
           

               {
               OpportunityLineItem newOli = new OpportunityLineItem();
                   newOli.PricebookEntryID = oli.PricebookEntryID;
                   newOli.Quantity = oli.Quantity;
                   newOli.UnitPrice = oli.UnitPrice;
                   newOlI.OpportunityID=newOP.id;
              
                   items.add(newOli);
                   } //end loop
                   
                   insert items;
           
         } catch (Exception e){  

              // roll everything back in case of error  

             Database.rollback(sp);  
             ApexPages.addMessages(e);
             opp = opp.clone(false);
  
             return null;  

         }  
         
    

         return new PageReference('/'+newOp.id+'/e?retURL=%2F'+newOp.id);  

     }  

    

 }

 

 

Our business had a need to prevent closed-won opportunities from being edited or deleted by anyone, so I used a page layout with the edit and delete buttons removed, a "locked" record type and a workflow rule to change the record type whenever an opportunity was marked closed-won.  This is working fine for us, however I just learned that if anyone searches for the opportunity, they do see an edit button in the list view.  I currently have made all the fields read only so that they cannot be changed, but what would have been the better way to handle this requirement?

 

Thanks, I appreciate any advice.

I need to have a validation rule that does the following:

 

If  picklist field Type=Claim*, then require that picklist field Resolution, picklist field Product Quantity and number field Amount are completed. I have put into place the validation rule below, however it does not let me save even if all 4 fields have values in it.  I think it is the way the field Type=Claim* is written, but I have not been successful in figuring this out.

 

Thanks!

 

AND(
OR(
(ISPICKVAL( Type, "Claim*")),
ISPICKVAL ( Resolution__c , ""),
ISPICKVAL( Product_Size__c , ""),
(Amount__c <> 0)))

 

I am trying to create a formula field that takes a text field and only displays the values after the hyphen.  For example, the text field contains XXX XX-ZZZ ZZZZ.  I only want the values ZZZ ZZZZ and want to remove the hyphen and everything before it.  This is the formula I have tried but it does not find the hyphen"

 

TRIM(RIGHT(Owning_Org__c, FIND("-",Owning_Org__c)))

 What this formula gives me is:  XX-ZZZ ZZZZ.  To complicate this further, the text is not the same length after or before the hyphen.  Any ideas on how to accomplish would be much appreciated!!!

I am not sure what I am doing wrong with my savepoint.  It seems no matter where I put it, the cloned opportunity still saves despite the user clicking cancel.  Is there something else that I am missing?  Should I have a custom cancel method in my VF page? 

<apex:page standardController="Opportunity" extensions="OppCloneController" 
    action="{!cloneWithItems}">  
    <apex:pageMessages />  

</apex:page>

 

 

 

Thanks!

Pat

 

 

public class OppCloneController {  


    private ApexPages.StandardController controller {get; set;}  

    public Opportunity opp {get;set;} 
    public List<OpportunityLineItem> items = new List<OpportunityLineItem>();
    Schema.DescribeSObjectResult R = Opportunity.SObjectType.getDescribe();
    List<Schema.RecordTypeInfo> RT = R.getRecordTypeInfos();
    

    // set the id of the record that is created -- ONLY USED BY THE TEST CLASS  

    public ID newRecordId {get;set;}  

     // initialize the controller  

    public OppCloneController(ApexPages.StandardController controller) {  

     //initialize the standard controller  

      this.controller = controller;  

    // load the current record  

         opp = (Opportunity)controller.getRecord(); 
          


     }  

    // setup the save point for rollback  
    
        Savepoint sp = Database.setSavepoint();
        
    // method called from the VF's action attribute to clone the opp 

    public PageReference cloneWithItems() {  



        Opportunity newOP;  


         try {  


          //copy the opportunity - ONLY INCLUDE THE FIELDS YOU WANT TO CLONE  

             opp = [select Id, Name, Account.Name, AccountID, StageName, CloseDate, OwnerID, Type_of_Job__c, 
             Invoice_Requirements__c, Customer_Account__c, Contact_Name__c, Customer_E_mail__c, RecordTypeID,
             Phone__c, fax__c, Pricebook2Id
             from Opportunity where id = :opp.id]; 
             
 
             newOP = opp.clone(false);  
           //check to see if the opportunity name contains DTV or DirecTV, if so apply the appropriate record type,
           //otherwise use standard record type
                          
                    
   
                      // VALUE MAPPING 

            newOp.Name = opp.Name;
            newOp.Account.Name = opp.Account.Name;     
            newOp.AccountId = opp.AccountId;
            newOp.CloseDate = opp.CloseDate;
            newOp.StageName = 'New Work Order';
            newOp.OwnerID = opp.OwnerID;
            newOp.Type_of_Job__c = opp.Type_of_Job__c;
            newOp.Invoice_Requirements__c = opp.Invoice_Requirements__c;
            newOp.Customer_Account__c = opp.Customer_Account__c;
             newOp.RecordTypeId = opp.RecordTypeId;      
            newOp.Contact_Name__c = opp.Contact_Name__c;
            newOp.Customer_E_mail__c = opp.Customer_E_mail__c;
            newOp.Phone__c = opp.Phone__c;
            newOp.fax__c = opp.fax__c;
            newOp.Pricebook2Id = opp.Pricebook2Id;
            
             If (newOp.Name.contains('DirecTV'))
            newOp.RecordTypeId = [Select Id From RecordType RT Where RT.Name='DTV New Standard' limit 1].Id;
  
            else if (newOp.Name.contains('DTV'))
            newOp.RecordTypeId = [Select Id From RecordType RT Where RT.Name='DTV New Standard' limit 1].Id;
             else 
                newOp.RecordTypeID = [Select ID From RecordType r Where r.Name='New Standard' limit 1].ID;
                
                   insert newOP;  

             // set the id of the new opp created for testing  

              newRecordId = newOP.id;  
 



  // copy over the line items - ONLY INCLUDE THE FIELDS YOU WANT TO CLONE 
               
               for(OpportunityLineItem oli : [Select ID, OpportunityID,  
               UnitPrice, Quantity, PricebookEntryID
               
               from OpportunityLineItem oliList where OpportunityID = :opp.id]
               )
           

               {
               OpportunityLineItem newOli = new OpportunityLineItem();
                   newOli.PricebookEntryID = oli.PricebookEntryID;
                   newOli.Quantity = oli.Quantity;
                   newOli.UnitPrice = oli.UnitPrice;
                   newOlI.OpportunityID=newOP.id;
              
                   items.add(newOli);
                   } //end loop
                   
                   insert items;
           
         } catch (Exception e){  

              // roll everything back in case of error  

             Database.rollback(sp);  
             ApexPages.addMessages(e);
             opp = opp.clone(false);
  
             return null;  

         }  
         
    

         return new PageReference('/'+newOp.id+'/e?retURL=%2F'+newOp.id);  

     }  

    

 }

 

 

The business' needs for their custom opprotunity cloning has changed and they need the cloned opportunity to be cloned to edit mode, with the correct Record Type based upon the opportunity name.  I am struggling on how to do this.    This is my code, but it generates errors on the if statement.  Should I be doing this in a different way?  Also, is there a conditional operator "like" that I can use for the opportunity name is like or the opportunity name contains?  Should I be doing 2 select statements?  Thanks for any suggestions.

 

 

public class OppCloneController {  

    private ApexPages.StandardController controller {get; set;}  

    public Opportunity opp {get;set;} 
    public List<OpportunityLineItem> items = new List<OpportunityLineItem>();
 

    // set the id of the record that is created -- ONLY USED BY THE TEST CLASS  

    public ID newRecordId {get;set;}  

     // initialize the controller  

    public OppCloneController(ApexPages.StandardController controller) {  

     //initialize the stanrdard controller  

      this.controller = controller;  

       // load the current record  

         opp = (Opportunity)controller.getRecord();  
     }  

    // method called from the VF's action attribute to clone the opp 

    public PageReference cloneWithItems() {  


          // setup the save point for rollback  

        Savepoint sp = Database.setSavepoint();  

        Opportunity newOP;  


         try {  


          //copy the opportunity - ONLY INCLUDE THE FIELDS YOU WANT TO CLONE  

             opp = [select Id, Name, Account.Name, AccountID, StageName, CloseDate, OwnerID, Type_of_Job__c, 
             Invoice_Requirements__c, Customer_Account__c, Contact_Name__c, Customer_E_mail__c, RecordTypeID,
             Phone__c, fax__c, Pricebook2Id
             from Opportunity where id = :opp.id]; 
 
 			
             newOP = opp.clone(false);  
           //check to see if the opportunity name contains DTV or DirecTV, if so apply the appropriate record type,
           //otherwise use standard record type
                         
             if (opp.Name = 'DirecTv' || 'DTV'){
             	newOpp.RecordTypeID = 'DTV New Standard';
                }else {
             	newOpp.RecordType = opp.RecordTypeId;
             }	
             		

 

 

Hello,

 

i am working on a Email Visual force template. In that Visual force template i need to have links as we cannot implement command buttons i guess.  When we click on the link it should either redirect to Visual force page or open pop window like alert or confirmation box using java script. Now how could i achieve this when we click the link given in the VF Email template a VFpage or an alert or confirmation box opens up.

 

Please do help on this.

 

 

Thank you.

Hi all,

 

Hope you all are well.

 

I have a custom object called Members with master details relationship linked to Opportunity object. How could I create a query so that it displays all the Members of a current object on the visual force page?

 

Sorry, I know it is probably a lame question but quite like to know how it is done.

 

Thanks,

I know how to create a class and visual force page but don't know who to create a query for above propose.

  • February 25, 2011
  • Like
  • 0

Hi All,

 

I am at the end of my patience with myself here, cause I cannot figure out what I am missing. 

 

This is a custom object, Work Order, that has a look up to an Opportunity.  There can be many Work Orders related to the same opportunity.

 

Trigger fires when

  • the Work Order stage field is updated to either one of the closed values;
  • if all of the Work Orders related to that opportunity are closed, then update the opportunity stage, if not, do nothing.

I can get this to save, run the test, but it never updates anything.  I have changed this code so many times, I have no idea where I am screwing up and would appreciate some pointer.

 

At present - I am getting an error on line 24:         Map <ID, Opportunity> updateOpps = new Map <ID, Opportunity> ([SELECT id, stageName, (select ID, Opportunity__c from Work_Orders__r)
        from Opportunity where id in :affectedOpps]);

 

Error reads:  IN Operator must be used with iterable expression.

 

I am stil very much a beginner, so please be explicit if you are telling me something I need to do:)

 

Thanks!!!!

 

 

Trigger CheckOpportunityWorkorders on Work_Order__c (after insert, after update) {

   set<id> oppids = new set<id>();

     	
	    if(Trigger.isInsert || Trigger.isUpdate)
   		    	for (Work_Order__c wo: Trigger.new) {
            if (wo.stage__c == 'Work Order Closed - Quickbooks' ||  wo.stage__c == 'Job Completed' ){
      		oppids.add(wo.Opportunity__c);
      		String oid = wo.Opportunity__c;
      		
 	    if(oppIDs .size() > 0) {
 
  Map <ID, Opportunity> affectedOpps = new Map <ID, Opportunity> ([select id, stageName, (select id, Opportunity__c from Work_Orders__r 
  	where Work_Order__c.stage__c != 'Work Order Closed - Quickbooks' OR stage__c != 'Job Completed') 
	from Opportunity where id in :oppids]);

	
	System.debug('Opportunity: '+affectedOpps.get(oid).StageName);     		
   

      	if (affectedOpps .size()==0){	
		
		Map <ID, Opportunity> updateOpps = new Map <ID, Opportunity> ([SELECT id, stageName, (select ID, Opportunity__c from Work_Orders__r)
		from Opportunity where id in :affectedOpps]);
		String upID = wo.Opportunity__c;
		 	if(updateOpps.containskey(upID))
		 	
 //       	d = updateOpps.get(upID);
				 
			upID.stageName = 'Job Complete';
			
			update updateOpps;
      	}
		
		
 
}
}
}
}

 

public with sharing class testCheckOpportunityWorkOrders {

    static testMethod void myTest() {

		Account a = new Account(name='test', type = 'customer');
		insert a;
       //Insert a test opportunity
		
       Opportunity o = new Opportunity();
       o.AccountId = a.id;
       o.StageName='Target';
       o.Name='test';
       o.closeDate=Date.today();

       insert o;
       
       system.debug('opportunity id' + Opportunity.ID);
       
         //Insert a Work_Order

       Work_Order__c wo = new Work_Order__c();

       wo.Opportunity__c = o.id;
       
       wo.Stage__c = 'Job Completed';
       wo.Close_Date_WO__c=Date.today();

  
       insert wo;
 		system.debug('workorder' + wo.ID);
 		      
       Work_Order__c ww = new Work_Order__c();

       ww.Opportunity__c = o.id;
       
       ww.Stage__c = 'Return Trip Needed';
       ww.Close_Date_WO__c=Date.today();
  
       insert ww;
       
       ww.Stage__c = 'Work Order Closed - Quickbooks';
       update ww;
       
       wo.Stage__c = 'Work Order Closed - Quickbooks';
       update wo;
       
		system.debug('workorder' + ww.ID + ww.Stage__c);
		
       Opportunity updated_Opportunity = [SELECT ID, WO_Count__c FROM Opportunity WHERE Id = :o.Id];

       //Verify that the values of the opp were changed by the trigger
       
  //System.assertEquals(opportunity, [Select WO_Count__c from Opportunity Where ID = :o.ID].wo_count__c);
  
 
     }
static testMethod void testBulkInsert() {

  List<Opportunity> opps = new List<Opportunity>();
  
 }

}

 

 

 

Good morning, I am hoping someone can set me straight on what I am attempting to do here. 

 

  • I have a custom object Work Order that has a lookup relationship to Opportunity. 
  • There can be many Work Orders related to one opportunity. 
  • On Opportunity, I have a custom field that is populated via a trigger to count all of the Work Orders associated

I have a second trigger that is meant to

  • identify those Work Orders that are closed and,
  • if the count of Closed Work Orders = the count of all Work Orders
  • update the Opportunity Stage to Completed

I am getting lost on how to write the logic to compare the COUNT of the closed Work Orders to the value in the Opportunity field.  I'd appreciate any help!!!  Thanks.

 

trigger trigWorkorderCloseOpp on Work_Order__c (after insert, after update) {

    //************************************************
    // Build a LIST of Opportunity ID's that may
    // need closing
    //************************************************

	set <id> oppIDs = new set <id>();
	list <Opportunity> opportunity = [SELECT ID FROM Opportunity WHERE ID in:oppIDs];

	
    if(Trigger.isInsert || Trigger.isUpdate){
        for(Work_Order__c w : trigger.new){
            if(w.Opportunity__c != null && w.stage__c == 'Work Order Closed - Quickbooks')
            {oppIDs.add(w.Opportunity__c);
            } else if (w.Opportunity__c != null && w.stage__c == 'Job Completed')
            {oppIDs.add(w.Opportunity__c);
            
            }

	        }

      // INSERT/UPDATE Trigger

    if(Trigger.isDelete || Trigger.isUpdate){
        for(Work_Order__c w : trigger.old){
           if(w.Opportunity__c != null && w.stage__c == 'Work Order Closed - Quickbooks')
            {oppIDs.add(w.Opportunity__c);
            } else if (w.Opportunity__c != null && w.stage__c == 'Job Completed')
            {oppIDs.add(w.Opportunity__c);
             }
        }
    }

    if(oppIDs .size() > 0) {
    
        Map<ID, Opportunity> oppMap = new Map<ID, Opportunity>([Select id, WO_Count__c, StageName from Opportunity Where Id in :oppIds]);  	
    	
    	Opportunity d = null;
    		
    	for (AggregateResult ar : [SELECT ID, Opportunity__c, COUNT(Id)total FROM Work_Order__c WHERE Opportunity__c in: oppIds GROUP BY Opportunity__c])
    	
    		{
    			String dID = (String)dr.get('Opportunity__c');
    			Integer a = Integer.valueOf(ar.get('total'));
    			if(oppMap.get(dID) == null)
    			 d = new Opportunity(ID=string.valueOf(ar.get('Opportunity__c')));
    			
    			else
    			if(oppMap.containskey(dID)&& a.equals(Opportunity.WO_Count__c))
        		d = oppMap.get(dID);
    			
    			
    		}

    		d = opps.get(dID);
    		d.StageName = 'Job Completed';
    		
    		update opps.values();
    		
    }
    }
}		

 

 

 

This trigger is on Quote and I am stuck on one part I am not able to use IsClosed() on quote status.

 

trigger CloseAllQuotes on Quote (after update) {

system.debug('Close All the Quotes on the Oppurtunity after one Quote is closed');

ID Oppid = Trigger.new[0].OpportunityId;
List <Quote> newQt = new List <Quote> ();

for(Quote Qt: newQT) {
    if((){ ----> I need to chk if previously this was not approved
    Qt = [select id,status,OpportunityId from Quote where OpportunityId=:Oppid]; 
    Qt.Status = 'Approved';
    Update Qt;
           
        }     
    }
}

Does anyone know of a way to create a "Mass Submit for Approval" button on a Custom Object?  I have the process already created but we need to be able to submit many at once.  Any help is appreciated!

Very similar to the VF Cookbook Opportunity Wizard example, I have created an opportunity creation wizard because my users complain about too many clicks when creating an opportunity, adding products, etc.  My question is when the user clicks on Save, I would like to save the opportunity but instead of redirecting to the saved opportunity detail, go directly to the standard add products page.  I do not want to add the button to the VF page, just redirect to the standard add products search functionality.

 

I have been trying to set the addProductsURL as the page reference after saving the opportunity and have tried it a couple of ways in my controller without success.

public PageReference addProductsURL(){ PageReference p = new PageReference('/'+SelectSearch?addTo={!Opportunity.ID} ); p.getParameters().put('addTo',opportunity.Id); p.setRedirect(true); return p; This is how I tried to return the addProductsURL after saving opportunity: PageReference addProduct = Page.addProductsURL; addProduct.getParameters().put('id',this.controller.getId()); addProduct.setRedirect(true); return addProduct;

 

Thanks!  Any ideas are appreciated :)

 

I have created a custom object called PTO. I have also created an approval process for it.  How can I create a  trigger so that it automically executed the approval process i have setup as soon as a new PTO record is created(inserted).  This would behave the same way as if I manually pressed the submit approval button.

 

trigger PTO_Trigger on PTO__c (after insert) 
{
for(PTO__c pto: [select id from pto__c])
{
Approval.ProcessSubmitRequest req1 = new Approval.ProcessSubmitRequest();
req1.setObjectId(pto.id);
}
}

 

 

 

Message Edited by bikla78 on 07-15-2009 11:49 PM