• JohnSchultz
  • NEWBIE
  • 225 Points
  • Member since 2013

  • Chatter
    Feed
  • 7
    Best Answers
  • 0
    Likes Received
  • 1
    Likes Given
  • 0
    Questions
  • 37
    Replies

I'm new to Apex in general and cannot seem to get this trigger to work...

I have a custom object LOC that has a related custom object called GPO.

I need to have a trigger that will update a related user field on LOC with the owner of the related GPO.

 

I need the related user so I can use it in an approval process.

 

Here is what I have so far and it does nothing. From my research I know maps are needed but I don't understand the concept at this point.

 

trigger LOCapprover on LOC__c (before insert,before update) {
    for(LOC__c loc: Trigger.new){
        if(loc.LOC_GPO__c != null)
    loc.Receiving_User__c = loc.LOC_GPO__r.Owner.Id;  
        
    }    
}

 

Hi All,

 

I am an administrator and have not much apex experience. Having a bit of an issue with my trigger. The purpose of the trigger is to count the number of Activity Records associated to a Lead and then drop it into a field called Activity_Count__c on the Lead. The code all works as intended, but I wanted to add another parameter. I would like to be able to only have that field contain the number of Activity Records that are 'Created By' a certain User (i.e. User ID = '12345'). How would I add that contraint into the Trigger, Class and Test Class? See below.

 

Thanks,

Elliot

 

 

Class:

 

 

public with sharing class LeadActivityCount {

 

    public static Boolean didRun = false;

    public static String ledsPrefix =  Lead.sObjectType.getDescribe().getKeyPrefix();

 

    /*

    * Takes a set of lead IDs, queries those leads, and updates the activity count if appropriate

    */

    public static void updateLeadCounts(Set<ID> ledsIds) {

 

        if (didRun == false) { //We only want this operation to run once per transaction.

            didRun = true;

 

            //Query all the leads, including the tasks child relationships

            List<Lead> leds = [SELECT ID, activity_count__c, (SELECT ID FROM Tasks), (SELECT ID FROM Events) FROM Lead WHERE ID IN :ledsIds];

            List<Lead> updateLeds = new List<Lead>();

 

            for (Lead l : leds) {

                Integer count = l.tasks.size() + l.events.size();

 

                if (l.activity_count__c != count) {

                    l.activity_count__c = count;

                    updateLeds.add(l); //we're only doing updates to leads that have changed...no need to modify the others

                }

            }

 

            //Update the appropriate leads

            try {

                update updateLeds;

            } catch (Exception e) {

                //This is controversial. Anything could happen when updating the opportunity..validation rule, security, etc. The key is we don't

                //want the event update to fail...so we put a try catch around the opp update to make sure we don't stop that from happening.

            }

        }

    }

}

 

 

Test Class:

 

 

@isTest
private class LeadsTestClassName{

public static Boolean didRun = false;
public static String ledsPrefix =  Lead.sObjectType.getDescribe().getKeyPrefix();
   
    /*
    * Test method for this class and TaskUpdateLead and EventUpdateLead
    */
    public static testMethod void testCountTask() {
        //Setup

        Lead leds = new Lead(lastname='Test', email='1@2.com', company='Test');
        insert leds;

        //Insert our first task
        Task t = new Task(subject='Test Activity', whoId = leds.id);
        insert t;

        //Verify count
        leds = [SELECT ID, activity_count__c FROM Lead WHERE ID = :leds.id];
        System.assertEquals(1,leds.activity_count__c);

        //Disconnect task from the lead
        didRun = false; //Reset
        t.whoId = null;
        update t;
        //Verify count = 0
        leds = [SELECT ID, activity_count__c FROM Lead WHERE ID = :leds.id];
        System.assertEquals(0,leds.activity_count__c);

        didRun = false; //Reset
        //Add an event
        Event e = new Event(subject='Test Event', whoId = leds.id, startDateTime = System.Now(), endDateTime = System.now());
        insert e;

        //Verify count = 1
        leds = [SELECT ID, activity_count__c FROM Lead WHERE ID = :leds.id];
        System.assertEquals(1,leds.activity_count__c);

        //Relink the task to the lead
        didRun = false; //Reset
        t.whoId = leds.id;
        update t;

        //Verify count = 2
        leds = [SELECT ID, activity_count__c FROM Lead WHERE ID = :leds.id];
        System.assertEquals(2,leds.activity_count__c);

        //Disconnect the event from the lead
        didRun = false; //Reset
        e.whoId = null;
        update e;

        //Verify count is back down to 1
        leds = [SELECT ID, activity_count__c FROM Lead WHERE ID = :leds.id];
        System.assertEquals(1,leds.activity_count__c);

        //Delete the task
        didRun = false; //reset
        delete t;
        //Verify count is back down to 0
        leds = [SELECT ID, activity_count__c FROM Lead WHERE ID = :leds.id];
        System.assertEquals(0,leds.activity_count__c);

    }
}

 

 

Trigger:

 

 

