• kevin Carothers
  • NEWBIE
  • 319 Points
  • Member since 2014

  • Chatter
    Feed
  • 10
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 4
    Questions
  • 66
    Replies
We are looking to fire a trigger based on the record result of a workflow rule.  My initial thought would be to write an entirely new trigger that encorporates the logic of the workflow rule AND the existing trigger, but if we can just tell the existing trigger to fire after the workflow completes, it won't require developer time.

Thoughts?
hello all, 
i am newbie to apex coding.

i am stuck in this scenerio.  I cannot able to update the field in a case object which is a detail of the self lookup.  Please help me to break the challenge.  The coding is as follows, the main error is in "update t2", its in last line...some looping problem
Thank yo so much in advance...
trigger complex on Case (before insert, after update) {
    set<id> casid = new set<id>();
    set<id> curid = new set<id>();
    set<String> cassta = new set<String>();
    list<Case> multi=new list<Case>();
            for(Case c:Trigger.new){
                if(c.status__c=='closed'){
                cassta.add(c.status__c);
                curid.add(c.id);
                if(c.Case__c != null)
                casid.add(c.Case__c);
                }
                }
                  if(casid.size()>0)
                {
                  list<Case> t1=[select id,Case__c,status__c from Case Where id IN :casid];
                  for(Case q2:t1)
                   {
                   q2.status__c='closed';
                   }
                    update t1;
                }
                else
                {
                list<Case> t2=[select status__c from Case Where Case__c IN :curid];
                            for(Case q1:t2)
                            {
                            q1.status__c='closed';
                            }
                update t2;
                }            
Can anyone please explain to me what this code below is doing? I did not get the last few lines.

//Methd to handle the backing up of actual recordtype on closing and restoring the actual recordtype on re-opening
    public static void updateRecordtypeOnReopen(List<case> caselis,Map<Id,Case> caseNewMap,Map<Id,Case> caseOldMap) {
        //Loop to assign recordtype from the Actual RecordType Id field when the case is getting re-opened
        Schema.DescribeSObjectResult d = Schema.SObjectType.Case;
        Map<Id,Schema.RecordTypeInfo> rtMapById = d.getRecordTypeInfosById();
        Map<String,Schema.RecordTypeInfo> rtMapByName = d.getRecordTypeInfosByName();
        for(Case c:caselis)
        {
            //To backup the actual recordtype on closing/resolving the case
            if(caseOldMap.get(c.Id).Status!=caseNewMap.get(c.Id).Status && (caseNewMap.get(c.Id).Status=='Closed' || casenewMap.get(c.Id).Status=='Resolved') && String.isBlank(c.Actual_RecordType__c))
            {
                c.Actual_RecordType__c = ''+c.RecordTypeId;
                c.Case_RecordType_Name__c =  rtMapById.get(c.RecordTypeId).getName();
            }
            //Restroing the actual recordtype on re-opening the case
            if(caseOldMap.get(c.Id).Status!=caseNewMap.get(c.Id).Status && (caseOldMap.get(c.Id).Status=='Closed' || caseOldMap.get(c.Id).Status=='Resolved') && !String.isBlank(c.Actual_RecordType__c) && (c.Case_RecordType_Name__c =='Administrative' || c.Case_RecordType_Name__c =='Shipping Request' ||c.Case_RecordType_Name__c =='Technical'))
            {
                c.RecordTypeId = (Id)c.Actual_RecordType__c;
            }
        }
       
    }
I'm a bit stumped here,
I've taken the salesforce example for creating a controller extension:
https://www.salesforce.com/us/developer/docs/pages/Content/apex_pages_standardcontroller.htm

public class myControllerExtension {

    private final Account acct;
    
    public myControllerExtension(ApexPages.StandardController stdController) {
        this.acct = (Account)stdController.getRecord();
    }
    
    public String getGreeting() {
        return 'Hello ' + acct.name + ' (' + acct.id + ')';
    }
}

And I'm trying to add a test class for it, which fails miserably in Eclips with a Constructor not defined message: 
Constructor not defined: [myControllerExtension].<Constructor>(ApexPages.StandardController)

but that's exactly what I've declare above!?

Here's the full test class:
@isTest
private class myControllerExtensionTestClass {

    static testMethod void myUnitTest() {

        Account a = new Account(name = 'Some Care Centre');
        
        ApexPages.Standardcontroller sc =  new Apexpages.Standardcontroller(a);
		myControllerExtension anExt = new myControllerExtension(sc);
		
		String aString;
		aString = anExt.getGreeting();
    }
}

I've tried to initiate the extension without arguments: 
myControllerExtension anExt = new myControllerExtension();
which gets me past the constructor error, but I then face a "method does not exist or incorrect signature [myControllerExtension].getGreeting()" error as soon as I call anExt.getGreeting();

I've written similar code a couple of months ago, so I went back and looked at the project that I have and the classes refuse to save now too, even though I could deploy them back then.

I have no idea what's going on. Any tips would be appreciated.
Presently I have this workflow rule logic that checks to see if a certain set of subtasks by a certain department is completed and if so it passes ownership to the next user in the process.  The problem is that is doesn't check who was previous owner and therefore the logic is flawed.  If one of these processes gets further along it'll keep firing, rather than just the 1 time that I goes between departments.

AND( NOT(ISBLANK( TEXT(Competitive_Analysis__c) )) , NOT(ISBLANK(TEXT(Catalog_Item_UDF__c))) , NOT(ISBLANK(TEXT(Market_Driven_Price_UDF__c ))), NOT(ISBLANK( TEXT(Packaging_and_Label_Specifications__c)) ), NOT(ISBLANK( TEXT(Recommendations_for_Stock_Levels__c)) ) , NOT(ISBLANK(TEXT( Replace_Other_Product_and_Obsolescence__c ))), NOT(ISBLANK(TEXT( Requirements_Document__c) )), NOT(ISBLANK(TEXT( Sales_Training_CSA__c ))) , NOT(ISBLANK(TEXT( Sales_Training_RSM__c ))))

User-added image

I've tried to add some "OwnerID" logical operators but it keeps telling me that my users don't exist, their login names, their userIDs, their aliases.  Nothing works.  How would I add a logical check in the above formula to check for existing owner and only fire if it was owned by the previous owner and only if all their tasks were completed.
I don't think this is possible but wanted to check with the community to see if anyone has had this use case before.  Thanks
  • May 14, 2014
  • Like
  • 0
I have a SOQL query that hasn't changed in a long time that look something like this:
SELECT Lead.Id, Lead.Name (SELECT Task.Id, Task.ActivityDate FROM Lead.Tasks ORDER BY Task.ActivityDate DESC) FROM Lead WHERE Id = 'xxx'
In the past, that has always returned the specified lead info as well as all tasks they have, or at least as many as the API allowed for, sorted by most-recent activity / due date. At some point recently, that query started returning up to 15 tasks that are completely unsorted. I don't care so much about the limited number of tasks being returned, but the seemingly broken sorting behavior is causing problems for us.

Any ideas?
Hello,

I know this has been discussed many times, however I cannot find an answer after breaking my skull open with this issue all day and yesterday. I have only been working with SalesForce for a week so forgive me if this is simple to do.

Problem:
Case.LastModifiedDate only reflects the date/time that the actual case was modified, and not the date/time of the last activity within a case.

My goal/solution:
Since Case.LastModifiedDate is a read-only field, I have created a custom field named Case.LastModifiedDateActivity. I want Case.LastModifiedDateActivity (DATETIME datatype) to be automatically updated (via Apex) whenever an employee performs an activity related to a certain case. (When the employee writes an email to a customer, makes a phone call, etc. in regards to a certain case).

Can someone help me implement this function? It is vital for our support team! 
Hi Team,

Currently, I am unable to set up an email alert for the Event object, the standard functionality does not allow you to set up workflow email for Events and Tasks. Only way to overcome that is create a trigger.

I have searched a lot but didn't find how to write this EmailAlert on Event object.
If it is possible, could you show me a sample code to fire an email alert to  "CreatedBy" and "Assigned To" users when End Date of the Event is Overdue ( EndDateTime > Today() ) ?

Many thanks for your help,

Regards,
Ludivine
In visualforce, if I've got a couple of dynamic picklists, is it possible to bind the selected value to a real standard or custom field?

In other words let's say I've got a visualforce page that overrides the Lead edit page.  This vf page has a couple dynamic picklists on it.  On selecting values in those dynamic picklists, the user would click save, and the selected values would be mapped to actual fields on the Lead object.  Not sure how to do this.

Here's a simple vf page that could override the lead edit button, along with it's custom controller.  It seems to work, except for actually saving the dynamic picklist selections to the database.

Any help is appreciated 

vf page:


<apex:page standardController="Lead" extensions="DependentObjects" id="UseCaseDisplay" label="FeatureCategoryReport">
<apex:form >
<apex:pageBlock title="New Lead" mode="edit">
<apex:pageBlockButtons >
<apex:commandButton action="{!save}" value="Save"/>
<apex:commandButton action="{!cancel}" value="Cancel"/>

</apex:pageBlockButtons>

<apex:pageBlockSection id="section1" title="Lead Information" columns="2" collapsible="true" ondblclick="toggleInputFieldsSales();">
<apex:inputField value="{!lead.LastName}"/>
<apex:inputField value="{!lead.Email}"/>
<apex:inputField value="{!lead.Company}"/>
<apex:inputField value="{!lead.LeadSource}"/>
<apex:inputField value="{!lead.Lead_Source_Detail__c}" />
</apex:pageBlockSection>  


<apex:pageblocksection >
<table border="0" width="923px;">
  <tr>
    <td align = "right"> 
         <apex:outputLabel style="font-weight:bold;font-size:11px;" value="Lead Source" for="category"/>
         &nbsp;&nbsp;
    </td>
    <td> &nbsp;         
         <apex:selectList style="align:right;" value="{!category}" size="1" id="category">
         <apex:selectOptions value="{!categories}"/>
         <apex:actionSupport event="onchange" rerender="features"/>        
         </apex:selectList>
    </td>
  </tr>
  <tr>
     <td align = "right">
         <apex:outputLabel style="font-weight:bold;font-size:11px;" value="Lead Source Detail" for="features"/>
         &nbsp;&nbsp;
    </td>
     <td>
         &nbsp;
         <apex:selectList value="{!feature}" size="1" id="features" disabled="{!ISNULL(category)}">
         <apex:selectOptions value="{!features}"/>
         </apex:selectList>
    </td>
  </tr>
</table>  
</apex:pageBlockSection>




</apex:pageBlock>
</apex:form>
</apex:page>


controller:






public class DependentObjects {

    private final Lead acct;
    
    
    // The extension constructor initializes the private member
    // variable acct by using the getRecord method from the standard
    // controller.
    public DependentObjects(ApexPages.StandardController stdController) {
        this.acct = (Lead)stdController.getRecord();
    }
    
    public String selectedAccName {get; set;}
    public DependentObjects() {
        selectedAccName = '';
    }
    return page;
    }    
    
    
    /* String value for the category */
    String category;

    /* String value for the feature */
    String feature;

    /* Getter for the category value */
    public String getCategory() { return this.category; }

    /* Setter for the category value */
    public void setCategory(String s) { this.category = s; }

    /* Getter for the feature value */
    public String getFeature() { return this.feature; }
 
    /* Setter for the feature value */
    public void setFeature(String s) { this.feature = s; }
    
    /* Getter which dynamically generates the categories from the Feature_Category__c object. */
    public List<SelectOption> getCategories() {
      //List<SelectOption> optionList = new List<SelectOption>();
      /* Add a null option to force the user to make a selection. */
     // options.add(new SelectOption('','- None -'));
    
      /* Loop through the Lead records creating a selectOption
         for each result with the record ID as the value and the name as the label 
         displayed in the selectList */

    Set<String> uniqueCustomObjectSet = new Set<String>();    
    List<SelectOption> options = new List<SelectOption>();
          options.add(new SelectOption('','- None -'));

    for(LeadSourceHidden__c sl:[Select LeadSourceHidden__c,Name From LeadSourceHidden__c WHERE LeadSourceHidden__c != null ORDER BY LeadSourceHidden__c DESC
    ])
    {
    uniqueCustomObjectSet.add(sl.LeadSourceHidden__c);
    }
    List<String> uniqueCustomObjectList = new List<String>(uniqueCustomObjectSet);
    
    for(integer i=0; i<uniqueCustomObjectList.size(); i++){
    options.add(new SelectOption(uniqueCustomObjectList[i],uniqueCustomObjectList[i]));
    }
    
    //options.add(new SelectOption('test','test'));
    return options;
    }

    /* Getter which generates the options for the features selectList based on the current
       value of the selected category. If there is no value selected then only
       the null option should be returned. */
    
    public List<SelectOption> getFeatures() {
      List<SelectOption> optionList = new List<SelectOption>();
      /* Add a null option to force the user to make a selection. */
       optionList.add(new SelectOption('', '- None -')); 

      /* If a category has been selected then query for the related values */
      if(category != NULL) {

        /* Loop over the related campaign records for the given lead source 
           creating a selectOption with the value being the feature record ID
           and the label is the name of the lead source. */
        for (Campaign f : [select Name,Type from Campaign f where f.Type =: category LIMIT 40000 ]){
          optionList.add(new SelectOption(f.Id,f.Name));
        }
      }
      return optionList;
    }
}


  • May 12, 2014
  • Like
  • 0
