• JonSimmons
  • NEWBIE
  • 80 Points
  • Member since 2005

  • Chatter
    Feed
  • 3
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 21
    Questions
  • 72
    Replies
i am a salesforce admin brand new to development, and i want to programatically share accounts using apex.  What i am trying to accomplish is automatically share parent accounts with the child account owner, as my org has a private sharing model and right now i have to share each one manually as needed.  if anyone can help me out with some sample code to get started, i will be very greatful.

HI,

I have a triger that creates new task when certain fields in opportunity are changed,

however ic annto deplaoy it because i have no test method.

I have been looking thru the posts here and to be honest i dont get it, in normal apex test method is withing he code, but for trigger its not?

in sll samples i saw there is no reffernce to the trigger or maybe i dont undestand how it suppose to be refferenced.

Here is my trigger below, cna anyone please help me out with a simpe test

trigger assignTask on Opportunity (after update) { List<Task> task = new List<Task>(); List<Opportunity> newOpportunity = new List<Opportunity>(); for (Integer i = 0; i < Trigger.new.size(); i++) { if ((Trigger.new[i].Type == 'New Business')&&(Trigger.new[i].CC_Co_ordinator__c !=null)&&(Trigger.new[i].Finance_Status__c =='Pre-Approved')&&(Trigger.new[i].Optimised_Date__c ==NULL)&& (Trigger.new[i].First_Contact_task_created__c != True)) { System.debug('triggerfire'); task.add(new Task( WhatId = Trigger.new[i].Id, OwnerId=Trigger.new[i].CC_Co_ordinator__c, Subject='First Contact ', ActivityDate = System.today() ) ); } } insert task; }

 

  • March 23, 2009
  • Like
  • 0

Can anyone tell me what is wrong with this simple trigger?  I'm sure I'm just missing something stupid, I'm just not seeing it.  Maybe I'm just completely off track.  I just need to update a single field on the triggering lead upon Insert or Update.

 

Eclipse doesn't give me any real error message, it just says that and unexpected error occured and to try again.

 

 

My code 

******************

 

trigger Calculate_Lead_Qualification_Score on Lead (before insert, before update)
{

    for(Lead theLead : trigger.new)  //loop through each lead that is being inserted or updated
        {

       
            //SFDC doesn't like the line below.  No error, it just won't save if this line is included       
            theLead.Lead_Qualification_Score__c = theLead.Application_Suitability_Score__c + theLead.Budget_Score__c + theLead.Role_Score__c + theLead.Timing_For_Purchase_Score__c;
           
            system.debug('Calculated Lead Qualification Score: ' + theLead.Lead_Qualification_Score__c);
        }
   
}

 

 

 

 

 

thanks

Jon

 

 

I'm just starting to work with the API in PHP and I have run into something odd.

Given this simple query, my results contain everything except the Id of the returned record.

Am I missing something, the Id field is there, but it contains a '0', not the Id of the returned record as expected.

 

 

 

    $query = 'Select UnitPrice, Quantity, PricebookEntryId, OpportunityId, Id From OpportunityLineItem WHERE OpportunityId = \'' . $opportunityId . '\' AND PricebookEntryId = \'' . $salesTaxPricebookEntryId .'\'';
     

      $response = $mySforceConnection->query($query);
      $queryResult = new QueryResult($response);

 

 

 

 

QueryResult Object
(
    [queryLocator] =>
    [done] => 1
    [records] => Array
        (
            [0] => SObject Object
                (
                    [type] =>
                    [fields] => stdClass Object
                        (
                            [OpportunityId] => 006S0000002pi1YIAQ
                            [PricebookEntryId] => 01uS0000000xeDiIAI
                            [Quantity] => 1.0
                            [UnitPrice] => 47.5
                        )

                    [Id] => 0
                )

        )

    [size] => 1
)

 

The Outbound Message contains a SessionId and a ServerURL, Is it possible  to use this SessionId and ServerURL to access Salesforce and avoid login/authentication?

 

Thanks

Jon

 

The APEX Language Reference and Force.com Developers Guides (among others) state that the New collection can be written to in a Before Insert trigger.   Unfortunately when I try to do so, I get a 'Collection is read-only' error.   What gives?

 

 Sample code:

 

 