trigger TaskUpdateLead on Task (after delete, after insert, after undelete, after update) {

    Set<ID> ledsIds = new Set<ID>();
    //We only care about tasks linked to leads.
    String prefix =  LeadActivityCount.ledsPrefix;

    //Add any lead ids coming from the new data
    if (Trigger.new != null) {
        for (Task t : Trigger.new) {
            if (t.WhoId != null && String.valueOf(t.whoId).startsWith(prefix) ) {
                ledsIds.add(t.whoId);
            }
        }
    }

    //Also add any lead ids coming from the old data (deletes, moving an activity from one lead to another)
    if (Trigger.old != null) {
        for (Task t : Trigger.old) {
            if (t.WhoId != null && String.valueOf(t.whoId).startsWith(prefix) ) {
                ledsIds.add(t.whoId);
            }
        }
    }

    if (ledsIds.size() > 0)
        LeadActivityCount.updateLeadCounts(ledsIds);

}

Hi,

I am new to triggers. I wanted to assign FirstName and LastName to customFields, which I have tried as follows.

PLease improve the code. Any help will be appreciated.

 

trigger copyFirstNameLastName on Account (before insert) {
    for(Account ac:trigger.new){
    List<Account> acc = new List<Account>([Select id,FirstName,LastName from Account Where id IN :Trigger.new]); 
                     
    for(Account a:acc){
    if(acc.IsPersonAccount==true){
        if(!acc.isEmpty()){
        acc.First_Name__pc = acc.FirstName;
        acc.Last_Name__pc = acc.LastName;
        }
        }
    update acc;
    }
    }
    
}

 -- Thanks in Advance --

Hi,

 

I have this process that uses a Map.  The key is a field that contains a value that comes from a legacy system.  This is kind of like a key, but not really.  What I mean 99% of the time for a year range of data it is unique but there are one-off situations that require two opportunities for the same company with the same key(remember kind of) data.

 

Up until this little know one-off situation the Map was working perfect; however, because Maps do not allow duplicates on the key I am dropping the duplicate from the process.  To give a more detailed understanding:

 

I get a map of all opportunities for a given date range which is the last year of opporutnities.  I have another object that has these possible matching keys which the process loops over and does a get on the Opp Map.  If I find a match I write the looped data record to an opportunity related object--easy enough and it works great.

 

The problem now are these few duplicates opportunities that are not getting the same record written to its related list.  So my question is this...

 

How can I keep governor limits low (this was why I went with the map approach to begin with) and read each import record (from legacy system), find the matching opportunity so that I can write the import data to the opportunity related object and if not found I would write the import data to an error object?

 

I know I cannot put a select inside of an outer loop because I would quickly hit limits and  a LIST allows duplicates but I don't think it has a quick search method like the map and if it even does--how would I know that I found the first one and search again excluding the first search.  That would seem like double searching for each opportunity!  I am at a loss!  Please help!

 

Hi All,

    

     VF page to hide one of two fields based on picklist value in the same page.plz verify my code is right or worng.im run this  code nothing happen.

 

<apex:page standardController="Account">
<script type="text/javascript">
function changetextbox()
{
var ele=document.getElementById('{!$Component.form1.block1.populate}');
var opt=ele.options[ele.selectedIndex];
if (opt=='Prospect')
{
var newEle=document.getElementById('{!$Component.form1.block1.textpop}');
newEle.disabled=true;
}
}
</script>
<apex:form id="form1">
<apex:pageBlock id="block1">
<apex:inputField value="{!Account.Type}" id="populate" onchange="changetextbox();"/>
<apex:inputField value="{!Account.accountnumber}" id="textpop"/>
</apex:pageBlock>
</apex:form>
</apex:page>

Hi,

 

Please help me in writing the method instead of writing 3 soql statements.

i will pass the owner id it should return all the reporting to ids from salestree upto three levels.

 

trigger salesnotice on Opportunity (after update) {


map<string,string> stnmap=new map<string,string>();
map<Id,String>Reporting2Ids =new map<ID,String>();

for(Opportunity op:trigger.new) { 

if(Trigger.IsUpdate && op.Stagename!=Trigger.oldMap.get(op.Id).Stagename &&(op.StageName=='Confirmed' || op.StageName==' Application' || op.StageName==' Endorsed Confirmed')){
stnmap.put(op.ownerid,op.id);

}
}
salestree(stnmap);
public static void salestree(map<String,String> x){

list<Sales__c> lstst= [select id,Subordinate__c,Subordinate__r.Email,Repo__c,Repo__r.Email from Sales__c where Subordinate__c IN : x.keyset()];
if(!lstst.isempty()){
for(Sales__c s:lstst){
Reporting2Ids.put(s.repo__c,s.Repo__r.Email);
}
}
list <Sales__c> lstst1= [select id,Repo__c,Repo__r.Email from Sales__c where Subordinate__c IN :Reporting2Ids.keyset()];
if(!lstst1.isempty()){
for(Sales__c s:lstst1){
Reporting2Ids.put(s.repo__c,s.Repo__r.Email);
}
}
list <Sales__c> lstst2= [select id,Repo__c,Repo__r.Email from Sales__c where Subordinate__c IN :Reporting2Ids.keyset()];
if(!lstst2.isempty()){
for(Sales__c s:lstst2){
Reporting2Ids.put(s.repo__c,s.Repo__r.Email);
}
}

}
List<string>s =new List<String>();
s=Reporting2Ids.values();

System.debug('**************************>>'+s);

}

 