Hi everyone,

This should be pretty easy but it's giving me bouts of grief.

I need to get the name of the person that approved a record into an HTML email template, as there are several possible approvers and they would all like to know who approved the record from an email sent on final approval/rejection, rather than logging into Salesforce (for various reasons - they'd like to know via email).

I tried using the LastModifiedBy name, which seems to be correct when I look at an approved record in the UI, but when I insert it in my email template as a field, it's blank when the approval/rejection takes place, and the email is sent- 

Any ideas on how I can accomplish this?

Thanks in advance.

 
Hi All,

I'm trying to use a component in a VF email template.
The Component looks like this;
<apex:component controller="findDetailData" access="global">
  <apex:attribute name="xstrOpptyId" description="opportunity ID" type="String" assignTo="{!strOptID}"/>
  <table>
  <tr>
   <td>Name</td>
   <td>Quantity</td>
   <td>UoM</td>
   <td>NRC</td>
   <td>Price</td>
   <td>Variance</td>
   <td>MRC</td>
   <td>Waived</td>
  </tr>
  <apex:repeat var="opp" value="{!opptyLines}">
     <td>{!opp.PriceBookEntry.name}</td>
     <td align="right">{!ROUND(opp.Quantity,0)}</td>
     <td align="left">{!opp.UoM__c}</td>
     <td align="right">{!ROUND(opp.NRC__c,0)}</td>
     <td align="right">{!ROUND(opp.Variance__c,0)}</td>
     <td align="right">{!ROUND(opp.TotalPrice,0)}</td>
     <td align="left">{!opp.Waived__c}</td>
  </apex:repeat>
  </table>  
</apex:component>

And the controller is this;
public class findDetailData {
    public  List<OpportunityLineItem> opptyLines = new List<OpportunityLineItem>();
    public String strOptID{get;set;}

    public findDetailData() {
        
        Opportunity lo = [SELECT Amount, Id, Name, (SELECT Quantity, NRC__c,
        PriceBookEntry.UnitPrice, PricebookEntry.Name,
        Variance__c, TotalPrice, Waived__c FROM OpportunityLineItems)
        FROM Opportunity
        WHERE Id =  :strOptID LIMIT 1];
        
        //System.debug('lo.size(): ' + lo.size());
        OpportunityLineItem ox = new OpportunityLineItem(Quantity=1,UoM__c='', NRC__c=0,TotalPrice=0,Waived__c=false);
        
        opptyLines = lo.OpportunityLineItems;
        }

    public List<OpportunityLineItem> getopptyLines() {
        return opptyLines;
        }
    }

....And when I onsert it on the page, I'm declaring it like this;
<c:findDetailData xstrOpptyId="{!relatedTo.OpportinityId__c}"/>

....But I keep getting the error  "Error occurred trying to load the template for preview: List has no rows for assignment to SObject. Please try editing your markup to correct the problem"



 

My use case is that, when a rep inserts an "Advanced" product (product code 99997) on and opportunity, I have to look at all the opportunities on the related account, and see if a "Basic" product is also on an opportunity on the account (product code 99998).  

If not, I need to insert an OpportunityLineItem record with the  Basic product.
What's weird to me is that, after building and inserting the OpportunityLineItem and putting it in the correct Opportunity (the one being edited), the 'before' and 'after' debug statements show no change to the number of opportunitylineitems.... This seems very strange to me.
 

Does anyone have a clue as to what may be happening?   Is it even possible to programmatically add opportunitylineitems?

Thanks,

 

trigger CheckOpportunityForProperProducts on OpportunityLineItem (after insert) {
    Set<Id> accIdList = new Set<Id>();
    List<Id> oppIdList = new List<Id>();    

	// Get Pricebook info for later (possible) insert
    Pricebook2 standardBook = [SELECT Id FROM Pricebook2 WHERE IsStandard = true];
    PricebookEntry BasicEntry = [SELECT Id, UnitPrice FROM PricebookEntry WHERE Pricebook2Id = :standardBook.Id AND Product2.ProductCode = '99998'];

	//All opportunity IDs in a list
	for(OpportunityLineItem oli :Trigger.new) {
		oppIdList.add(oli.OpportunityId);
	    }

    // this gives us just the account IDs related to this insert...
    List<Opportunity> tmpOpps = [SELECT Id,  AccountId FROM Opportunity WHERE Id in :oppIdList];
    List<Opportunity>  updateTheseOpportunities = new List<Opportunity>();

	for(Opportunity o :tmpOpps) {
		accIdList.add(o.AccountId);
	    }

	// Now get the complete set of working data
    Map<Id, Opportunity> allOpps = new Map<Id, Opportunity> ([SELECT Id, AccountId, StageName, CreatedDate,
	                                             Type, CloseDate, Name,
	                                                   (SELECT Quantity, UnitPrice, TotalPrice,
	                                                           PricebookEntry.Name,
	                                                           PricebookEntry.Product2.ProductCode
	                                                    FROM OpportunityLineItems)
	                                        FROM Opportunity WHERE AccountId in :accIdList
	                                        AND StageName LIKE '%Stage 5:%'
	                                        AND Count_of_Products__c > 0
                                        ORDER BY CreatedDate  ASC]);

	for(Id  acctId :accIdList) {
		Boolean  AdvancedRuleFound = false;
		Boolean  BasicRuleFound = false;
		Id theOppId = null;

		for(Opportunity o :allOpps.values()) {
			if(o.OpportunityLineItems != null && o.AccountId == acctId) {   // oppty related to this account
				// check all oppty products on this account
				for(OpportunityLineItem opptyLineItem : o.OpportunityLineItems) {
					if(opptyLineItem.PricebookEntry.Product2.ProductCode == '99997') {   // Advanced
						AdvancedRuleFound = true;
						theOppId = o.Id;    // put on the same opportunity that the Advanced is on....
						}
					if(opptyLineItem.PricebookEntry.Product2.ProductCode == '99998') {    // Basic
						BasicRuleFound = true;					
						}
					} // end of sifting thru olis
				}   // END check for OpportunityLineItems
			}    // END for(Opportunity o :allOps)

	    	System.debug('allOpps.get(theOppId).OpportunityLineItems.size() - Before: ' + allOpps.get(theOppId).OpportunityLineItems.size());
	    
		if(BasicRuleFound== false && AdvancedRuleFound == true && theOppId != null) {   // need to insert the basic product...
			OpportunityLineItem oppli = new OpportunityLineItem(PricebookEntryId=BasicEntry.Id, OpportunityId=theOppId, UoM__c='Each', NRC__c = 1000, UnitPrice=0, Quantity=1);
			allOpps.get(theOppId).OpportunityLineItems.add(oppli);
			System.debug('allOpps.get(theOppId).OpportunityLineItems.size() - After: ' + allOpps.get(theOppId).OpportunityLineItems.size());
			updateTheseOpportunities.add(allOpps.get(theOppId));
			}
    	}
        //upsert updateTheseOpportunities;
    }
 


 

Hi everyone,

I have a requirement to build a report that has summary buckets of the Opportunity Product description field, and the opportunity detail needs to be shown underneath that bucket.   An example would be;

Monetization 111
...all these opportunities
Content 55
...all these opportunities
Delivery 443
...all these opportunities
Security 22
...all these opportunities
Enablement 52
...all these opportunities 

Where "Monetization", "Content", "Delivery", etc.   are all buckets from a formula field on the opportunity product based on the product description.

Can this be done?   at first glance it seems like it's not, because I keep thinking there needs to be a lookup from the opportunity to the opportunity product, but that's obviously impossible - but maybe I'm not looking at it the right way.
 
Hi everyone,

This should be pretty easy but it's giving me bouts of grief.

I need to get the name of the person that approved a record into an HTML email template, as there are several possible approvers and they would all like to know who approved the record from an email sent on final approval/rejection, rather than logging into Salesforce (for various reasons - they'd like to know via email).

I tried using the LastModifiedBy name, which seems to be correct when I look at an approved record in the UI, but when I insert it in my email template as a field, it's blank when the approval/rejection takes place, and the email is sent- 

Any ideas on how I can accomplish this?

Thanks in advance.

 
Hi All,

I'm trying to use a component in a VF email template.
The Component looks like this;
<apex:component controller="findDetailData" access="global">
  <apex:attribute name="xstrOpptyId" description="opportunity ID" type="String" assignTo="{!strOptID}"/>
  <table>
  <tr>
   <td>Name</td>
   <td>Quantity</td>
   <td>UoM</td>
   <td>NRC</td>
   <td>Price</td>
   <td>Variance</td>
   <td>MRC</td>
   <td>Waived</td>
  </tr>
  <apex:repeat var="opp" value="{!opptyLines}">
     <td>{!opp.PriceBookEntry.name}</td>
     <td align="right">{!ROUND(opp.Quantity,0)}</td>
     <td align="left">{!opp.UoM__c}</td>
     <td align="right">{!ROUND(opp.NRC__c,0)}</td>
     <td align="right">{!ROUND(opp.Variance__c,0)}</td>
     <td align="right">{!ROUND(opp.TotalPrice,0)}</td>
     <td align="left">{!opp.Waived__c}</td>
  </apex:repeat>
  </table>  
</apex:component>

And the controller is this;
public class findDetailData {
    public  List<OpportunityLineItem> opptyLines = new List<OpportunityLineItem>();
    public String strOptID{get;set;}

    public findDetailData() {
        
        Opportunity lo = [SELECT Amount, Id, Name, (SELECT Quantity, NRC__c,
        PriceBookEntry.UnitPrice, PricebookEntry.Name,
        Variance__c, TotalPrice, Waived__c FROM OpportunityLineItems)
        FROM Opportunity
        WHERE Id =  :strOptID LIMIT 1];
        
        //System.debug('lo.size(): ' + lo.size());
        OpportunityLineItem ox = new OpportunityLineItem(Quantity=1,UoM__c='', NRC__c=0,TotalPrice=0,Waived__c=false);
        
        opptyLines = lo.OpportunityLineItems;
        }

    public List<OpportunityLineItem> getopptyLines() {
        return opptyLines;
        }
    }

....And when I onsert it on the page, I'm declaring it like this;
<c:findDetailData xstrOpptyId="{!relatedTo.OpportinityId__c}"/>

....But I keep getting the error  "Error occurred trying to load the template for preview: List has no rows for assignment to SObject. Please try editing your markup to correct the problem"



 

My use case is that, when a rep inserts an "Advanced" product (product code 99997) on and opportunity, I have to look at all the opportunities on the related account, and see if a "Basic" product is also on an opportunity on the account (product code 99998).  

If not, I need to insert an OpportunityLineItem record with the  Basic product.
What's weird to me is that, after building and inserting the OpportunityLineItem and putting it in the correct Opportunity (the one being edited), the 'before' and 'after' debug statements show no change to the number of opportunitylineitems.... This seems very strange to me.
 

Does anyone have a clue as to what may be happening?   Is it even possible to programmatically add opportunitylineitems?

Thanks,

 

trigger CheckOpportunityForProperProducts on OpportunityLineItem (after insert) {
    Set<Id> accIdList = new Set<Id>();
    List<Id> oppIdList = new List<Id>();    

	// Get Pricebook info for later (possible) insert
    Pricebook2 standardBook = [SELECT Id FROM Pricebook2 WHERE IsStandard = true];
    PricebookEntry BasicEntry = [SELECT Id, UnitPrice FROM PricebookEntry WHERE Pricebook2Id = :standardBook.Id AND Product2.ProductCode = '99998'];

	//All opportunity IDs in a list
	for(OpportunityLineItem oli :Trigger.new) {
		oppIdList.add(oli.OpportunityId);
	    }

    // this gives us just the account IDs related to this insert...
    List<Opportunity> tmpOpps = [SELECT Id,  AccountId FROM Opportunity WHERE Id in :oppIdList];
    List<Opportunity>  updateTheseOpportunities = new List<Opportunity>();

	for(Opportunity o :tmpOpps) {
		accIdList.add(o.AccountId);
	    }

	// Now get the complete set of working data
    Map<Id, Opportunity> allOpps = new Map<Id, Opportunity> ([SELECT Id, AccountId, StageName, CreatedDate,
	                                             Type, CloseDate, Name,
	                                                   (SELECT Quantity, UnitPrice, TotalPrice,
	                                                           PricebookEntry.Name,
	                                                           PricebookEntry.Product2.ProductCode
	                                                    FROM OpportunityLineItems)
	                                        FROM Opportunity WHERE AccountId in :accIdList
	                                        AND StageName LIKE '%Stage 5:%'
	                                        AND Count_of_Products__c > 0
                                        ORDER BY CreatedDate  ASC]);

	for(Id  acctId :accIdList) {
		Boolean  AdvancedRuleFound = false;
		Boolean  BasicRuleFound = false;
		Id theOppId = null;

		for(Opportunity o :allOpps.values()) {
			if(o.OpportunityLineItems != null && o.AccountId == acctId) {   // oppty related to this account
				// check all oppty products on this account
				for(OpportunityLineItem opptyLineItem : o.OpportunityLineItems) {
					if(opptyLineItem.PricebookEntry.Product2.ProductCode == '99997') {   // Advanced
						AdvancedRuleFound = true;
						theOppId = o.Id;    // put on the same opportunity that the Advanced is on....
						}
					if(opptyLineItem.PricebookEntry.Product2.ProductCode == '99998') {    // Basic
						BasicRuleFound = true;					
						}
					} // end of sifting thru olis
				}   // END check for OpportunityLineItems
			}    // END for(Opportunity o :allOps)

	    	System.debug('allOpps.get(theOppId).OpportunityLineItems.size() - Before: ' + allOpps.get(theOppId).OpportunityLineItems.size());
	    
		if(BasicRuleFound== false && AdvancedRuleFound == true && theOppId != null) {   // need to insert the basic product...
			OpportunityLineItem oppli = new OpportunityLineItem(PricebookEntryId=BasicEntry.Id, OpportunityId=theOppId, UoM__c='Each', NRC__c = 1000, UnitPrice=0, Quantity=1);
			allOpps.get(theOppId).OpportunityLineItems.add(oppli);
			System.debug('allOpps.get(theOppId).OpportunityLineItems.size() - After: ' + allOpps.get(theOppId).OpportunityLineItems.size());
			updateTheseOpportunities.add(allOpps.get(theOppId));
			}
    	}
        //upsert updateTheseOpportunities;
    }
 


 

Hi everyone,

I have a requirement to build a report that has summary buckets of the Opportunity Product description field, and the opportunity detail needs to be shown underneath that bucket.   An example would be;

Monetization 111
...all these opportunities
Content 55
...all these opportunities
Delivery 443
...all these opportunities
Security 22
...all these opportunities
Enablement 52
...all these opportunities 

Where "Monetization", "Content", "Delivery", etc.   are all buckets from a formula field on the opportunity product based on the product description.

Can this be done?   at first glance it seems like it's not, because I keep thinking there needs to be a lookup from the opportunity to the opportunity product, but that's obviously impossible - but maybe I'm not looking at it the right way.
 
We are looking to fire a trigger based on the record result of a workflow rule.  My initial thought would be to write an entirely new trigger that encorporates the logic of the workflow rule AND the existing trigger, but if we can just tell the existing trigger to fire after the workflow completes, it won't require developer time.

Thoughts?
Hello,

When I open the page for managed package, which should display components, versions of the package, etc, there is nothing in it now except the message:
"Data Not Available
The data you were trying to access could not be found. It may be due to another user deleting the data or a system error. If you know the data is not deleted but cannot access it, please look at our support page."

I was able to open this page normally before, modified and uploaded package without errors. The package itself is present in "create -> packages" section, and "edit" page available for it as usually.

Do you have ideas why this might happen and how to fix?

Thanks.
Hi friends,

I have created a date field name last updated and based on changes in another field medical_Practioners.I am updating this last updated field automatically.

I am trying to create work flow and I selected formula evaluate to true and then inserted the following formula.

PRIORVALUE( Medical_Members__c )  <>  Medical_Members__c.

However,when I check syntax then I get the following error.

Error: Function PRIORVALUE may not be used in this type of formula

Can sombody tell me how to do that.?






I want to retrieve some fields from the Quote object and the list of  child QuoteLineItems. 
I have a dyanmic SOQL query (field list for QuoteLineItems is dynamic).  The query runs fine but in viewing the debug output  the returned values do not seem to include the QuoteLineitems. 

Here is an example of my dynamic SOQL query.
I want to process thru the list using the OpportunityId and the QuoteLineItems for each record returned as inputs to another method.

select opportunityId, ( SELECT QuoeID,  PricebookEntryId,  discount, unitprice from QuoteLineItems ) from Quote where Id IN ('0Q0c000000020MUCAY')

Perhaps I'm trying to do too much in one query ;-)

  • June 13, 2014
  • Like
  • 0
I wrote a validation rule on the case object, worked fine for sys admins, but for standard users it always evaluated to true:

NOT(ISPICKVAL(Status,'Closed')) &&
IF( AssetId <> NULL, Asset.AccountId <> AccountId, false)

I wrote 2 others, that didn't ever evaluate to true:


NOT(ISPICKVAL(Status,'Closed')) &&
IF( NOT(ISBLANK( AssetId )) ,
Asset.Account.Name = Account.Name,false)


NOT(ISPICKVAL(Status,'Closed')) &&
IF(AssetId <> NULL,
If( AccountId <> NULL,
Asset.Account.Name <> Account.Name,false), false)


What don't any of these work? What should the rule say??
Hi guys I need help to solve this error:
InsertMilestonesDeploymentProject: execution of AfterUpdate caused by: System.NullPointerException: Attempt to de-reference a null object: Trigger.InsertMilestonesDeploymentProject: line 31, column 1

trigger InsertMilestonesDeploymentProject on Projeto_Implantacao__c (after insert, after update) {
	List<Etapas_Projeto_de_implantacao__c> mList = new List<Etapas_Projeto_de_implantacao__c>();	
	Etapas_Projeto_de_implantacao__c milestone1;
	Etapas_Projeto_de_implantacao__c milestone2;
	Etapas_Projeto_de_implantacao__c milestone3;
	Etapas_Projeto_de_implantacao__c milestone4;
	Etapas_Projeto_de_implantacao__c milestone5;
	Etapas_Projeto_de_implantacao__c milestone6;
	Etapas_Projeto_de_implantacao__c milestone7;
	Etapas_Projeto_de_implantacao__c milestone8;
	
	//Set of accounts
	Set<Id> accountIds =  new Set<Id>();
	
	for(Projeto_Implantacao__c p:Trigger.new){
		accountIds.add(p.Implantacao__c);//Implantacao__c is a lookup field
	}
	//Map of accounts
	Map<Id, Account> accountMap = new Map<Id, Account>([SELECT Id,Name,Unidade_de_atendimento__c FROM Account WHERE Id IN :accountIds]);
	
	
	
	if(Trigger.isAfter) {
    if(Trigger.isUpdate) {
       for(Projeto_Implantacao__c p: Trigger.new) {
       	for(Projeto_Implantacao__c old: Trigger.old) {
           
             milestone1 = new Etapas_Projeto_de_implantacao__c();
             milestone1.Name = '01 - Contato inicial';
             //restore info account master-detail Account>>Projeto_Implantacao__c>>Implantacao
             if(accountMap.get(p.Implantacao__r.Id).Unidade_de_atendimento__c == 'Campo Grande')//The problem It´s here
             	milestone1.Responsavel__c = '005G0000003oWY2';
             milestone1.Data_inicial_prevista__c = Date.today();
             milestone1.Data_final_prevista__c = Date.today().addDays(3);
             milestone1.Projeto_de_Implantacao__c = p.Id;
             mList.add(milestone1);
             
             milestone2 = new Etapas_Projeto_de_implantacao__c();
             milestone2.Name = '02 - Levantamento/Coleta de dados';
             milestone2.Data_inicial_prevista__c = Date.today().addDays(4);
             milestone2.Data_final_prevista__c = Date.today().addDays(10);
             milestone2.Projeto_de_Implantacao__c = p.Id;
             mList.add(milestone2);
             
             milestone3 = new Etapas_Projeto_de_implantacao__c();
             milestone3.Name = '03 - Conversão de dados';
             milestone3.Data_inicial_prevista__c = Date.today().addDays(11);
             milestone3.Data_final_prevista__c = Date.today().addDays(20);
             milestone3.Projeto_de_Implantacao__c = p.Id;
             mList.add(milestone3);
             
             milestone4 = new Etapas_Projeto_de_implantacao__c();
             milestone4.Name = '04 - Capacitação';
             milestone4.Data_inicial_prevista__c = Date.today().addDays(21);
             milestone4.Data_final_prevista__c = Date.today().addDays(30);
             milestone4.Projeto_de_Implantacao__c = p.Id;
             mList.add(milestone4);
             
             milestone5 = new Etapas_Projeto_de_implantacao__c();
             milestone5.Name = '05 - Instalação/Acompanhamento';
             milestone5.Data_inicial_prevista__c = Date.today().addDays(31);
             milestone5.Data_final_prevista__c = Date.today().addDays(44);
             milestone5.Projeto_de_Implantacao__c = p.Id;
             mList.add(milestone5);
             
             milestone6 = new Etapas_Projeto_de_implantacao__c();
             milestone6.Name = '06 - Ativação financeira';
             milestone6.Data_inicial_prevista__c = Date.today().addDays(45);
             milestone6.Data_final_prevista__c = Date.today().addDays(45);
             milestone6.Projeto_de_Implantacao__c = p.Id;
             mList.add(milestone6);
             
             milestone7 = new Etapas_Projeto_de_implantacao__c();
             milestone7.Name = '07 - Ativação do Service Desk';
             milestone7.Data_inicial_prevista__c = Date.today().addDays(49);
             milestone7.Data_final_prevista__c = Date.today().addDays(50);
             milestone7.Projeto_de_Implantacao__c = p.Id;
             mList.add(milestone7);                
             
             milestone8 = new Etapas_Projeto_de_implantacao__c();
             milestone8.Name = '08 - Encerramento da implantação';
             milestone8.Data_inicial_prevista__c = Date.today().addDays(46);
             milestone8.Data_final_prevista__c = Date.today().addDays(50);
             milestone8.Projeto_de_Implantacao__c = p.Id;
             mList.add(milestone8);                 
                        
           
       	}   
       }       
    }
    if(!mList.IsEmpty())
    { 
		insert milestone1;
		insert milestone2;
		insert milestone3;
		insert milestone4;
		insert milestone5;
		insert milestone6;
		insert milestone7;
		insert milestone8;
    }
      
  }
}


I have this JSON parser class:

public class GoogleAPIParser {

    public class Address_components {
        public String long_name;
        public String short_name;
        public List<String> types;
    }

    public List<Results> results;
    public String status;

    public class Location {
        public Double lat;
        public Double lng;
    }

    public class Geometry {
        public Location location;
        public String location_type;
        public Viewport viewport;
    }

    public class Results {
        public List<Address_components> address_components;
        public String formatted_address;
        public Geometry geometry;
        public List<String> types;
    }

    public class Viewport {
        public Location northeast;
        public Location southwest;
    }

   
    public static GoogleAPIParser parse(String json) {
        return (GoogleAPIParser) System.JSON.deserialize(json, GoogleAPIParser.class);
    }

}

Which I invoke using:

GoogleAPIParser parser = GoogleAPIParser.parse(jsonResponse);

 

How do I go through and access those attributes within the class that is returned now?

I'm trying to write a SOQL statement that will give me a count of opportunity objects grouped by contact role account. These fields aren't related to each other - the path is:

Opportunity -->
OpportunityContactRole -->
Contact -->
Account

In SQL I'd just join these tables, but I don't know how to do this in SOQL. Any ideas? Thank you!!

i am trying to get a custom object and its related items to show in a table in a visualforce page.  Currently i have the first object showing up but i am not sure how to pull in the related list

 

here is the controller

global with sharing class poistionController {
private Map<string,set<String>> employeeMap=new Map<string,set<String>>();

     public Employees__c pos{get;set;}

     public poistionController() {
        list<Training__C>trainList=[Select name from Training__C where employee__C=:employees__C.Name__c];
         pos = [select ID, Name, Active__C from Employees__c where Active__C= true];

      }

}

 

and here is the page

<apex:page controller="poistionController" showHeader="false">
<apex:relatedList list="Training__C"/>
  
      <apex:pageblock title="test">
      </apex:pageblock>
     
      <apex:dataTable value="{!pos}" var="Employee">
     
     
         <apex:column value="{!pos.name}">
         </apex:column>
        
         <apex:column value="{!pos.id}">
         </apex:column>
         </apex:dataTable>
 

 


</apex:page>

Hi,

I'm getting an error on my trigger when I call the email class I created.  The Line in red is the one causing the error.  
I'm new to apex and any help would be appreciated .
Thanks, Vanessa

The Error

Method does not exist or incorrect signature: [AccCreatedEmailAlert].sendMail(LIST<Task>, SOBJECT:Task)

Class Code

public class AccCreatedEmailAlert{
public static void sendMail (User u, Task t) {
User u1 =[select Email from User where Id =: t.OwnerId limit 1];
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
String[] toAddress = new String[] {u1.Email};
mail.setToAddresses(toAddress);
mail.setSubject('CS-Accommodation Order Task Created');
mail.setPlainTextBody('You are being sent this email because an CS-Accommodation Order Task has been created and assigned to you.\n\nThanks, SFDC');
Messaging.sendEmail(new Messaging.SingleEmailMessage[] {mail});
}
}


Trigger Code

  User-added image


  • May 30, 2014
  • Like
  • 0
Hello!!!
How do I:

1 - Report on a Visualforce page a request  to generate a CSV.
2 - Report on a Visualforce page the day of the week and time that I want to execute the request and send an email with the result.
3 - The class Schedulable Apex will contain the code for sending email.

How do I handle this?

I have the Schedulable class but do not know how to continue ..

global class CSVTest implements System.Schedulable {
    public String mailSouhaite {get; set;}
    public string inputText {get; set;}
   
    global void execute(SchedulableContext sc) {
        planifier();
    }

  
public void planifier(){
    String query=inputText;
    String premier=query.substringAfter('select ');
    premier=  premier.substringBefore('from');
   
    string titre= premier+'\n';
    string contenuCSV = titre;

    string queryResultatString = '';
    list<sObject> queryResultat = (List<sObject>)database.query(inputText);
    for(sObject a: queryResultat)
    {

        queryResultatString = queryResultatString + string.valueof(a);
    }

    list<string> queryLignes = queryResultatString.split('}');

    for(string s:queryLignes){
        list<string> queryColonnes = s.split(',');
        for(string st:queryColonnes){
            contenuCSV = contenuCSV + st.substringAfter('=') + ',';
        }
        contenuCSV = contenuCSV.substringBeforeLast(',').substringBeforeLast(',') + '\n';
    }
    
      //Send Mail
      Messaging.EmailFileAttachment csvPJ = new Messaging.EmailFileAttachment();
      blob csvBlob = Blob.valueOf(contenuCSV );
      string csvNom = 'nom_'+Date.today().format()+'.csv';
      csvPJ.setFileName(csvNom);
      csvPJ.setBody(csvBlob);
      Messaging.SingleEmailMessage email =new Messaging.SingleEmailMessage();
      String[] adressMail = new list<string> {mailSouhaite};
      
      String subject;
      subject = 'CSV - '+Date.today().format();
      email.setSubject(subject);
      email.setToAddresses(adressMail);
      email.setPlainTextBody('Mail....');
      email.setFileAttachments(new Messaging.EmailFileAttachment[]{csvPJ});
      Messaging.SendEmailResult [] envoyer = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});
    }
}
}