trigger ProductKits on OpportunityLineItem (before insert)
{

 

//test, just add an opportunitylineitem to trigger.new
            OpportunityLineItem bLineItem = new OpportunityLineItem();
                    bLineItem.quantity = 1;
                    bLineItem.UnitPrice = 100.00;
                    bLineItem.Opportunityid = '006S0000002pi1Y';
                    bLineItem.pricebookentryid = '01u80000003LOTJAA4';
            trigger.new.add(bLineItem);

 

}

 

I have code in production that passes all unit tests and works fine in most cases but in some instances I am getting an Invalid Query Locator error and I can't figure out why.

 

 

My code is a custom rollup trigger that  triggers when a case is 'Closed'.  Rolling up data from cases to their parent accounts.

 

 

My code loops through trigger.new to collect the accountid associated with each case that has just closed.  It then loops through the list of accounts pulling and account record and any associated cases.  Finally it loops through the accounts, loops through each account's cases, and adds up all of the appropriate values depositing the result into fields within the Account then updates the account.  A simple rollup really.

 

 

This works fine most of the time but I have come across some accounts that fail this process, it doesn't matter which case is closed on the account, I always get the same error so the problem is with the account not with the case.  This account has roughly 340 closed cases, though I don't believe that is anywhere near any kind of limit.

 

 

To get to my point, I'm not sure what 'Invalid Query Locator' means in this particular case.  I have seen very little info about the Query Locator, all of it old, but it all suggests problems that occur when querys time out or have been 'garbage collected'.  In this case the error comes back immediately so timeout or memory cleanup should not be an issue.

 

 

 

Below is the relevant code, it's chopped to remove specific custom field names and such so it's pretty ugly.

 

Any help is greatly appreciated.

 

Many Thanks

Jon

 

 

 

 

//if the given trigger has just been closed then roll up the FQTD follup values

set<ID> FQTDAccountIDs = new set<ID>(); //list of Accounts involved with fqtd rollup calculations
map<ID, Account> AccountsToUpdate = new map<ID, Account>(); //the accounts that will be updated by this trigger


//prepare for FQTD rollup

Integer i = 0;
for(case theCase : trigger.new)//loop through all of the available records in the trigger
{
if((trigger.old[i].status != 'Closed') && (trigger.new[i].status == 'Closed'))
{
if(!FQTDAccountIDs.contains(trigger.new[i].accountid))
{
FQTDAccountIDs.add(trigger.new[i].accountid);
System.Debug('Adding Account to the FQTD List: ' + trigger.new[i].accountid);
}
}
i++;
}


//ok, so we may have a list of records to update, lets get to the action
if(FQTDAccountIDs.size() > 0) //do we have any records to update?
{

 

  //loop through all accounts and add them, with their cases, to a map for later looping

for(Account thisAccount : [Select Id, name, (Select casenumber, status From Cases where status = 'Closed') From Account where id in :FQTDAccountIDs])
{
AccountsToUpdate.put(thisAccount.id, thisAccount);
}


//loop through each specified account
for(Account currentAccount : AccountsToUpdate.values())
{




// ****** This next for loop is the apparent problem; System.Exception: invalid query locator ********

//loop through all cases associated with this account
for(Case theCase : currentAccount.Cases)
{

//calculate the fields and rollup the data
// currentAccount.rolledupfield += theCase.rollupfield1__c + theCase.rollupfield2__c
}



}


//update the Accounts with the new values
update AccountsToUpdate.values();



}

 

 

Can anyone give me some pointers on duplicating Hover Links for Events and Tasks? 

 

I have a method that uses VisualForce loading data into a pane, but it's just not what we are looking for.

 

 

Thanks

 

I have built a simple sort of mini-view to provide details of a record when a link is hovered over with the mouse.  It works fine in my dev environment but the onMouseOver doesn't seem to work in production.

 

Basicly I have a table of ActivityHistories with an OnMouseOver event on the subject field, when you hover over the subject the Activity loads into an output panel to the right.  It works fine, in dev.

In production I get the list of ActivityHistories but the OnMouseOver does not work.  I'm not getting any javascript errors or anything.

 

 

I'm not aware of any settings within Salesforce that turn Javascript on/off but maybe I'm just missing something.   Can anyone give me any idea what I'm missing?

 

Thanks

 Jon

 

 

 

The Code

 

 

 