Thanks In advance.

 

Hello, I am trying to create a visualforce page to show the companies we worked with. So I wrote this (basically this board wrote it for me)

 

<apex:page controller="propinReferences"  sidebar="false"   contentType="text/html" >
<script>
var arraddress= new Array();
var arrid= new Array();
var ref= new Array();
var name= new Array();
var i=0;
var j=0;
document.write('<table border="0px"><tr>');
</script>
<apex:form >
 <apex:repeat value="{!referenceaccounts}" var="acct">
 
    <script>
    //alert('second');
    arraddress[i]='{!acct.name}';
    arrid[i]='{!acct.id}';
    ref[i]='{!acct.Logo__c}';
    name[i]= '{! acct.short_name__c}'

   <!-- ref[i]='<apex:image url="{!acct.Logo_URL__c}" width="50px" height="50px"/>'-->
 document.write('<td><a align="center" valign="bottom" href="https://ap1.salesforce.com/'+arrid[i]+'">'+ ref[i]+'</a></td><td><br /><apex:outputText value="{! acct.name}"/></td>');

     
     j++;
    i++;
    if(j == 5)
   
    {
        document.write('</tr>');
        j=0;
        document.write('<tr>');
    }
   
    </script>
    
 </apex:repeat>
    <script>
        document.write('</tr></table>');
    </script>
</apex:form>

</apex:page>

 But Result makes two columns. I want to display logo and name just below it not nearby. 

 

How Can I achive this? 

 

Thanks, 

 

 

I need to devlop custom chatter application same as current std chatter application  but I am not if we can  develop custom chatter application using Apex code

Good Morning:

 

I created the follwing Apex trigger back in June and it was working wonderfully (creating/deleting child records depending on some field updates from the parent record) and all of a sudden about two weeks ago, the trigger stopped creating the child records. 

 

I opened the developer console and got the following error:

 

 

required (...)+ loop did not match anything at input 'trigger'

 

 

I have done some reading on other posts with the same error message and understand that it means nothing is being passed from the map over to the creation portion of the record. I guess I need to understand why and why it all of a sudden happened when it was working fine for four months.

 

Any help is greatly appreciated.

 