-------------------------------------------------------------------------------------------------------------------------

PAGE

<apex:page controller="CSVTest">
  <apex:form >
  <apex:PageBlock >
    :::::::::: TEST TEST TEST :::::::::: <br /><br />
    Mail..........:&nbsp;<apex:inputText styleClass="classeMail" value="{!mailSouhaite}"/><br /><br />
    Request  :&nbsp;&nbsp;<apex:inputText styleClass="classeRequete" value="{!inputText}"/><br /><br /> 
    <apex:commandButton value="SEND" action="{!panifier}"/> <br/><br/>
   
  </apex:PageBlock>
  </apex:form>
</apex:page>
Thank you,

Hi,

 

Can we get $Profile.Name = "System Administrator" in apex trigger.

 

If no then how can I check if the current user is system admin or not.

 

Thaks.

I need to get current user profile name in trigger. I tried by using following way. Is there any possibility to get profile name directly without query.

 

trigger triggerName on CustomObject(after Insert){

Profile ProfileName = [select Name from profile where id = :userinfo.getProfileId()];
if(ProfileName.Name=='System Administrator'){

//code

}

}

  • April 11, 2012
  • Like
  • 0
Hi
can you tell me what is the method for getting current user's profile name in apex class.
 
In visualforce page, we can use    {!$Profile.Name}  
 
 
 
it gives current profile name but i want a relavant method  in apex code.
 
Thanks & Regards
Brijesh Kumar Baser