<apex:page standardController="Account" sidebar="false" showHeader="false">
   
    <apex:pageBlock title="Activity History">
        <apex:form >
        <table border="0" cellspacing="4">
        <tr>
        <td valign="top" width="375">
            <apex:dataTable value="{!account.ActivityHistories}" var="open" cellPadding="1" cellspacing="4" border="0">
               
               
               
                <apex:column width="200">
                    <apex:facet name="header"><b>Subject</b></apex:facet>
                    <apex:outputPanel >
                        <apex:actionSupport status="requesting" event="onmouseover" rerender="detail" >
                            <apex:param name="cid" value="{!open.id}" />
                        </apex:actionSupport>
                          <b>{!open.Subject}</b>
                    </apex:outputPanel>
                </apex:column>
 
            
               
                <apex:column >
                    <apex:facet name="header"><b>Status</b></apex:facet>
                    {!open.Status}
                </apex:column>

               

            </apex:dataTable>
            </td>
            <td>
           
     <apex:outputPanel id="detail">
        <apex:actionStatus id="requesting" >
            <apex:facet name="start">
                <apex:outputPanel >  <!-- Using a panel to make the facet work - only allows one child... -->
                    <apex:image url="{!$Resource.AjaxRoller}" alt="loading..."/>
                    <apex:outputText > ... Loading ... </apex:outputText>
                </apex:outputPanel>
            </apex:facet>
            <apex:facet name="stop">
                <apex:detail subject="{!$CurrentPage.parameters.cid}" relatedList="false" title="false" />
            </apex:facet>
        </apex:actionStatus>
    </apex:outputPanel>
           
           
            </td>
           
            </tr>
            </table>
           
        </apex:form>
    </apex:pageBlock>
   
   
</apex:page>

 

Hi,

 

I'm trying to develop a very simple trigger that essentially creates a contact and a few contact share records when a User record is created.  

 

In my dev environment the trigger and all of the unit tests work flawlessly, when I transfer to production the trigger doesn't even fire and as a result my unit tests fail. 

When I run the tests I get no indication that the Trigger even attempted to run, let alone some error to tell me why it might be failing.  Also, System.Debug within the Trigger doesn't show in my test output.

 

The trigger itself is below.  I can post the support class code if needed but it doesn't seem to be getting that far so I don't know if it will help.

 

Any help is greatly appreciated.

 

Thanks

Jon

 

 

 

trigger User_Create_ContactSharing_Trigger on User (after insert)

{

 

// User Create ContactShareing Trigger

 

 

 

 

System.Debug('Inside Insert Trigger');

 

//get the user data and pass to the function in our support class

User[] theUsers = [select id,name,firstname,lastname,companyname, email, phone, defaultcurrencyisocode from User where id in :trigger.new];

 

 

//loop through all new users

 for(User newUser :theUsers)

{

 

User_Contact_Trigger_Class.User_Create_Trigger(newUser);

 

}

 

 

}

I'm trying to create a trigger on Asset, after Undelete.

 

I simply want to set a flag to denote that the record has been undeleted.

 

 I expect that I should be able to do something like the following, but I get an "Attempt to de-reference a null object" error on the for loop line.

 

 

trigger Asset_Intercept_UnDelete on Asset (after undelete)

{

 

    for(Asset undeletedAsset : trigger.old)

  {

     Asset theAsset = [select undeleted__c from Asset where id in :trigger.old];

     theAsset.undeleted__c = true;

     update theAsset;

  } 

}

 

 

Any help or pointers are greatly appreciated.

 

 

Thanks

Jon

 

I would like to create a Trigger that captures a user's attempt to delete a record and instead mark that record as "Inactive" and cancel the delete request.
 
I have attempted to use the beforeDelete and afterDelete triggers, as well as attempted to allow the delete and then undelete the record afterwards.  I keep running into various walls.
 
I imagine that this is something that is probably fairly common yet I can't find any examples of how best to do this. 
Can anyone give me some ideas or otherwise point me in the right direction?
 
 
Thanks
Jon
 
 
I am working on writing a set of triggers with success but I'm struggling with the Unit Tests.   My trigger code works perfectly but I can't get salesforce to accept my unit tests, it seems like the more unit tests I create the lower my unit test coverage gets.
 
As I understand it any method marked with the TestMethod modifier is defined as a test method and therefore should not be used to calculate the percentage of coverage on the remaining code.  I am running the tests at Salesforce in my Dev Org and I can see which lines of code are not covered and which are covered, as I mark my code with the testmethod modifier I see the uncovered lines go away, but so does my percentage of covered code.
 