trigger RepSummaryCreation on Video_Turf__c (after update) {
Map<ID, String> releaseName = new Map<ID, String>();
for (Video_Turf__c newDoor2: Trigger.new){
if(newDoor.Assigned__c == TRUE)
releaseName.put(newDoor2.ID, newDoor.Name);

}

List<Rep_Summary__c> newSummary = new List<Rep_Summary__c>();
for(Video_Turf__c turf1 : [Select ID, Name, Date__c, Doors_Per_Rep__c, Rep_One__c from Video_Turf__c where ID in : releaseName.keyset() and Rep_One__c !='']){
newSummary.add(new Rep_Summary__c(
Date__c = turf1.Date__c,
Release__c = turf1.ID,
Doors__c = turf1.Doors_Per_Rep__c,
Name = turf1.Rep_One__c));
}

insert newSummary; 

List<Rep_Summary__c> newSummary2 = new List<Rep_Summary__c>();
for(Video_Turf__c turf2 : [Select ID, Name, Date__c, Doors_Per_Rep__c, Rep_Two__c from Video_Turf__c where ID in : releaseName.keyset() and Rep_Two__c !='']){
newSummary2.add(new Rep_Summary__c(
Date__c = turf2.Date__c,
Release__c = turf2.ID,
Doors__c = turf2.Doors_Per_Rep__c,
Name = turf2.Rep_Two__c));
}

insert newSummary2; 

List<Rep_Summary__c> newSummary3 = new List<Rep_Summary__c>();
for(Video_Turf__c turf3 : [Select ID, Name, Date__c, Doors_Per_Rep__c, Rep_Three__c from Video_Turf__c where ID in : releaseName.keyset() and Rep_Three__c !='']){
newSummary3.add(new Rep_Summary__c(
Date__c = turf3.Date__c,
Release__c = turf3.ID,
Doors__c = turf3.Doors_Per_Rep__c,
Name = turf3.Rep_Three__c));
}

insert newSummary3; 

List<Rep_Summary__c> newSummary4 = new List<Rep_Summary__c>();
for(Video_Turf__c turf4 : [Select ID, Name, Date__c, Doors_Per_Rep__c, Rep_Four__c from Video_Turf__c where ID in : releaseName.keyset() and Rep_Four__c !='']){
newSummary4.add(new Rep_Summary__c(
Date__c = turf4.Date__c,
Release__c = turf4.ID,
Doors__c = turf4.Doors_Per_Rep__c,
Name = turf4.Rep_Four__c));
}

insert newSummary4; 

List<Rep_Summary__c> newSummary5 = new List<Rep_Summary__c>();
for(Video_Turf__c turf5 : [Select ID, Name, Date__c, Doors_Per_Rep__c, Rep_Five__c from Video_Turf__c where ID in : releaseName.keyset() and Rep_Five__c !='']){
newSummary5.add(new Rep_Summary__c(
Date__c = turf5.Date__c,
Release__c = turf5.ID,
Doors__c = turf5.Doors_Per_Rep__c,
Name = turf5.Rep_Five__c));
}

insert newSummary5; 

List<Rep_Summary__c> newSummary6 = new List<Rep_Summary__c>();
for(Video_Turf__c turf6 : [Select ID, Name, Date__c, Doors_Per_Rep__c, Rep_Six__c from Video_Turf__c where ID in : releaseName.keyset() and Rep_Six__c !='']){
newSummary6.add(new Rep_Summary__c(
Date__c = turf6.Date__c,
Release__c = turf6.ID,
Doors__c = turf6.Doors_Per_Rep__c,
Name = turf6.Rep_Six__c));
}

insert newSummary6; 

List<Rep_Summary__c> newSummary7 = new List<Rep_Summary__c>();
for(Video_Turf__c turf7 : [Select ID, Name, Date__c, Doors_Per_Rep__c, Rep_Seven__c from Video_Turf__c where ID in : releaseName.keyset() and Rep_Seven__c !='']){
newSummary7.add(new Rep_Summary__c(
Date__c = turf7.Date__c,
Release__c = turf7.ID,
Doors__c = turf7.Doors_Per_Rep__c,
Name = turf7.Rep_Seven__c));
}

insert newSummary7; 

List<Rep_Summary__c> newSummary8 = new List<Rep_Summary__c>();
for(Video_Turf__c turf8 : [Select ID, Name, Date__c, Doors_Per_Rep__c, Rep_Eight__c from Video_Turf__c where ID in : releaseName.keyset() and Rep_Eight__c !='']){
newSummary8.add(new Rep_Summary__c(
Date__c = turf8.Date__c,
Release__c = turf8.ID,
Doors__c = turf8.Doors_Per_Rep__c,
Name = turf8.Rep_Eight__c));
}

insert newSummary8; 

List<Rep_Summary__c> newSummary9 = new List<Rep_Summary__c>();
for(Video_Turf__c turf9 : [Select ID, Name, Date__c, Doors_Per_Rep__c, Rep_Nine__c from Video_Turf__c where ID in : releaseName.keyset() and Rep_Nine__c !='']){
newSummary9.add(new Rep_Summary__c(
Date__c = turf9.Date__c,
Release__c = turf9.ID,
Doors__c = turf9.Doors_Per_Rep__c,
Name = turf9.Rep_Nine__c));
}

insert newSummary9; 

List<Rep_Summary__c> newSummary10 = new List<Rep_Summary__c>();
for(Video_Turf__c turf10 : [Select ID, Name, Date__c, Doors_Per_Rep__c, Rep_Ten__c from Video_Turf__c where ID in : releaseName.keyset() and Rep_Ten__c !='']){
newSummary10.add(new Rep_Summary__c(
Date__c = turf10.Date__c,
Release__c = turf10.ID,
Doors__c = turf10.Doors_Per_Rep__c,
Name = turf10.Rep_Ten__c));
}

insert newSummary10; 
}

 

Thanks,

 

Hampton

Hi All ,

Please suggest me with the below scenerio.

I have created a vf page , which displays selected products from another vf page . I have used <apex:outputLabel> component to display the selected products names in this page . Based on clicking a certain product from this list , I want to display some xyz output text .

 

The problem I am facing is :

 

I am not able to select a particular product out of the many .

Currently , I am using 'onclick' event on output label , which calls the javascript , which as a result calls the action function , and based on true/false value on the action function method , the "xyz" output text is displayed for all the products , irrelevant to the one I am clicking . What my requirement is : the "xyz" output text should only be displayed for the products which I am selecting out of the many.


I am pasting my current code :

 

VF Page :

 

<apex:page controller="productSelectController" sidebar="false">
<script type="text/javascript">
function expandDetails(){
alert('test');
<!--var a = document.getElementById('{!$Component.tex1}').value;-->
details();
}
</script>
<apex:form >

<apex:pageBlock >
<apex:outputPanel >
<apex:pageBlockSection title="test" />

<apex:pageBlockTable value="{!selectedProduct}" var="sp">
<apex:column >
<apex:outputLabel value="{!sp.name}" onclick="expandDetails();return true;" id="tex1">
<apex:pageBlock >
<apex:outputPanel id="second" >
<apex:pageBlock rendered="{!IF(proDetails,true,false)}">
<apex:outputText >xyz</apex:outputText>
</apex:pageBlock>
</apex:outputPanel>
</apex:pageBlock>
</apex:outputLabel>
</apex:column>
</apex:pageBlockTable>

</apex:outputPanel>
</apex:pageBlock>

<apex:actionFunction name="details" action="{!expandDetailsAction}" reRender="second" oncomplete="alert('After Apex Method');">
</apex:actionFunction>
</apex:form>
</apex:page>

 

 

Controller:

 

public with sharing class productSelectController {


//public Boolean offPB{get;set;}
//public String searchString{get;set;}
//public Filter thisProduct{get;set;}
//public String oppVar;
//public Opportunity oppId{get;set;}
public list<wrapClass> wrpList=new list<wrapClass>();
//public list<PriceBookEntry>listPE;
public wrapClass wrp ;
//public String par{get;set;}
public list<Product2> selectedProduct{get;set;}
public Boolean proDetails= false;
public String second;

public list<Product2> chooseProduct{get;set;}

public productSelectController ()
{
//thisProduct=new Filter();
}
//////PLEASE NEGLECT THIS PART//////  (This controller is shared by 2 pages , this part is for the 1st page)


/*public void Search() {
wrpList.clear();
oppVar=apexPages.currentPage().getParameters().get('oppId');
system.debug('aaaaaaaaa'+oppVar);
String searchLT = '%' + searchString +'%';
system.debug('bbbbbbbb'+searchLT );
oppId=[Select Id, Pricebook2Id,Pricebook2.Name From Opportunity Where Id =: oppVar];
system.debug('ccccccc'+oppId);
if(!offPB){

string strQuery='Select Product2Id,Product2.Name,Product2.Business_Unit__c,Product2.Family from PricebookEntry where Pricebook2Id =\''+oppId.Pricebook2Id+'\' ';
system.debug('dddddddddd'+strQuery);

if(searchString != null && searchString.trim() != ''){
strQuery += 'AND Product2.Name LIKE : searchLT ';
system.debug('eeeeeeeee'+strQuery );
listPE=[select Product2Id,Product2.Name,Product2.Business_Unit__c,Product2.Family from PricebookEntry where Pricebook2Id =:oppId.Pricebook2Id AND Product2.Name LIKE :searchLT AND IsActive = true];
listPE.sort();
system.debug('ffffffff'+listPE);
}
else {
String str_Family;
String str_BU;

if(thisProduct.prdFlter.Business_Unit__c != null && thisProduct.prdFlter.Business_Unit__c != '' )
{
str_BU = '%'+ thisProduct.prdFlter.Business_Unit__c + '%';
system.debug('qqqqqq'+str_BU);
strQuery += 'AND Product2.Business_Unit__c LIKE : str_BU';
system.debug('zzzzzzzz'+strQuery );
}
if(thisProduct.prdFlter.Family != null && thisProduct.prdFlter.Family !='')
{
str_Family = '%' + thisProduct.prdFlter.Family + '%';
system.debug('zzzzzzzz'+str_Family);
strQuery += ' AND Product2.Family LIKE : str_Family';
system.debug('zzzzzzzz'+strQuery );
}
listPE=database.query(strQuery );
system.debug('vvvvvvvvv'+listPE);
}

for(PriceBookEntry pbe : listPE)
{
wrp = new wrapClass(pbe.Product2);
system.debug('xxxxxx'+wrp);
wrpList.add(wrp );
}
system.debug('bbbbbbbbbbbb'+wrpList);

}else{

searchString = '';
string strQuery='Select Product2Id,Product2.Name,Product2.Business_Unit__c,Product2.Family from PricebookEntry where Pricebook2Id != \''+oppId.Pricebook2Id+'\' ';
system.debug('********'+strQuery);
if(searchString != null && searchString.trim() != ''){
strQuery += 'AND Product2.Name LIKE : searchLT ';
system.debug('+++++++++++++'+strQuery);
listPE=[select Product2Id,Product2.Name,Product2.Business_Unit__c,Product2.Family from PricebookEntry where Pricebook2Id !=:oppId.Pricebook2Id AND Product2.Name LIKE :searchLT AND IsActive = true];
system.debug('==========='+listPE);
listPE.sort();
}
else {
String str_Family;
String str_BU;

if(thisProduct.prdFlter.Business_Unit__c != null && thisProduct.prdFlter.Business_Unit__c != '' )
{
str_BU = '%'+ thisProduct.prdFlter.Business_Unit__c + '%';
system.debug('qqqqqq'+str_BU);
strQuery += 'AND Product2.Business_Unit__c LIKE : str_BU';
system.debug('zzzzzzzz'+strQuery );
}
if(thisProduct.prdFlter.Family != null && thisProduct.prdFlter.Family !='')
{
str_Family = '%' + thisProduct.prdFlter.Family + '%';
system.debug('zzzzzzzz'+str_Family);
strQuery += ' AND Product2.Family LIKE : str_Family';
system.debug('zzzzzzzz'+strQuery );
}
listPE=database.query(strQuery );
system.debug('vvvvvvvvv'+listPE);
}
for(PriceBookEntry pbe : listPE)
{
wrp = new wrapClass(pbe.Product2);
system.debug('xxxxxx'+wrp);
wrpList.add(wrp );
}

}
}
*//

 

/This is the "Next " button on page 1 , based on which , selected products are displayed on the 2nd page.
public PageReference Next() {
selectedProduct = new list<Product2>();
for(wrapClass wc : wrpList)
{
if(wc.chkProduct == true)
{
selectedProduct.add(wc.pbeVar);
system.debug('aaaaaa'+selectedProduct);
}
}
return Page.productDetails;
}

 

// This is the method to display the output text ////
public void expandDetailsAction()
{
if(!proDetails)
proDetails = true;
else
proDetails = false;
system.debug('eeeessss'+proDetails );
}
///////////// PLEASE NEGLECT THIS PART /////////  This is related to the first page.
/*public String offProducts()
{
if(!offPB)
offPB=true;
else
offPB=false;

return null;
}

public class Filter
{
public Product2 prdFlter{get;set;}

public Filter(){
prdFlter=new Product2();
}
}

*/

public class wrapClass
{
public boolean chkProduct{get;set;}
public Product2 pbeVar{get;set;}
public wrapClass(Product2 p)
{
pbeVar= p;
chkProduct = false;
}
}

 

public list<wrapClass> getWrpList() {
return wrpList;
}

public list<Product2> getSelectedProduct()
{
return selectedProduct;
}

public Boolean getProDetails()
{

System.debug('999999999'+proDetails );
return proDetails;
}
public void setProDetails(boolean b)
{
this.proDetails = b;
System.debug('mmmmmmmmmmmm'+proDetails );
}

public String getSecond() {
return second;
}

}

 

 

 