I believe that the problem is that I'm not calling my methods directly, but rather creating/updating/deleting records that should fire triggers that call my methods.  As I understand it, this should be sufficient as the code that the trigger calls should be included in the test, but this isnt' what I'm seeing happening.  Conversely, if I do call my methods directly I get the exact same results, salesforce reports that I'm not testig the methods that I am calling and then assertion testing.
 
Everything I do seems to make the situation worse so I'm at a loss as to how to create unit tests at all.
 
Can someone take a look at the code below and give me an example of a unit test to cover this portion of my code?  That should get me moving in the right direction for the remainder.
 
 
 
The trigger should fire upon insert of a custom object, the result should be the insert of a new ContactShare object with userid and contactid from the custom object.   The code works flawlessly, I just can't seem to make the UnitTests work.
 
Many Thanks
Jon
 
 
 
 

trigger Sharing_on_Additional_Contact_Owner on Additional_Contact_Owner__c (before delete, after insert, after update)

{

   if (Trigger.isInsert) //we must be inserting

   {

      Classes_and_Unit_Tests.InsertContactShare(Trigger.new[0].Contact_Name__c, Trigger.new[0].Additional_Contact_Owner_Name__c);

   }

}

 
 
 

public class Classes_and_Unit_Tests

{

   public static void InsertContactShare(id newContactId, id newOwnerId)

   {

   // given an Additional_Contact_Owner__c record, insert a new contactshare record providing Contact access to a User

      try

      {

            //instantiate the object

            ContactShare theShare = new ContactShare();

            //update the object

            theShare.ContactAccessLevel = 'Edit';

            theShare.ContactId = newContactId;

            theShare.UserOrGroupId = newOwnerId;

            //insert it into salesforce

            insert (theShare);

      }

      catch (Exception e)

      {

      //do nothing for now

      }

}  //end insertcontactshare method

 

} //end class

 
 
 
 
 
I'm trying to write a trigger on a custom object that will insert/update/delete ContactShare records upon insert/update/delete of the custom object.
 
I have been running into a wall where Salesforce simply won't allow me to save and gives me only an "unknown error".
I recently moved my code to a different dev org and the same code gets a new error.  "DML not allowed on ContactShare"
 
I have found a bunch of old posts with the same sort of error but no real resolution to any of them and a few allude to the possibility that this is some kind of bug.
 
Is this a bug, is there some way around it, if DML is not allowed what other methods of Insert/Update/Delete are available?
 
 
Thanks alot
Jon
 
I have developed a simple trigger that works fine on my dev org and a clients Enterprise org.  I'm attempting to create this same Trigger on another client's org but Eclipse wont save it for me.
 
I have created the project so I have a stub trigger without issue but when I copy in my trigger code and try to save I just get a warning that says "File only saved locally, not on server", but no reason why and no actual error.
 
I found that if I set the Trigger to Inactive then Eclipse will upload the code but I cannot Activate the trigger.
 
Is there a permission that I dont know about that will allow me to create a trigger but not actvate it?  Is there some trick to activating this trigger that I didnt need on the other orgs?
 
Thanks
Jon
 
 
 
Can anyone provide a code snippet (in any language) that shows the proper method of bypassing a proxy server to allow API access to salesforce?
 
My code looks like this, but it's not working as expected.  (C#)
Code:
                System.Net.IWebProxy myProxy;
                myProxy = new System.Net.WebProxy();
                System.Uri myUri = new System.Uri(binding.Url);
                myProxy.GetProxy(myUri);

                binding.Proxy = myProxy;

                loginResult = binding.login(user, pass);
 
 

 Thanks
Jon

 
I am using PrintAnything to create a series of custom forms, I'm using multiple queries to pull data from various sources and compiling it all onto my forms.
 
I have found that some of the fields that I need simply will not be made available by printanything.  (Maybe it should be called, Print AlmostAnything :) )
 
These fields are custom fields and their datatype varies from Lookup to Text fields.  I am able to get other custom fields without issue.  When I run in Debug mode these fields simply are not included in the query results.  It doesn't matter whether I use a SOQL query or retrieve I get the same results.
 
 
Any thoughts or help?
 
Thanks
Jon
 
 
Is there any information available about inserting Javascript code into a PrintAnything print package? 
I have attempted to insert some basic javascript code but it doesn't seem to be working and I can't seem to call it from within my template. 
 