Please help!!

Thanks in Advance.

 

 

  • October 21, 2013
  • Like
  • 0

I'm new to Apex in general and cannot seem to get this trigger to work...

I have a custom object LOC that has a related custom object called GPO.

I need to have a trigger that will update a related user field on LOC with the owner of the related GPO.

 

I need the related user so I can use it in an approval process.

 

Here is what I have so far and it does nothing. From my research I know maps are needed but I don't understand the concept at this point.

 

trigger LOCapprover on LOC__c (before insert,before update) {
    for(LOC__c loc: Trigger.new){
        if(loc.LOC_GPO__c != null)
    loc.Receiving_User__c = loc.LOC_GPO__r.Owner.Id;  
        
    }    
}

 

Hi All,

 

I am an administrator and have not much apex experience. Having a bit of an issue with my trigger. The purpose of the trigger is to count the number of Activity Records associated to a Lead and then drop it into a field called Activity_Count__c on the Lead. The code all works as intended, but I wanted to add another parameter. I would like to be able to only have that field contain the number of Activity Records that are 'Created By' a certain User (i.e. User ID = '12345'). How would I add that contraint into the Trigger, Class and Test Class? See below.

 

Thanks,

Elliot

 

 

Class:

 

 

public with sharing class LeadActivityCount {

 

    public static Boolean didRun = false;

    public static String ledsPrefix =  Lead.sObjectType.getDescribe().getKeyPrefix();

 

    /*

    * Takes a set of lead IDs, queries those leads, and updates the activity count if appropriate

    */

    public static void updateLeadCounts(Set<ID> ledsIds) {

 

        if (didRun == false) { //We only want this operation to run once per transaction.

            didRun = true;

 

            //Query all the leads, including the tasks child relationships

            List<Lead> leds = [SELECT ID, activity_count__c, (SELECT ID FROM Tasks), (SELECT ID FROM Events) FROM Lead WHERE ID IN :ledsIds];

            List<Lead> updateLeds = new List<Lead>();

 

            for (Lead l : leds) {

                Integer count = l.tasks.size() + l.events.size();

 

                if (l.activity_count__c != count) {

                    l.activity_count__c = count;

                    updateLeds.add(l); //we're only doing updates to leads that have changed...no need to modify the others

                }

            }

 

            //Update the appropriate leads

            try {

                update updateLeds;

            } catch (Exception e) {

                //This is controversial. Anything could happen when updating the opportunity..validation rule, security, etc. The key is we don't

                //want the event update to fail...so we put a try catch around the opp update to make sure we don't stop that from happening.

            }

        }

    }

}

 

 

Test Class:

 

 

@isTest
private class LeadsTestClassName{

public static Boolean didRun = false;
public static String ledsPrefix =  Lead.sObjectType.getDescribe().getKeyPrefix();
   
    /*
    * Test method for this class and TaskUpdateLead and EventUpdateLead
    */
    public static testMethod void testCountTask() {
        //Setup

        Lead leds = new Lead(lastname='Test', email='1@2.com', company='Test');
        insert leds;

        //Insert our first task
        Task t = new Task(subject='Test Activity', whoId = leds.id);
        insert t;

        //Verify count
        leds = [SELECT ID, activity_count__c FROM Lead WHERE ID = :leds.id];
        System.assertEquals(1,leds.activity_count__c);

        //Disconnect task from the lead
        didRun = false; //Reset
        t.whoId = null;
        update t;
        //Verify count = 0
        leds = [SELECT ID, activity_count__c FROM Lead WHERE ID = :leds.id];
        System.assertEquals(0,leds.activity_count__c);

        didRun = false; //Reset
        //Add an event
        Event e = new Event(subject='Test Event', whoId = leds.id, startDateTime = System.Now(), endDateTime = System.now());
        insert e;

        //Verify count = 1
        leds = [SELECT ID, activity_count__c FROM Lead WHERE ID = :leds.id];
        System.assertEquals(1,leds.activity_count__c);

        //Relink the task to the lead
        didRun = false; //Reset
        t.whoId = leds.id;
        update t;

        //Verify count = 2
        leds = [SELECT ID, activity_count__c FROM Lead WHERE ID = :leds.id];
        System.assertEquals(2,leds.activity_count__c);

        //Disconnect the event from the lead
        didRun = false; //Reset
        e.whoId = null;
        update e;

        //Verify count is back down to 1
        leds = [SELECT ID, activity_count__c FROM Lead WHERE ID = :leds.id];
        System.assertEquals(1,leds.activity_count__c);

        //Delete the task
        didRun = false; //reset
        delete t;
        //Verify count is back down to 0
        leds = [SELECT ID, activity_count__c FROM Lead WHERE ID = :leds.id];
        System.assertEquals(0,leds.activity_count__c);

    }
}

 

 

Trigger:

 

 

trigger TaskUpdateLead on Task (after delete, after insert, after undelete, after update) {

    Set<ID> ledsIds = new Set<ID>();
    //We only care about tasks linked to leads.
    String prefix =  LeadActivityCount.ledsPrefix;

    //Add any lead ids coming from the new data
    if (Trigger.new != null) {
        for (Task t : Trigger.new) {
            if (t.WhoId != null && String.valueOf(t.whoId).startsWith(prefix) ) {
                ledsIds.add(t.whoId);
            }
        }
    }

    //Also add any lead ids coming from the old data (deletes, moving an activity from one lead to another)
    if (Trigger.old != null) {
        for (Task t : Trigger.old) {
            if (t.WhoId != null && String.valueOf(t.whoId).startsWith(prefix) ) {
                ledsIds.add(t.whoId);
            }
        }
    }

    if (ledsIds.size() > 0)
        LeadActivityCount.updateLeadCounts(ledsIds);

}

On the existing VF Page, there are commanlinks used to select products.

IT looks like this:-

 

The   VF page called - Custom Product Selector allows users to add products to the   list using commandlink - Add Link.    <apex:commandlink value="Add"   action="{!ProcessSelected}" rerender="Selected"   style="color:blue">
                                <apex:param name="contIdParam" value="{!p.ID}"   assignTo="{!PBEIdChosen}"/>
                            </apex:commandlink>
  

 

We need CHECKBOXES instead of links, to be able to select several products   at once to the list. 

 

 

Sales User feels it is   a burden to have to enter each product  inidividually then wait for it to   add to the list.

 

Can we provide checkboxes selection instead of links in the Visual force page.?

 

This VF page is trying to mimic the search product page - the standard page to search and add products from the opportunity. The checkboxes on that page, is what we would like to see here in this VF page.

 

 

Is this possible?

Hi !

 

I'm currently running in the following issue :

 

I've defined a custom setting, hierachy type and public visibility.


It contains a text field, this field is filled with a value.


In an apex class, I retrieve this custom setting like this :

global class MyClass{
    
    private static String latitudeLongitude = CustomSetting__c.getInstance().TextField1__c;

}

 

Then I use this field in a method of this class and this is working fine, the value is correctly retrieved.


But when I lanch the following test class, a NullPointerException is thrown on the same line that retrieve the custom setting value.

This is odd because custom settings are initiazed in the test class (This is apex v27)

This is the test method :

static testMethod void TestGoogleGeoCodeUpdater(){
        //Création des custom settings pour les tests
        ALTGEOCODE__Geocode__c CS = new ALTGEOCODE__Geocode__c(
            ALTGEOCODE__Champ_coordonnees__c = 'ALTGEOCODE__Geolocation__c'
        );
        insert CS;
        
        Account compte1 = new Account(
            Name              = 'Test',
            BillingStreet     = 'Revaison Street',
            BillingPostalCode = '60000',
            BillingCity       = 'SP',
            BillingState      = 'Rhône',
            BillingCountry    = 'FRANCE'
        );
        insert compte1;
    }

 

I'm really stuck here, help would be appreciated.

 

Thanks a lot.

  • May 31, 2013
  • Like
  • 0

I have a tigger that works great with a variety of settings and workflows to auto convert lead on approval BUT I want it to be done without creating the opportunity.  I have a custom button to convert without a opportunity but it has to be done mannually... How do I make my trigger use my custon Convert_No_Opp button!!

 

Any help would be great!

 

trigger ConvertLead on Lead (after insert, after update) {
for (Lead lead : Trigger.new) {
if ((lead.isConverted == false)&&(lead.Status == 'Assigned')&& (lead.Exclude_from_workflow__c == false)) //to prevent recursion 
{
 Database.LeadConvert lc = new Database.LeadConvert();
LeadStatus convertStatus = [SELECT Id, MasterLabel FROM LeadStatus WHERE IsConverted=true LIMIT 1];
 lc.setConvertedStatus(convertStatus.MasterLabel);
 
 if (lead.Exclude_from_workflow__c == false){
 Database.LeadConvertResult lcr = Database.convertLead(lc);
System.assert(lcr.isSuccess());}
}
}
 }

 

Hi,

I am new to triggers. I wanted to assign FirstName and LastName to customFields, which I have tried as follows.

PLease improve the code. Any help will be appreciated.

 

trigger copyFirstNameLastName on Account (before insert) {
    for(Account ac:trigger.new){
    List<Account> acc = new List<Account>([Select id,FirstName,LastName from Account Where id IN :Trigger.new]); 
                     
    for(Account a:acc){
    if(acc.IsPersonAccount==true){
        if(!acc.isEmpty()){
        acc.First_Name__pc = acc.FirstName;
        acc.Last_Name__pc = acc.LastName;
        }
        }
    update acc;
    }
    }
    
}

 -- Thanks in Advance --