Any guidance would be appreciated.
 
 
Thanks
Jon
 
Is there a method provided for formatting numbers in PrintAnything?
 
I have a Number field that is set to 8.0, but even though it's not supposed to have any decimal places PrintAnything still prints .0 on the end of each number.   Is there any number formatting available that will help me to get rid of this .0?
 
Thanks
Jon
 
I have created a couple of templates pulling data from a series of queries but when the templates are displayed some of the data is showing but other data is not.  What is even more strange is that some of the data within a given query result shows while other data does not.

It does not seem to matter whether or not I use a Retreive query or a where clause, I get the same strange result.

Has anyone seen this happen and/or give me some idea where to look for an answer?

Thanks
Jon


I am writing some software and I would like it to be re-distributable and work with any SFDC user's organization, so I'm using the partner WSDL. Unfortunatly I have found that the partner WSDL is shy of ALOT of the standard objects, Product2 for example.

I can run a query like "SELECT id, name FROM Product2" and get results but then I can't cast them to a Product2 object. Is there some other way that I can get to the data?

Thanks
Jon
I am querying for a list of Opportunities based upon lastmodifieddate and a couple of other fields, I would like to return an array of Opportunities from my function. I can get the data but when I try to cast the resulting array into an array of Opportunities I get the "Specified Cast is Invalid" error. I have tried updating the WSDL with no joy.

Any help is greatly appreciated.



My Code:



private Opportunity[] GetUpdatedClosedOpportunities(SqlDateTime startTime, SqlDateTime endTime)
{
Opportunity[] thegoods = null;

QueryResult qr = null; //storage location for returned data
binding.QueryOptionsValue = new sforce.QueryOptions(); //define the query specifications
binding.QueryOptionsValue.batchSize = 450; //number of records to return.
binding.QueryOptionsValue.batchSizeSpecified = true; //specify that the above item is supplied

string startTimeString = "2005-12-15T21:43:31.000Z"; //temporarily hard coded for testing
string sqlStatement = "SELECT id, name FROM Opportunity WHERE isclosed = TRUE AND lastmodifieddate > " + startTimeString;
try
{
qr = binding.query(sqlStatement);
thegoods = (Opportunity[]) qr.records; //Cast Invalid error here!!

return thegoods;
}
catch (Exception ex)
{
Console.WriteLine ("Failed to get Opportunity: " + ex.Message);
}
return thegoods;
}

Message Edited by JonSimmons on 01-05-2006 07:20 AM

Can anyone tell me what is wrong with this simple trigger?  I'm sure I'm just missing something stupid, I'm just not seeing it.  Maybe I'm just completely off track.  I just need to update a single field on the triggering lead upon Insert or Update.

 

Eclipse doesn't give me any real error message, it just says that and unexpected error occured and to try again.

 

 

My code 

******************

 

trigger Calculate_Lead_Qualification_Score on Lead (before insert, before update)
{

    for(Lead theLead : trigger.new)  //loop through each lead that is being inserted or updated
        {

       
            //SFDC doesn't like the line below.  No error, it just won't save if this line is included       
            theLead.Lead_Qualification_Score__c = theLead.Application_Suitability_Score__c + theLead.Budget_Score__c + theLead.Role_Score__c + theLead.Timing_For_Purchase_Score__c;
           
            system.debug('Calculated Lead Qualification Score: ' + theLead.Lead_Qualification_Score__c);
        }
   
}

 

 

 

 

 

thanks

Jon

 

 

I'm just starting to work with the API in PHP and I have run into something odd.

Given this simple query, my results contain everything except the Id of the returned record.

Am I missing something, the Id field is there, but it contains a '0', not the Id of the returned record as expected.

 

 

 

    $query = 'Select UnitPrice, Quantity, PricebookEntryId, OpportunityId, Id From OpportunityLineItem WHERE OpportunityId = \'' . $opportunityId . '\' AND PricebookEntryId = \'' . $salesTaxPricebookEntryId .'\'';
     

      $response = $mySforceConnection->query($query);
      $queryResult = new QueryResult($response);

 

 

 

 

QueryResult Object
(
    [queryLocator] =>
    [done] => 1
    [records] => Array
        (
            [0] => SObject Object
                (
                    [type] =>
                    [fields] => stdClass Object
                        (
                            [OpportunityId] => 006S0000002pi1YIAQ
                            [PricebookEntryId] => 01uS0000000xeDiIAI
                            [Quantity] => 1.0
                            [UnitPrice] => 47.5
                        )

                    [Id] => 0
                )

        )

    [size] => 1
)

 

The Outbound Message contains a SessionId and a ServerURL, Is it possible  to use this SessionId and ServerURL to access Salesforce and avoid login/authentication?

 

Thanks

Jon

 

The APEX Language Reference and Force.com Developers Guides (among others) state that the New collection can be written to in a Before Insert trigger.   Unfortunately when I try to do so, I get a 'Collection is read-only' error.   What gives?

 

 Sample code:

 

 

trigger ProductKits on OpportunityLineItem (before insert)
{

 

//test, just add an opportunitylineitem to trigger.new
            OpportunityLineItem bLineItem = new OpportunityLineItem();
                    bLineItem.quantity = 1;
                    bLineItem.UnitPrice = 100.00;
                    bLineItem.Opportunityid = '006S0000002pi1Y';
                    bLineItem.pricebookentryid = '01u80000003LOTJAA4';
            trigger.new.add(bLineItem);

 

}

Hi,

 

Scenario : I have custom object called SFDC_Project__c which has look up to cases through Case__c field.

When i create case and through same detail page through related list if i click New Project, i want to copy value of Trigger_Value field  from cases to project Cases_Trigger_Value__c after clicking save.

 

I have written trigger on project:

 

trigger SetPrimaryContact on SFDC_Project__c (before insert) 
{

for (SFDC_Project__c o : Trigger.new)
{
List<Case> contactRole = new List<Case>();
contactRole = [select ID, Trigger_Value__c from Case where Id = :o.Case__r.id limit 1];
o.Cases_Trigger_Value__c = contactRole[0].Trigger_Value__c;

insert o;

}
}

  Once i save i get error :

 Error: Invalid Data. Review all error messages below to correct your data.
Apex trigger SetPrimaryContact caused an unexpected exception, contact your administrator: SetPrimaryContact: execution of BeforeInsert caused by: System.ListException: List index out of bounds: 0: Trigger.SetPrimaryContact: line 8, column 47

 

Any help will be appriciated .

 

Thanks & Regards,

Abhijit

Message Edited by Abhijit on 09-21-2009 12:34 PM
  • September 21, 2009
  • Like
  • 0

I have a very simple web controller that I need to write test code for:

 

 

public class web_controller_testimonial_list {

public list<Testimonial__c> listResults = new list<Testimonial__c>();

public list<Testimonial__c> getTestimonials() {
listResults = [SELECT quote__c, contact_name__c, contact_title__c, account_name__c FROM Testimonial__c WHERE Status__c = 'Published' ORDER BY Quote_Date__c desc];
return listResults;
}

public list<Testimonial__c> fetchTestimonials() {
getTestimonials();
return null;
}

}

 

 

 And really, I suppose it could be scaled down to something a little more simple, for the sake of this post:

 

 

public class web_controller_testimonial_list {

public list<Testimonial__c> getTestimonials() {
listResults = [SELECT quote__c, contact_name__c, contact_title__c, account_name__c FROM Testimonial__c WHERE Status__c = 'Published' ORDER BY Quote_Date__c desc];
return listResults;
}

}

 

 ... actually, I don't even know where to start.  I've been learning as I go, and I'm stumped.  How would I write a test case for something like this?

Thank you,

 

~ Nick

 

Message Edited by infowelders_ns on 09-21-2009 02:28 PM
There is a particular line of code that seems to be tricky for me in test methods. I have used this in various triggers, most of which seem to cover this line of code automatically, without any intentional additional code; however, a couple of my test methods are not covering this line of code, and I am wondering if there is a technique for covering this. This can be problematic, especially in very small triggers, where this line of code could make or break the 75% coverage.
 

}Catch(Exception e){}

 
My second question is: Say you have a trigger that creates a new record when triggered; how would you go about querying that newly created record in a test method? I'm guessing there is a simple line of code to use, I just don't know that line of code.
 
Can anyone help me out? Thanks in advance!

What is the Best approach if we want to Calculate SUM of ChildRelationship records (through LookUp relationship) NOT Mast-Detail Relationship.

 

My scenerio is this:

 

Contact: Name, Balance

Bill:         Name, Amount, Contact__c (Lookup Field)

 