Hi,

 

I have this process that uses a Map.  The key is a field that contains a value that comes from a legacy system.  This is kind of like a key, but not really.  What I mean 99% of the time for a year range of data it is unique but there are one-off situations that require two opportunities for the same company with the same key(remember kind of) data.

 

Up until this little know one-off situation the Map was working perfect; however, because Maps do not allow duplicates on the key I am dropping the duplicate from the process.  To give a more detailed understanding:

 

I get a map of all opportunities for a given date range which is the last year of opporutnities.  I have another object that has these possible matching keys which the process loops over and does a get on the Opp Map.  If I find a match I write the looped data record to an opportunity related object--easy enough and it works great.

 

The problem now are these few duplicates opportunities that are not getting the same record written to its related list.  So my question is this...

 

How can I keep governor limits low (this was why I went with the map approach to begin with) and read each import record (from legacy system), find the matching opportunity so that I can write the import data to the opportunity related object and if not found I would write the import data to an error object?

 

I know I cannot put a select inside of an outer loop because I would quickly hit limits and  a LIST allows duplicates but I don't think it has a quick search method like the map and if it even does--how would I know that I found the first one and search again excluding the first search.  That would seem like double searching for each opportunity!  I am at a loss!  Please help!

 

Hi All,

 

I have 2 objects.

Contacts

Donations

 

Donations is the child object and have the foreign key contact id in Donations.

Each contact may donate any number of times. 

Contact to Donation have one to many relationship. So one contact has many donations.

 

I want to pull all contact records who donated for past 5 years from now. such that contact should have atleast one donation in each and every year.

 

Ex: 2009,2010,2011,2012,2013

I want the contact records who donated atleast once in 2009 and 2010 and 2011 and 2012 and 2013

 

If contact missed to donate in any one of the year , i dont want that record in my result.

 

Please help me with sql query.

Its urgent

 

Thanks

 

 

Hi All,

    

     VF page to hide one of two fields based on picklist value in the same page.plz verify my code is right or worng.im run this  code nothing happen.

 

<apex:page standardController="Account">
<script type="text/javascript">
function changetextbox()
{
var ele=document.getElementById('{!$Component.form1.block1.populate}');
var opt=ele.options[ele.selectedIndex];
if (opt=='Prospect')
{
var newEle=document.getElementById('{!$Component.form1.block1.textpop}');
newEle.disabled=true;
}
}
</script>
<apex:form id="form1">
<apex:pageBlock id="block1">
<apex:inputField value="{!Account.Type}" id="populate" onchange="changetextbox();"/>
<apex:inputField value="{!Account.accountnumber}" id="textpop"/>
</apex:pageBlock>
</apex:form>
</apex:page>

I am sometimes amazed how a seemingly simple thing is some times made unneccessary difficult. Say you want to start a Live Agent session and have an input field to type an email address in right away without bothering the user with a pre-chat form. Should be as simple as the following code, right?: 

 

<html>
    <head>
	<!-- THIS NEEDS TO BE INCLUDED FOR EVERYTHING TO WORK -->
	<script type='text/javascript' src='https://c.la1c1.salesforceliveagent.com/content/g/deployment.js'></script>
	<script type='text/javascript'>
	liveagent.init('https://d.la1c1.salesforceliveagent.com/chat', '572D0000000011K', '00DD0000000oGsq');
	</script>
	<!-- END INCLUDE -->
    </head>
    <body>
	<!-- THIS IS JUST THE HEADER OF THE PAGE -->
	<h1>Chat med en kundebehandler!</h1>
	
	<!-- HERES THE BUTTON CODE FROM SF. ADD CONTENT WHERE THE COMMENT IS -->
	<div id="liveagent_button_online_573D0000000016a" style="display: none;" >
	    <input type="text" name="email" id="chatter_email" onBlur="emailUpdate()"/><br/>
	    <a href="javascript&colon;//Chat" onclick="liveagent.startChat('573D0000000016a')">Fyll inn din e-post og trykk her for å chatte</a>
	</div>
	<div id="liveagent_button_offline_573D0000000016a" style="display: none;">Kundebehandler offline</div>
	<script type="text/javascript">
	    if (!window._laq) { window._laq = []; }
	    window._laq.push(function()
		{liveagent.showWhenOnline('573D0000000016a', document.getElementById('liveagent_button_online_573D0000000016a'));
		liveagent.showWhenOffline('573D0000000016a', document.getElementById('liveagent_button_offline_573D0000000016a'));
	    });
	    function emailUpdate() {
		liveagent.addCustomDetail('Contact E-Mail', document.getElementById('chatter_email').value).map('Contact', 'Email', true, true, false);
		
	    }
	</script>
	<!-- END OF BUTTON CODE -->
    </body>
</html>

 But no - you get a javascript exception: "you cannot add a detail after page initialization".

 

In practice this means that you can add whatever you like before you load the page, but if you want the user to input something - you're ... toast (that was not the word I wanted to use, so I leave that up to your imagination). 

 

Stuff like that irritates me like a red hot poker up the butt.

 

Thanks for listening :) ...