So I want to Fire a trigger on Bill such that whenever a Bill is updated I can Update Contact.Balance value with SUM of Amount for ALL Bills Where Contact__c = current_saving_bill.Contact__c.

 

 

 

Also I'm not able to work this approach with this case: Say If I change Contact__c value in bill so I now Want to Update Contact.Balance value for current edited bill's OLD Contact__c and NEW Contact__c value. :( can anyone help me devise a solution for this ...

 

 

  • September 17, 2009
  • Like
  • 0

code:

 

trigger LeadConvertoContact on Lead (after update) {
    for(Lead l :Trigger.new)
    {
        if(l.IsConverted==true)
        {
            List<UsageLog__c> uls=[select id,Contact__c,OwnerId from UsageLog__c where leadname__c=:l.Id and Contact__c=:''];
            for(UsageLog__c uc:uls)
            {
                uc.Contact__c=l.ConvertedContactId;       
                //uc.OwnerId=l.OwnerId;                   
            }

           

            //If I comment out this line of code  can be saved to the server    ....... why?           

           update uls;                 

        }
    }
}

 

 

THanks!

Message Edited by netbrain on 09-21-2009 11:16 PM
i am a salesforce admin brand new to development, and i want to programatically share accounts using apex.  What i am trying to accomplish is automatically share parent accounts with the child account owner, as my org has a private sharing model and right now i have to share each one manually as needed.  if anyone can help me out with some sample code to get started, i will be very greatful.

 

I have code in production that passes all unit tests and works fine in most cases but in some instances I am getting an Invalid Query Locator error and I can't figure out why.

 

 

My code is a custom rollup trigger that  triggers when a case is 'Closed'.  Rolling up data from cases to their parent accounts.

 

 

My code loops through trigger.new to collect the accountid associated with each case that has just closed.  It then loops through the list of accounts pulling and account record and any associated cases.  Finally it loops through the accounts, loops through each account's cases, and adds up all of the appropriate values depositing the result into fields within the Account then updates the account.  A simple rollup really.

 

 

This works fine most of the time but I have come across some accounts that fail this process, it doesn't matter which case is closed on the account, I always get the same error so the problem is with the account not with the case.  This account has roughly 340 closed cases, though I don't believe that is anywhere near any kind of limit.

 

 

To get to my point, I'm not sure what 'Invalid Query Locator' means in this particular case.  I have seen very little info about the Query Locator, all of it old, but it all suggests problems that occur when querys time out or have been 'garbage collected'.  In this case the error comes back immediately so timeout or memory cleanup should not be an issue.

 

 

 

Below is the relevant code, it's chopped to remove specific custom field names and such so it's pretty ugly.

 

Any help is greatly appreciated.

 

Many Thanks

Jon

 

 

 

 

//if the given trigger has just been closed then roll up the FQTD follup values

set<ID> FQTDAccountIDs = new set<ID>(); //list of Accounts involved with fqtd rollup calculations
map<ID, Account> AccountsToUpdate = new map<ID, Account>(); //the accounts that will be updated by this trigger


//prepare for FQTD rollup

Integer i = 0;
for(case theCase : trigger.new)//loop through all of the available records in the trigger
{
if((trigger.old[i].status != 'Closed') && (trigger.new[i].status == 'Closed'))
{
if(!FQTDAccountIDs.contains(trigger.new[i].accountid))
{
FQTDAccountIDs.add(trigger.new[i].accountid);
System.Debug('Adding Account to the FQTD List: ' + trigger.new[i].accountid);
}
}
i++;
}


//ok, so we may have a list of records to update, lets get to the action
if(FQTDAccountIDs.size() > 0) //do we have any records to update?
{

 

  //loop through all accounts and add them, with their cases, to a map for later looping

for(Account thisAccount : [Select Id, name, (Select casenumber, status From Cases where status = 'Closed') From Account where id in :FQTDAccountIDs])
{
AccountsToUpdate.put(thisAccount.id, thisAccount);
}


//loop through each specified account
for(Account currentAccount : AccountsToUpdate.values())
{




// ****** This next for loop is the apparent problem; System.Exception: invalid query locator ********

//loop through all cases associated with this account
for(Case theCase : currentAccount.Cases)
{

//calculate the fields and rollup the data
// currentAccount.rolledupfield += theCase.rollupfield1__c + theCase.rollupfield2__c
}



}


//update the Accounts with the new values
update AccountsToUpdate.values();



}