• jbroquist
  • SMARTIE
  • 510 Points
  • Member since 2008

  • Chatter
    Feed
  • 18
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 15
    Questions
  • 93
    Replies

HI 

I am  facing the above error when i am trying to follow the record after saving.

 

Please  clarify.

I'm trying to do a trigger that doesn't let anyone close the case if I have tasks opened in the case.

 

If you try to close the case an error will appear.

 

Code:

 

trigger ChamadoAbertoTarefaAberta on Case (after update) {

    {
        List <Task> statuslist = [SELECT id, Status FROM Task WHERE WhatId IN :trigger.new AND Status statuslist.add(t.WhatId, true)];
        MAP<id,string> statuslist= new LIST<Id,String>(); 
   		for(Task t : trigger.new) 
        }
            
            for(Case c : trigger.new()){
            if(map.get(c.Id) == true){
            c.addError(My error here); 
            }
            else{
            break; 
}
            }
}

 I don't know where I'm going wrong.

 

Thanks for help !

Hi,

I have two object QOD__c--> child object, Approval_Status__c is a field on this object

Project__c--> Parent Object, Project_State__c is a field on this object.

 

I'm writting a trigger whenevr Approval_Status__c changes and equal to Approved then update the Project__State__c to "Closed"

 

below is the trigger but m getting error on it...

trigger Populate on Quality_of_Delivery__c (after update) {

List<Project__c> Lstprj=new List<Project__c>(); Set<Id> PrjId =new Set<Id>();

Lstprj=[Select Id from Project__c];

for(Project__c proj : lstprj){

PrjId.add(proj.Id);

}

    Map<Id,Project__c> prj = new Map<Id, Project__c>([select Project_State__c,Id from project__c where id in :prjid]);//Getting error here..DML requires SObject or SObject list type: MAP<Id,Project__c> at line 30 column 13 

 

      for(Quality_of_Delivery__c q: Trigger.new)  

{  

 

if(trigger.oldmap.get(q.Id).Approved_Status__c!=trigger.newmap.get(q.Id).Approved_Status__c)  

 

    {  

 

    if(  trigger.newmap.get(q.Id).Approved_Status__c=='Approved'){

                     prj.get(q.Project__c).Project_State__c='Closed';      

                          }      

      }         

    update prj;  

        

                      }

  }

 

please look into this

i figured this should be pretty simple. I have a custom object called ONSITE_PRODUCT__c

onsite_product__c has a lookup field called product__c which has a lookup relationship to the salesforce products object. 

 

ive created a new picklist field called New_products__c which also has a list of the same products as the product__c lookup field. I want a user to select a product from the New_products__c picklist and have that same product value saved as the product lookup field value.

 

heres my trigger

 

trigger UpdateOnsiteProduct on Onsite_Product__c (before insert,before update) {
    { 
        for (Onsite_Product__c a : Trigger.new) 
        { 
            a.Product__c = a.New_Products__c;
        }
    }
}

 

 

and this is the error i keep receiving

 

Error: Invalid Data. 
Review all error messages below to correct your data.
Apex trigger UpdateOnsiteProduct caused an unexpected exception, contact your administrator: UpdateOnsiteProduct: data changed by trigger for field Product: id value of incorrect type: XYZ PRODUCT

 

Thanks.

Can someone help me with the code for a trigger that rolls up opportunity values into a custom object?  For example:

 

Custom Object  = Forecast_C

 

Custom Object Field  to update = Q1_Bookings_c

 

The information will come from

 

Opportunity Object Fields

 

Closed_To_Date_C + (Opportunities at the stage Closed Won) - With a close date in current FQ

 

Any help?

 

  • February 26, 2013
  • Like
  • 0

Hi,
In visualforce, there's code like

This can be used for string output formatting.

Is there simillar one in Apex, like

Dicimal d = 4000.0;
How can I convert it to a string like '4,000.0'

I tried 2 ways, both failed
1) d.format() , this will be displayed like '4,000'
2) String.format: don't know how to use this API. There's no document from SFDC about this

I have an object that holds over 800,000 apartment units.  One date field is Available__c which tells us when that apartment unit is available.  If a client enters an available date as today and that unit is still available tomorrow, I want the date to automatically update tomorrow.  I don't want to run a report each morning and update the dates using the data loader.

 

How would I go about writing code that evaluates all dates in the Unit Object that are older than today and changing the date to today?

 

Some of the fields of the Object are CommencementDate, Expiry Date and Termination Date

I want to write a trigger 

1)If the commencement date has not happened yet – it should trigger to pending

Can I try After Insert After Update Trigger

 



for(Office off: Trigger.new)
{
system.debug('Trigger.New size' +Trigger.New.size());
try
{
if(off.CommencementDate__c == ' ??')
off.Description = 'It is pending';
else if(off.CommencementDate__c==' ??')
off.Description = ' Active ';
}
catch (Exception e)
{
system.debug('Error');
}
}



How to write date trigger ?

Hello All,

I am getting 

Error: Compile Error: Expression cannot be assigned at line -1 column -1

global class UpdateAllOpportunities implements Database.Batchable<sObject> { 
// This is the query that is passed to the execute method. 
// It queries all of the Opportunities with specific criteria Pipeline
String query = 'Select Id,OwnerId FROM Opportunity WHERE (StageName != Sold OR StageName != Not Sold) AND Revenue__c > 500000';

global database.queryLocator start(Database.BatchableContext BC) {
return database.getQueryLocator(query); 

} //close start method 

global void execute(Database.BatchableContext BC, list <Opportunity> scope) {
List<Task> taskList = new List<Task>(); 
// Iterate through the whole query of Opportunities and create tasks requesting update 
// Create a Task that's associated with each Opportunity. 
for(Opportunity o : scope) { 
Task tsk = new Task(); 
tsk.OwnerId = o.OwnerId; 
tsk.ActivityDate = System.today()+ 3; 
tsk.Status = 'Not Started'; 
tsk.Subject = 'Weekly Opportunity Update Reminder';
task.description = 'Please update the task with work planned and completed for the week by Wednesday';
task.priority = 'High'; 
task.IsReminderSet = 'true';
task.ReminderDateTime = System.today()+1;
taskList.add(tsk);

} //close for-loop 
try {
insert taskList; 
} catch (system.dmlexception e) { 
System.debug('Tasks not inserted: ' + e); 

try {
update scope; 
} catch (system.dmlexception e) {
System.debug('Scope not updated: ' + e); 

} //close execute method 
global void finish(Database.BatchableContext BC) {
AsyncApexJob a = [Select Id, Status, NumberOfErrors, JobItemsProcessed,TotalJobItems,CreatedBy.Email from AsyncApexJob where Id = :BC.getJobId()];
// Create and send an email with the results of the batch.
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage(); 
mail.setToAddresses(new String[] {a.CreatedBy.Email}); 
mail.setReplyTo('Salesforce.NoReply@optum.com'); 
mail.setSenderDisplayName('Strategic Opportunity Task Creation Batch Processing');
mail.setSubject('Opportunity Task Creation Update ' + a.Status); 
mail.setPlainTextBody('The batch apex job processed ' + a.TotalJobItems + ' batches with ' + a.NumberofErrors + ' failures.'); 
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail }); 
} //close finish method 
} //close class

I am trying to create a batch apex to create tasks when Opportunity meets a specific criteria.

 

Also can someone tell me how I can set the notification flag to true in this code?

 

thanks for your help

SAK

 

  • February 25, 2013
  • Like
  • 0

Could someone help me?

 

I created the following trigger.

 

trigger RFTSetPDStatus on RFT_Category__c (before insert, before update) {
  if (Trigger.isInsert)
  { 
    for(RFT_Category__c pd:Trigger.new)
    {
        pd.PD_Status__c='Open';      
    }
  }
  if (Trigger.isUpdate)
  {
    Integer msExist=null;
    Integer msCnt=null;  
    for(RFT_Category__c pd:Trigger.new)
    {
        msExist=[SELECT COUNT() FROM Ichthys_RFT__c WHERE RFT_Category__r.Id = :pd.Id];
        if(msExist==0)
        {
          pd.PD_Status__c ='Open';
        }
        else
        {
          msCnt = [SELECT COUNT() FROM Ichthys_RFT__c WHERE RFT_Category__r.Id = :pd.Id AND Status__c <>'Completed'];
          if(msCnt==0)
          {
            pd.PD_Status__c ='Close';
          }
          else if(msCnt>0)
          {
            pd.PD_Status__c ='Open';
          }
        }
    }
  }
}

 

When I try to update over 1500 data from Apex Dataloader,

the error "System.LimitException: Too many SOQL queries: 101" occurred.

So I split data into 50 and updated them. 

Is there any way to update over 1500 data by changing this trigger code?

 

Thanks in advance for your support!

 

Anna

  • February 22, 2013
  • Like
  • 0

Can somebody help me write a function that computes

 

the sum of numbers from 1 to 1000 and return the result.

 

I just want to be sure I am not making a mistake

I can't seem to get my test code to check a chunk of my trigger.  I have a trigger, a class to prevent recursion, and my test class.

 

Trigger (basically any time the Opp Stage changes a pair or records are created in a custom object assigning points to the move to and from the stage.)  Lines 15 through 30 are not covered by the test class listed at the bottom.

 line 	 source
 1 	  trigger UpdateSalesScoreEvents on Opportunity (After update) {
 2 	  
 3 	   try {
 4 	  
 5 	   // List of variables to be used later.
 6 	   List<Sales_Score__c> ScoreEvents = new list<Sales_Score__c>();
 7 	   List<Opportunity> OldStage = New list<Opportunity>();
 8 	  
 9 	  
 10 	   // Add to the list all opps associated with an agreement in the trigger that has been signed
 11 	   for (Opportunity Opp: Trigger.New) {
 12 	   if ((Opp.Company_Division__c == 'Textura') && (Opp.StageName != trigger.oldMap.get(Opp.id).StageName) && (!ScoreEventHelper.hasAlreadyCreatedScores())){
 13 	  
 14 	   //
 15 	   Sales_Score__c OldEvent = new Sales_Score__c();
 16 	   OldEvent.Opportunity__c = opp.id;
 17 	   OldEvent.Direction__c = 'Leaving Stage';
 18 	   OldEvent.Movement_Date__c = system.Today();
 19 	   OldEvent.Stage__c = Trigger.oldMap.get(opp.ID).StageName;
 20 	   // Add to ScoreEvent list
 21 	   ScoreEvents.add(OldEvent);
 22 	  
 23 	   //
 24 	   Sales_Score__c Event = new Sales_Score__c();
 25 	   Event.Opportunity__c = opp.id;
 26 	   Event.Direction__c = 'Entering Stage';
 27 	   Event.Movement_Date__c = system.Today();
 28 	   Event.Stage__c = opp.StageName;
 29 	   // Add to ScoreEvent list
 30 	   ScoreEvents.add(Event);
 31 	  
 32 	  
 33 	   }
 34 	   ScoreEventHelper.setAlreadyCreatedScores();
 35 	   insert ScoreEvents;
 36 	   }
 37 	   } catch (Exception e) {Trigger.new[0].addError(e.getMessage());}
 38 	  }

 Class used to prevent recurrsion;

 1 	  public class ScoreEventHelper{
 2 	  
 3 	   // Static variables are local to the context of a Web request
 4 	  
 5 	   // (or testMethod during a runTests call)
 6 	  
 7 	   // Therefore, this variable will be initialized as false
 8 	  
 9 	   // at the beginning of each Web request which accesses it.
 10 	  
 11 	  
 12 	   private static boolean alreadyCreatedScores = false;
 13 	  
 14 	  
 15 	   public static boolean hasAlreadyCreatedScores() {
 16 	   return alreadyCreatedScores;
 17 	   }
 18 	  
 19 	   // By setting the variable to true, it maintains this
 20 	  
 21 	   // new value throughout the duration of the request
 22 	  
 23 	   // (or testMethod)
 24 	  
 25 	   public static void setAlreadyCreatedScores() {
 26 	   alreadyCreatedScores = true;
 27 	   }
 28 	  }

 This is the test method I created.  Something in it needs to be added to check more code from the trigger.

 1 	  public class ScoreEventTests {
 2 	   static testMethod void TestScoreEvents() {
 3 	   User user1 = new User();
 4 	   user1.FirstName = 'Steve';
 5 	   user1.LastName = 'Will';
 6 	   user1.UserName = 'stevew@submittalexchange.com';
 7 	   user1.Email = 'stevew@submittalexchange.com';
 8 	   user1.Alias = 'swill';
 9 	   user1.CommunityNickname = 'steve';
 10 	   user1.TimeZoneSidKey = 'America/Chicago';
 11 	   user1.LocaleSidKey = 'en_US';
 12 	   user1.LanguageLocaleKey = 'en_US';
 13 	   user1.EmailEncodingKey = 'UTF-8';
 14 	   user1.ProfileId = '00e70000000swZU';
 15 	   insert user1;
 16 	  
 17 	   Account account = new Account();
 18 	   account.Name = 'Test GradeBeam Account';
 19 	   account.Type = 'Architect';
 20 	   account.AD_Rep__c = user1.Id;
 21 	   account.NCA_Rep__c = user1.Id;
 22 	   account.Account_Source__c = 'BSD';
 23 	   insert account;
 24 	  
 25 	   Opportunity opp1 = new Opportunity();
 26 	   opp1.Name = 'Test Opp';
 27 	   opp1.AccountId = account.id;
 28 	   opp1.CloseDate = System.today();
 29 	   opp1.StageName = 'Qualified';
 30 	   opp1.Amount = 100;
 31 	   opp1.OwnerId = user1.Id;
 32 	   opp1.Company_Division__c = 'Textura';
 33 	   insert opp1;
 34 	  
 35 	  
 36 	   opp1.StageName = 'Sales Process';
 37 	   update Opp1;
 38 	  
 39 	   opp1.StageName = 'Written Agreement';
 40 	   update Opp1;
 41 	  
 42 	   opp1.StageName = 'Negotiation';
 43 	   update Opp1;
 44 	   }
 45 	  }

 

I need help updating a field in the Parent Object after the Child Object is created.

 

In this case, the field: Contract.Contract_Header__c needs to be updated with Contract_Header__c.Id after creation of this child object from THIS trigger below.

 

I have no idea how to go about this...  a couple of questions:

  • Is this possible within this trigger or do I have to write a new trigger on the Contract_Header__c Object?
  • Any help in getting started would be greatly appreciated!

 

Thanks,

Chris

 

Here is the code that I wrote that creates the child object (Contract_Header__c) from the parent object (Contract):

 

 

 

trigger Contract on Contract (after update) 
{
    List <Contract_Header__c> contractHeaders = new List <Contract_Header__c> ();
    Map <Id, Contract> oldmap = new Map <Id, Contract>();
    Map <Id, Contract> newmap = new Map <Id, Contract>();

 //System.debug('Chris in trigger');//

    for(Contract c: Trigger.new) 
    {
    //System.debug('Chris in contract loop');//
     if ((Trigger.oldMap.get(c.Id).Status != Trigger.newMap.get(c.Id).Status) && Trigger.newMap.get(c.Id).Status == 'Activated')
        { 
        //System.debug('Chris in status changed');//
        Contract_Header__c contractHeader = new Contract_Header__c ();
        contractHeader.Contract__c = c.Id;

        //System.debug('Chris creating new contract header and adding to list');//
        contractHeaders.add(contractHeader);
        }
    }

    if(contractHeaders.size()>0)
    {
    //System.debug('Chris has values to insert = '+ ContractHeaderInsert.size());//
     try{
        insert contractHeaders;
        }catch (System.Dmlexception e)  
             {
             system.debug (e); 
             }
    }

}

  • February 20, 2013
  • Like
  • 0

So, I have an object called Interaction.  When the picklist value "Speaker" is stored in the Interaction object's Selected_Sub_type__c field, I want it to update Contact and Account object checkboxes.  It works correctly for the Contact object.  I want to enhance the following code so that it will also update the Account object record Guest_Speaker_s__c checkbox to TRUE.

 

The Interaction object is related to the Account and Contact object by these fields:

Field Label     API Name          Data Type

Account         Account__c        Master-Detail(Account)

Contact         Contact__c         Lookup(Contact)

 

 

This code works to update the Contact object checkbox:

======================================================================================

// Update Contact field: "Guest_Speaker__c" to TRUE when a new Interaction__c record is inserted or updated.

// This code will not set the checkbox to false if the Sub_type value is not 'Speaker'

 

trigger UpdateGuestSpeakerCheckbox on Interaction__c (after insert, after update) {

 

// Will store Contact record ID

map< id, contact > contacts = new map< id, contact >();

 

// Create trigger for new or selected Interaction__c record

for(Interaction__c record:trigger.new)       

 

if(record.Selected_Sub_type__c == 'Speaker')

 

     // Update checkbox field on the Contact record to TRUE

     contacts.put(record.contact__c, new contact(id=record.contact__c, Guest_Speaker__C = TRUE));     

 

update contacts.values(); 

 

}

======================================================================================

 

 

This was my attempt to make the checkbox on the Account record update with the same trigger:

The Contact record updated fine.  The Account record was not updated.

Can you help me dial this in?

Thanks!

 

Kevin

 

My attempt, it compiles but it does not update Account object.

=======================================================================================

// Update Contact field: "Guest_Speaker__c" to TRUE when a new Interaction__c record is inserted or updated.

// This code will not set the checkbox to false if the Sub_type value is not 'Speaker'

 

trigger UpdateGuestSpeakerCheckbox on Interaction__c (after insert, after update) {

 

// Will store Contact record ID

map< id, contact > contacts = new map< id, contact >();

 

// Create trigger for new or selected Interaction__c record

for(Interaction__c record:trigger.new)       

 

if(record.Selected_Sub_type__c == 'Speaker')

 

     // Update checkbox field on the Contact record to TRUE

     contacts.put(record.contact__c, new contact(id=record.contact__c, Guest_Speaker__C = TRUE));     

 

update contacts.values(); 

 

 

// The new section added to update the Account object, just doesn't work!

 

// Store Account record ID  

map< id, account > account = new map< id, account >();

 

     for(Interaction__c record:trigger.new)       

          if(record.Selected_Sub_type__c == 'Speaker')

 

     // Update checkbox field on the Account record to TRUE     

     Account.put(record.account__c, new account(id=record.account__c, Guest_Speaker_s__c = TRUE));

 

}

=======================================================================================

I have 2 step Approval process I have submitted to Approval 

Now Once It has been approved by first approval now it is ready for secon approval. 

Here I want to know that after getting first approval will there Recall Button in process or not ?

I am unable to check it due to some reasons. 

I want to clone a record in same object uisng textfield......

For example:

 

if i have a Quantity__c field in object and fill the field with some numbers like 1,2,3 ....,and i press the save button, automatically it creates 3records or 2records in samke object as per the basis of quantity field uisng triggers(After insert).......

 

 

 

thanks

=========

Venkat Sforce

What is the best approach for a trigger to only fire once, after my IF condition has been met? The code below operates as it should once the IF condition is met - case is created.
 
However, the account could remain in the IF condition state for a couple of days. In the mean time, a simple update to the account could occur (e.g. phone number update) which would fire the trigger (again) thus a second (duplicate) case is created - not so good.
 
Where does my code need to be modified to prevent this behavior? I only need to have the trigger fire once when the original IF statement criteria is met. Of course, if the account falls out of the IF statment condition and then back in, the trigger would fire again - that's expected behavior.

 

Thanks.

 

 

trigger CreateVenereRequestIdCase on Account (before update) {

Case[] newCase = new Case[0];
for (Account a : Trigger.new) {
Account beforeUpdate = System.Trigger.oldMap.get(a.Id);
if((a.RecordTypeId == '012700000009Tor' || a.RecordTypeId == '012700000009JNI')
&& a.Venere_Module_ID__c == null && a.Venere_ID__c == null && a.Request_Venere_ID__c == TRUE && beforeUpdate.Request_Venere_ID__c == FALSE)
system.debug('Here is the account id: ' + a.Id);
newCase.add(new Case(
accountID = a.id,
Origin = 'Market Manager',
Priority = 'Medium',
RecordTypeID = '012T00000000Obu', //HDM - Venere Request ID
Status = 'New',
Subject = 'Venere ID Request',
Description = 'Please create a new Venere ID for ' + a.Name)
);

}
insert newCase;

}

 


 

 

 

 

 

I recently had issues with using Knockouts HTML comment tagging system with Visualforce. After searching around I found a good workaround which I detail in my blog post.

 

I thought I would share this workaround with everyone so you don't bang your head on your desk for hours trying to get Knockout to work.

 

Let me know what you think!

I'm receiving an odd error when submitting a record for approval. The record is a custom object and the approval process is entered when two custom checkboxes are marked as true.

 

Here is the error:

Error: Invalid Data. 
Review all error messages below to correct your data.
Related To: id value of incorrect type: a0DK0000002uyZK

 I'm really not sure what could be causing this as the Id mentioned in the error is a valid Id and all lookup relationship fields have been properly set.

 

Any ideas?

I'm working on a trigger for the Opportunity object that creates a few child "Commission" records when an opportunity is marked as  "Closed Won". The issue comes from my unit test that reopens and record that was marked as "Closed Won". 

 

Here is the error:

System.DmlException: Update failed. First exception on row 0 with id 006Q0000009MdFOIA0; first error: REQUIRED_FIELD_MISSING, Required fields are missing: [CloseDate]: [CloseDate]

The error occurs on the last update to the opportunity StageName that essentially reopens the deal.  I'm really banging my head against the wall on this one since it's pretty clear I'm setting the CloseDate when I insert the record.

 

//...insert other required records for test

 //create opportunity
Opportunity opportunity = new Opportunity();
opportunity.AccountId = account.Id;
opportunity.OwnerId = ramUser.Id;
opportunity.Name = 'Test Opportunity';
opportunity.StageName = 'First Appointment';
opportunity.RecordTypeId = [SELECT Id FROM RecordType WHERE SObjectType='Opportunity' AND Name='RAM Opportunity'].Id;
opportunity.TotalCash__c = 3000.00; //creates positive revenue so commissions can be calculated
opportunity.CloseDate = system.today();
insert opportunity;

//update opportunity to closed won
opportunity.StageName = 'Closed Won';
update opportunity;

Test.startTest();

//update opportunity again to 'In Processing' - reopen the deal
opportunity.StageName = 'In Processing';
update opportunity;

//...assertions

Test.stopTest();

 Any ideas as to why this may be happening?

***Let me start off by saying Enforce Validation and Triggers from Lead Convert setting is already set for our organization.

 

Moving forward...

 

I have a trigger that is supposed to set 3 custom lookup fields on an Opportunity when an opportunity is created. The value of these fields is based on the owner of the opportunity record.

 

The trigger functions properly in all use cases except when a lead is converted. For some reason the OwnerId of the Opportunity is the running user when the trigger executes instead of the Id set in the LeadConvert obj. This really perplexes me as I specifically set the OwnerId via the setOwnerId() method in my unitTest before calling the convertLead method.

 

Could anyone shed some light on to why the ownerId's are not being properly set?

 

 

trigger SetOpportunityOwnerManager on Opportunity (before insert, before update) 
{
//Create unique set of ownerId's
Set<ID> ownerIds = new Set<ID>();
for(Opportunity o : Trigger.new)
{
system.debug('OWNERID: ' + o.OwnerId);
ownerIds.add(o.OwnerId);
}

//Business logic to run ONLY on Insert
if(Trigger.isInsert)
{
//Create map of OwnerId's to their corresponding manager's
Map<ID, User> userMap = new Map<ID, User>([SELECT Id, Name, ManagerId, Processor__c, InterchangeDirector__c FROM User WHERE Id IN :ownerIds]);

//Set the manager field on the list of opportunities
for(Opportunity o : Trigger.new)
{
system.debug('***updating ' + o.Name);
o.OwnerManager__c = userMap.get(o.OwnerId).ManagerId;
o.Processor__c = userMap.get(o.OwnerId).Processor__c;
o.InterchangeDirector__c = userMap.get(o.OwnerId).InterchangeDirector__c;
}
}
}

 

Here is my unit test:

 

//create lead
Lead l = new Lead();
l.OwnerId = RAM.Id;
l.Status = 'Fresh';
l.Company = 'Test Co.';
l.FirstName = 'Jonny';
l.LastName = 'Quest';
l.Phone = '(480) 123-4567';
insert l;

//start testing
Test.startTest();

//verify lead owner information
Lead lTest = [SELECT Id, OwnerId FROM Lead WHERE Id=:l.Id];
system.assertEquals(RAM.Id, lTest.OwnerId); //PASSED

//convert lead
Database.Leadconvert lc = new database.Leadconvert();
lc.setLeadId(l.Id);
lc.setOwnerId(RAM.Id);
lc.setConvertedStatus('QC Verified');

Database.Leadconvertresult lcr = database.convertLead(lc);

//verify lead successfully converted
system.assert(lcr.isSuccess()); //PASSED

//verify manager, icd, & processor fields were populated on the created opportunity
Opportunity o = [SELECT Id, OwnerId, OwnerManager__c, InterchangeDirector__c, Processor__c FROM Opportunity WHERE Id=:lcr.getOpportunityId()];
system.assertEquals(RAM.Id, o.OwnerId); //PASSED
system.assertEquals(ISM.Id, o.OwnerManager__c); //FAILED
system.assertEquals(icd.Id, o.InterchangeDirector__c);
system.assertEquals(Processor.Id, o.Processor__c);

//end testing
Test.stopTest();

 

 

Thanks in advance!

Any idea what would cause report and dashboard graphs to display relationship fields in this way:

On our opportunity object, we have a custom user relationship field called "Processor". The processor for each opportunity is dynamically set based on the opportunity owner, when the opportunity record is initially created. I have created a custom trigger to then add the chosen processor to the parent Account Team with full editing privileges, and remove any other processors from the Account Team that may already exists.

 

Here is the trigger code:

 

/**
* Title: AddProcessorToAccountTeam
* Author: Jonathan Broquist
* Date: April 28, 2010
*
* Description:
* Everytime the processor relationship field is changed on an Opportunity,
* add the new user to the Account Team of the parent Account.
*/
trigger AddProcessorToAccountTeam on Opportunity (after insert, after update)
{
//list to hold new account team members
List<AccountTeamMember> acctMembers = new List<AccountTeamMember>();

//list to hold new account sharing rules
List<AccountShare> acctSharingRules = new List<AccountShare>();

//misc
Set<String> rmMemberAccts = new Set<String>();
Map<ID, ID> acctToProcessorMap = new Map<ID, ID>();

//iterate through records to find update processor values
for(Opportunity o : Trigger.new)
{
//new opportunity
if(Trigger.isInsert && o.Processor__c != null)
{
AccountTeamMember processor = new AccountTeamMember();
processor.AccountId = o.AccountId;
processor.TeamMemberRole = 'Processor';
processor.UserId = o.Processor__c;
acctMembers.add(processor);

AccountShare processorSharingRule = new AccountShare();
processorSharingRule.AccountId = o.AccountId;
processorSharingRule.OpportunityAccessLevel = 'Edit';
processorSharingRule.CaseAccessLevel = 'Read';
processorSharingRule.AccountAccessLevel = 'Edit';
processorSharingRule.UserOrGroupId = o.Processor__c;
acctSharingRules.add(processorSharingRule);
}
//updated opportunity
else if(Trigger.isUpdate)
{
//old opportunity record
Opportunity oldOpp = Trigger.oldMap.get(o.Id);

//check to see if the processor value has changed and verifies the
//new value is not null
if(oldOpp.Processor__c != o.Processor__c && o.Processor__c != null)
{
//add old processor to remove list if one exists
if(oldOpp.Processor__c != null)
{
rmMemberAccts.add(oldOpp.AccountId);
acctToProcessorMap.put(oldOpp.AccountId, oldOpp.Processor__c);
}

//add new processor to account team and update sharing rules
AccountTeamMember processor = new AccountTeamMember();
processor.AccountId = o.AccountId;
processor.TeamMemberRole = 'Processor';
processor.UserId = o.Processor__c;
acctMembers.add(processor);

AccountShare processorSharingRule = new AccountShare();
processorSharingRule.AccountId = o.AccountId;
processorSharingRule.OpportunityAccessLevel = 'Edit';
processorSharingRule.CaseAccessLevel = 'Read';
processorSharingRule.AccountAccessLevel = 'Edit';
processorSharingRule.UserOrGroupId = o.Processor__c;
acctSharingRules.add(processorSharingRule);
}
else if(oldOpp.Processor__c != o.Processor__c && o.Processor__c == null)
{
rmMemberAccts.add(o.AccountId);
acctToProcessorMap.put(oldOpp.AccountId, oldOpp.Processor__c);
}
}

//DML OPERATIONS
//remove team members from account team if any exist
if(rmMemberAccts.size() > 0)
{
List<AccountTeamMember> removeTeam = new List<AccountTeamMember>();
for(AccountTeamMember atm : [SELECT Id, UserId, AccountId FROM AccountTeamMember WHERE TeamMemberRole='Processor' AND AccountId IN :rmMemberAccts])
{
if(atm.UserId == acctToProcessorMap.get(atm.AccountId))
removeTeam.add(atm);
}

delete removeTeam;
}

system.debug('-->ACCOUNT MEMBERS: ' + acctMembers);
//insert the new account team members if any exist
if(acctMembers.size() > 0)
insert acctMembers; //LINE 100

//insert account sharing rules if any exist
if(acctSharingRules.size() > 0)
insert acctSharingRules;
}

}

 

Here is a snippet of the unit test that appears to causing the issues. Basically just batch creating opportunities...

 

 

//bulk insert opportunities
        Integer numOfOpps = 30;
        List<Opportunity> newOpps = new List<Opportunity>();
        for(Integer i=0; i<numOfOpps; i++)
        {
        	Opportunity o = new Opportunity();
	        o.Name = 'Test Opp';
	        o.AccountId = a.Id;
	        o.StageName = 'First Appointment';
	        o.Type = 'Outside Sales';
	        o.CloseDate = system.today() + 60;
	        newOpps.add(o);
        }
        
        Database.Saveresult[] oppResults = database.insert(newOpps);

 

Here is the relevant debug stack log:

 

19:47:21.392|USER_DEBUG|[97,4]|DEBUG|-->ACCOUNT MEMBERS: (AccountTeamMember:{AccountId=001R000000U0Iz0IAF, Id=01MR0000001JohsMAC, UserId=00540000000oDrMAAU, TeamMemberRole=Processor}, AccountTeamMember:{AccountId=001R000000U0Iz0IAF, UserId=00540000000oDrMAAU, TeamMemberRole=Processor})
19:47:21.392|METHOD_EXIT|[97,4]|debug(ANY)
19:47:21.392|METHOD_ENTRY|[99,7]|LIST:SOBJECT:AccountTeamMember.size()
19:47:21.392|METHOD_EXIT|[99,7]|size()
19:47:21.392|DML_BEGIN|[100,5]|Op:Insert|Type:AccountTeamMember|Rows:2
19:47:21.417|DML_END|[100,5]|
19:47:21.417|VF_PAGE_MESSAGE|cannot specify Id in an insert call
19:47:21.417|EXCEPTION_THROWN|[100,5]|System.DmlException: Insert failed. First exception on row 0 with id 01MR0000001JohsMAC; first error: INVALID_FIELD_FOR_INSERT_UPDATE, cannot specify Id in an insert call: [Id]
19:47:21.423|FATAL_ERROR|System.DmlException: Insert failed. First exception on row 0 with id 01MR0000001JohsMAC; first error: INVALID_FIELD_FOR_INSERT_UPDATE, cannot specify Id in an insert call: [Id]

Trigger.AddProcessorToAccountTeam: line 100, column 5

 

The bolded area is a debug output showing the values of the list of Account Team Memebers attempting to be inserted.

 

I cannot for the life of me figure out why an ID field is being passed to one of the AccountTeamMemeber records, and not the others.

 

Any thoughts or inisght would be greatly appreciated... I've been banging my head against this issue for quite some time.

 

 

Sincerely,

Jonathan

 

In the following case, the field CalendarAvailability__c is a picklist field and Closed, Tenative, & Open are the fields values. I'm trying to have an image displayed in a formula field based on the value of that field but am receiving the following error on save:

 

Error: Syntax error. Missing ')'

 

 But as far as I can tell my Case statement seems to be formatted properly ... what am I missing ...?

 

 

CASE
(
CalendarAvailability__c,
'Closed',
IMAGE('/img/samples/color_red.gif', 'Closed' [, 25, 100]),
'Tenative',
IMAGE('/img/samples/color_yellow.gif', 'Tenative' [, 25, 100]),
'Open',
IMAGE('/img/samples/color_green.gif', 'Open' [, 25, 100]),
' '
)

 

 

 

 

Message Edited by jbroquist on 03-30-2010 06:50 PM

I've been using the following trigger in production for about 5 months with no issues and all of a sudden today I'm getting the following errors:

 

Apex script unhandled trigger exception by user/organization: DeploymentOrderIsVerified: execution of AfterUpdate caused by: System.ListException: List index out of bounds: 0 Trigger.DeploymentOrderIsVerified: line 10, column 41

 The code block the error is referring too is as follows:

 

/**
* Fires when the Deployment Order IsVerfied flag is set to true.
* Child Lease Field Updates:
* -IsVerified__c = TRUE
* -NextStep__c = 'Awaiting Funding'
*/
trigger DeploymentOrderIsVerified on DeploymentOrder__c (after insert, after update)
{
DeploymentOrder__c olddo;
DeploymentOrder__c newdo = Trigger.new[0];

 

 How would I get a ListException error referencing the first item in Trigger.new on an after insert/after update trigger?

 

 

I am creating unit tests for a custom controller I created to handle file uploads and am having issues populating the Attachment body property in my test method. I really just don't know how I'm supposed to simulate a file upload during unit testing.

 

The body property is normally populated from the visualforce apex:inputFile tag, where I bind the inputFile to the attachment body property in my controller.

 

 

<apex:inputFile value="{!file.body}" />

 

 

I know that the Attachment body must be encoded in Base64, but how do I create a variable in my test class that I can use for filesize bounds testing as well? Can anyone provide some direction or even code samples on how I would go about doing this?

 

My test method is as follows:

 

static testMethod void basicControllerTest()
{
System.debug('Unit Test: AttachOppPaperwork Controller');

//Create Opportunity record
Opportunity o = new Opportunity();
o.name = 'Test Opp 1';
o.stageName = 'First Appointment';
o.closeDate = system.today()+60;
insert o;

//Set current page to AttachOppPaperwork
PageReference oPage = new PageReference('/apex/AttachOppPaperwork?id='+o.Id);
Test.setCurrentPage(oPage);

//Instantiate Controller
AttachOppPaperworkController c = new AttachOppPaperworkController();

//Verify variable values
System.assertEquals(o.name, c.oppName); //c.oppName == [Opportunity Name]
System.assertEquals(o.id, c.oppId); //c.oppId == [Opportunity Id]
System.assertNotEquals(null, c.file); //c.file instantiated

//Test File Upload
System.debug('-->AttachOppPaperworkController.upload() called');

//Set file body
//???

//upload the attachment
PageReference uploadTest = c.upload();

System.debug('::AttachOppPaperworkController.attachmentId = ' + c.attachmentId);
System.assertNotEquals(null, c.attachmentId); //attachmentId property should not be null
System.assertEquals(null, uploadTest); //method should return null, refreshing the page
System.assertEquals(true, c.complete); //complete flag should be set to true

//Verify Opportunity field update
Opportunity oTest = [SELECT PaperworkUploadedDate__c FROM Opportunity WHERE Id=:o.Id];

System.debug('::PaperworkUploadedDate__c = ' + oTest.PaperworkUploadedDate__c);
System.assertNotEquals(null, oTest.PaperworkUploadedDate__c); //date field should have a value
}

 

 

I'm currently trying to create a more comprehensive list view for certain users in our organization, so they can see relatedList information for multiple Opportunities at a glance. My code works, except for the fact that the relatedLists that are rendered are all the same. Meaning, that the rendered relatedLists for 2 different records show the same information. Has anyone else come across this issue before when using the repeat tag?

 

Here is my visualforce code:

 

<apex:page standardController="Opportunity" recordSetvar="opps"> <apex:pageMessages /> <apex:pageBlock title="Viewing Opportunities"> <apex:form id="theForm"> <apex:panelGrid columns="2"> <apex:outputLabel value="View:"/> <apex:selectList value="{!filterId}" size="1"> <apex:actionSupport event="onchange" rerender="list"/> <apex:selectOptions value="{!listViewOptions}"/> </apex:selectList> </apex:panelGrid> </apex:form> <apex:pageBlockSection id="list"> <table> <apex:repeat var="opp" value="{!opps}"> <tr> <td> {!opp.Name} - {!opp} </td> </tr> <tr> <td> <apex:relatedList subject="{!opp}" list="Leases__r"/> <apex:relatedList subject="{!opp}" list="MerchantApplications__r"/> </td> </tr> </apex:repeat> </table> </apex:pageBlockSection> </apex:pageBlock> </apex:page>

 

 

 

I recently just downloaded the latest Flex Toolkit SWC from the Salesforce Wiki, and when I replaced it in one of my projects I wasn't able to login anymore. After adding the following line everything started working again:

 

 

connection.serverUrl = "https://www.salesforce.com/services/Soap/u/15.0";

 

 So my question is, why am I able to login with the 15.0 API and not the 16.0? is it a bug? anyone else having these issues?

 

Let me know if you would like to see more of my code snippet ...

 

 

//Jonathan

 

I'm looking for a new way to calculate opportunity Amount field. My company doesn't just sell products. We also provide leases for those products and take payments on them. We calcualte out the lease through different fields and factors, then have workflows update the amount field with our leasing totals which works fine. The problem I'm running into is if we have an Opportunity where the client both purchases and leases different products. Our workflow doesn't update the amount field when products are associated with the opportunity.

 

I was looking for a way to override the amount field so our company could use the forecasting features of Salesforce. Is there any solutions to what I'm trying to do out there?

 

Any help would be great ... thanks!

Message Edited by jbroquist on 03-23-2009 09:24 AM
Message Edited by jbroquist on 03-23-2009 09:25 AM

I have a custom object called Merchant_Analysis__c which has a master-detail relationship with Opportunity. There is a field on the custom object called Opportunity__c which is just a reference to the parent Opportunity. I have a simple javascript button on the Opportunity called  New Merchant Analysis which simply passes the opportunity id to the visualforce controller via GET.

 

In my save method for the controller I set the Merchant_Analysis__c.Opportunity__c field to the ID of the Opportunity

 

public analysisController()

{

String oid = System.currentPageReference().getParameters().get('id');

 

if(oid != null && oid != '')

{

Opportunity o = [select id,name from Opportunity WHERE id=:oid];

this.oppID = o.id;

}

}

public PageReference save()

{

analysis.Opportunity__c = oppID;

analysis.recordtypeid = recType;

insert analysis;

 

PageReference analysisPage = new PageReference('/' + analysis.id);

analysisPage.setRedirect(true);

 

return analysisPage;

}

 

 The variable oppID is a public class level String variable that holds the Opportunity ID. For some reason when I run my test methods I get the following error:

 

System.SObjectException: Field is not writeable: Merchant_Analysis__c.Opportunity__c

 I've checked all the field level securities and everything to make sure Opportunity__c is not read only anywhere. For some reason I cannot figure out how to get past this error or even what is causing it.

 

Does anyone know how I can set the the relationship field of a Custom Object with a Master-Detail Relationship?

 

 

Any help would be great, as this problem has been plaguing me for too long now.

 

 

Thanks,

Jonathan 

 

 

 

Message Edited by jbroquist on 02-26-2009 11:52 AM
Message Edited by jbroquist on 02-26-2009 11:52 AM

I'm new to Apex/Visforce and I'm having trouble wrapping my brain around test methods and getting them to work. I currently have a method that is giving me the following error and I can't figure out why:

 

System.SObjectException: Field is not writeable: Merchant_Analysis__c.Opportunity__c

 It refers to the bolded line below:

 

public PageReference save()
{
analysis.Opportunity__c = oppID;
analysis.recordtypeid = recType;
insert analysis;

PageReference analysisPage = new PageReference('/' + analysis.id);
analysisPage.setRedirect(true);

return analysisPage;
}

static testMethod void testSave()
{
analysisController controller = new analysisController();
String recType = '012400000005QI0AAM';

Opportunity o = new Opportunity(name='test opp',stagename='test stage',closedate=System.today());
insert o;

Merchant_Analysis__c a = new Merchant_Analysis__c();
a.Opportunity__c = o.id;
a.recordtypeid=recType;
insert a;

PageReference testPage = new PageReference('/' + a.id);
testPage.setRedirect(true);

controller.oppID = o.id;
controller.recType = recType;

controller.analysis = a;


String ref0 = testPage.getUrl();
String ref1 = controller.save().getUrl();

System.assertEquals(ref0,ref1);
}

 

If someone could help troubleshoot this issue with me that would be awesome.

 

 

 

Thanks,

Jonathan

 

 

 

Message Edited by jbroquist on 02-18-2009 02:10 PM

I downloaded and installed the 1.50 CTI Demo Adapter from the following resource:

http://wiki.apexdevnet.com/index.php/CTI_Toolkit

 

During installation I also installed the Firefox add-on that it prompted to install.

 

Now when I open up Firefox and login to Salesforce the adapter will crash every single time. Is anyone else having these issues? I'm trying to move my entire company off of Internet Explorer to Firefox but this issue is the only thing holding us back. 

Hi All,

I have two object in the related list and if Approal Status on both the object changes to "Approved " then the Project_State__c field on the parent object changes to "Closed".

 

I have written the trigger but It's not working...please help me

 

trigger Update_Project_State on Project__c (before update) {

 

for(Project__c Prj:trigger.New){

 List<Quality_of_Delivery__c> Lstqod= new LIST<Quality_of_Delivery__c>();//object-1 MD relation

 List<Root_Cause__c> LstRC= new LIST<Root_Cause__c>();       //object-2 lookup    

 

Lstqod=[Select project__c,Final__c,Approved_Status__c from Quality_of_Delivery__c where project__c=: prj.Id];//Query qod      

 

LstRC=[Select Project_Name__c,Final__c,Approval_Status__c from Root_Cause__c where Project_Name__c=: j.Id];               

List<Project__c> prjupdate= new List<Project__c>();

            if(LstRC!=null){        for(Root_Cause__c r:LstRC){  

            if(r.Approval_Status__c=='Approved' && r.Final__C==True)  

             {                

              if(Lstqod!=null){     

                                  for(Quality_of_Delivery__c q:lstqod)  {    

                                            

                            if(q.Approved_Status__c=='Approved' && q.Final__c==True){

                                                             

                                   if(prj.Project_State__c=='Active'){                         

                                                     prj.Project_State__c='Closed';    

                                                     prjupdate.add(prj);      

                               }                                                                                                      

                           else if(prj.Project_State__c=='In Cancellation')

                                          {                                 

                                  prj.Project_State__c='Cancelled';                             

                                     prjupdate.add(prj);                              

   }                                                                                                                                                                       

   }

}                                                                     

update prjupdate;                                                                                                                                   

        }       

        }                                          

    }       

   }                                                               

}

}

HI 

I am  facing the above error when i am trying to follow the record after saving.

 

Please  clarify.

I am trying to fix my apex class testing code except I do not understand a way around what it is telling me to do. It tells me that in line 17, its expecting a right parenthesis, but only found a ;...however when I attempt to put a right parenthesis in it begins telling me all manor of things. It tells me that it does not expect token 'product' in the next line, that it is now expecting a close right curly bracket in line 17, etc. Please help!

 

This is my code, you will probably recognize it from the force.com workbook spring 13 release. I followed their instructions exactly:

 

@isTest

private

class TestHandleProductPriceChange {

 

  

statictestMethodvoid testPriceChange () {

  

Invoice_Statement__c Invoice = newInvoice_Statement__c(Status__c = 'Negotiating');

  

insert Invoice;

  

  

Merchandise__c[] products = new merchandise__c[]{

  

newMerchandise__c(Name = 'item 1', Description__c =

  

'test product 1', Price__c = 10,Total_Inventory__c = 10),

  

newMerchandise__c(Name = 'item 2', Description__c =

  

'test product 2', Price__c = 11,Total_Inventory__c = 10)

    };

    Insert products;

  

Line_Items__c[] LineItems = newLine_Items__c[] {

  

newLine_Items__c(Invoice_Statement__c = invoice.id,

  

Merchandise__c = products[0].price__c = 20; //raise price

    prodcts[1].price__c = 5;

//lower price

    Test.startTest();

  

update products;

    Test,stopTest();

  

    lineItems =

    [

SELECT id, unit_price__c FROM Line_items__c WHERE id IN :lineItems];

    System.assert(lineItems[0].unit_price__c ==10);

//unchanged

    System.assert(lineItems[1].unit_price__c == 5);

//changed!!

    };

  

insert lineItems;

  

    products[0].price__c = 20;

    Test.startTest();

  

update products;

    Test.stopTest ();

  

    lineItems = [

SELECT id, unit_Price__c FROMLine_Items__cWHERE id IN :lineItems];

  

  

system.assert(lineItems[0].unit_Price__c == 10);

    }

    }

 

 

 

any help would be much appreciated

I have a trigger that is working in the sandbox to insert the Forecast-quota records from my custom budget object.  When I attempted to run in production today, I am getting the above message.  I am running as admin in both environments.  The only difference is the volume of data I am loading.  Any suggestions?

 

 

  • March 05, 2013
  • Like
  • 0

I am currently creating opportunity teams in a trigger by inserting into OpportunityTeamMember and then OpportunityShare.  Everything is working on the surface...the team members are getting created.  But when I look into the logs, I am seeing errors when inserting into the team member table:

 

12:20:39.283 (283789000)|USER_DEBUG|[236]|DEBUG|.............The DB Insert failed for the following Opportunity Team Member: 00560000000zDeyAAE
12:20:39.286 (286362000)|USER_DEBUG|[237]|DEBUG|.............The DB returned the following error for the above record: Database.Error[getFields=(Opportunity);getMessage=Required fields are missing: [Opportunity];getStatusCode=REQUIRED_FIELD_MISSING;]

From the message,  I am not quite sure which required field is missing. I am inserting the Opportunity ID, the user ID, and the team role into the team member table.  then for each record that was inserted into the team member  table, I am inserting a corresponding opportunityshare record.  The only other field that looks like it may be required in the OpportunityTeamMember table is the OpportunityAccessLevel column, but that field is not writeable (I assume this column is being updated by a backend process once the opportunityshare record is created).

 

If there are suppose to be three users on the team, there will three sets of the above messages in the logs, yet all three members are showing on the opportunity as team members.  So it appears to be working.  Any ideas why I am seeing this in the logs?  Thanks

I need a fresh set of eyes on this trigger. Can some one take am moment  and perhaps point me in the right direction?

 

Trigger:

trigger Opportunity on Opportunity (before insert, before update) {
	System.debug('Alerting on Opportunity Trigger --------------------> Starting ');
	for(Opportunity o:trigger.new){

		Boolean boolStage;
		Boolean booRec;
		Boolean boolClose;

			if(trigger.isUpdate){
				Opportunity oldOpp = Trigger.oldMap.get(o.id);
				if(oldOpp.StageName != o.StageName){
					boolStage = true;
				}
				if(oldOpp.CloseDate != o.CloseDate){
					boolClose = true;
				}
			}
			
//			for(integer i=0;i<rec.size();i++){
				if(boolStage == true ){
			//StageName = 1-Qualification Complete/Research, 0-Prospecting	
				if(o.StageName == '0-Prospecting' || o.StageName == '1-Qualification Complete/Research'){
					o.Forecast_Identifier__c = 'Lead';
			//StageName = 2-Assessment, 3-Justification, 4-Internal Estimate
				}else if(o.StageName == '2-Assessment' || o.stageName == '3-Justification' || o.StageName == '4-Internal Estimate'){
					o.Forecast_Identifier__c = 'Open';
			//StageName = 5-Final Proposal
				}else if(o.StageName == '5-Final Proposal'){
					o.Forecast_Identifier__c = 'Upside';
			//StageName = 6-Vendor Selection, 7-Contract
				}else if(o.StageName == '6-Vendor Selection' || o.StageName == '7-Contract'){
					o.Forecast_Identifier__c = 'Committed';
			//StageName = 8-Closed
				}else if(o.StageName == '8-Closed'){
					o.Forecast_Identifier__c = 'Won';
		 		 }
				}else if(!trigger.isUpdate){
			//StageName = 1-Qualification Complete/Research, 0-Prospecting	
				if(o.StageName == '0-Prospecting' || o.StageName == '1-Qualification Complete/Research'){
					o.Forecast_Identifier__c = 'Lead';
			//StageName = 2-Assessment, 3-Justification, 4-Internal Estimate
				}else if(o.StageName == '2-Assessment' || o.stageName == '3-Justification' || o.StageName == '4-Internal Estimate'){
					o.Forecast_Identifier__c = 'Open';
			//StageName = 5-Final Proposal
				}else if(o.StageName == '5-Final Proposal'){
					o.Forecast_Identifier__c = 'Upside';
			//StageName = 6-Vendor Selection, 7-Contract
				}else if(o.StageName == '6-Vendor Selection' || o.StageName == '7-Contract'){
					o.Forecast_Identifier__c = 'Committed';
			//StageName = 8-Closed
				}else if(o.StageName == '8-Closed'){
					o.Forecast_Identifier__c = 'Won';
		 		 }
				}
				
				if(boolClose == true){
					o.Target_Complete_Date__c = o.closeDate+90;
					o.General_Availability_Date__c = o.closeDate+90;
				}
//			}
		

		} 

	}

 TestCase:

@isTest(seeAlldata=true)
private class TestOpportunityTrigger {

    static testMethod void myUnitTest() {
    	System.debug('Alerting on TestOpportunityTrigger --------------------> Starting');
    List<RecordType> rec = [Select id, name from RecordType where sobjecttype = 'Opportunity' and name = 'Business Development'];    

	Account acc = new Account();
	acc.Name = 'Test';
	acc.ShippingStreet = '123 Est Street';
	acc.ShippingCity = 'Home';
	acc.ShippingState = 'AL';
	acc.ShippingPostalCode = '36105';
	insert acc;
	System.debug('Alerting on --------------------> acc Details'+acc);
	
	List<String> stName = new List<String>{'0-Prospecting','1-Qualification Complete/Research','2-Assessment','3-Justifiction','4-Internal Estimate','5-Final Proposal','6-Vendor Selection','8-Closed'};
	for(integer p=0;p<200;p++){
		for(Integer i=0;i<stName.size();i++){
		Opportunity opp = new Opportunity();
		opp.RecordTypeId = rec[0].id;
		opp.StageName = stName[i];
		opp.AccountId = acc.id; 
		opp.Name = 'TestOpp';
		opp.Type = 'Availity Connect';
		opp.CloseDate = date.today();
		opp.Opportunity_States__c = 'AL';
		opp.Description = 'Testing';
		System.debug('Alerting on --------------------> opp Details'+opp);
		try{
			insert opp;
		}catch (Dmlexception e){
			System.debug('Insert Failed '+e);
		}

			opp.StageName = '0-Prospecting';
			opp.CloseDate = opp.CloseDate+4;
			try{
			update opp;	
			}catch (DmlException e) {
				System.debug('Update Failed '+e);
			}

		}
	}
	
	
    }
}

 

 

  • March 01, 2013
  • Like
  • 0

i am trying to access the Report objects in apex but getting limited fields my apex source code is

public Class MyController{
public List<Report> getReports(){

List<Report> rep1 = new List<Report>();
rep1=[Select Id,Developername,Description,Name,OwnerId from Report];


return rep1;

}

}

but i want to get the value of the sObject type to which it is related to for example 1.i click on new Report 2.then select Opportunities 3.then click create

how to get this opportunity object and how to get filters applied to reports please explain it.

I'm looking to have a trigger update a checkbox on a contact page whenever an idea is posted to the idea section.  I've written the trigger below but I'm missing something.

 

I think I've been able to query the ID of the user logged in (saved as uid).  I need a way to say update the field for the contact with the same ID (I'm assuming the contact ID will be the same as the user ID?)

 

This is my first attempt at Apex coding.

 

trigger UpdateContact on Idea (after insert, after update){

for (Idea newIdea : Trigger.new){

//Gets the user id who posted the idea
id uid = UserInfo.getUserId();

//Need code to set the PortalUse_IdeaRaised__c field to true (this is a checkbox)

//Something along the lines of Contact.PortalUse_IdeaRaised__c = true;
}

}

 

 

This doesn't work. Any ideas?

 

COb__c c = [select Parent__r.Name fro Cobj__c limit 1];


String parentName = c.get('Parent__r.Name');

 

 

Anyone else having trouble with IDE version 27 not building after save?

 

Tried everything setting I could find but the only way was to "Save to server' after every change.

 

Needless to say that got pretty tedious so I went back to version 26 and all is well. Was it just me?

I am trying to populate Contract_Header_LOOKUP__c (a lookup field) with the id from Contract_Header__c (a text field)... hence, the SOQL query.

 

It compiles, but when I try to get it to work, I am getting this error.

 

 

Error: Invalid Data. 
Review all error messages below to correct your data.
Apex trigger ContractLine_ContractHeaderLookupUpdate caused an unexpected exception, contact your administrator: ContractLine_ContractHeaderLookupUpdate: execution of BeforeUpdate caused by: System.QueryException: List has no rows for assignment to SObject: Trigger.ContractLine_ContractHeaderLookupUpdate: line 7, column 1

 

trigger ContractLine_ContractHeaderLookupUpdate on Contract_Line__c (before update, before insert){

    for (Contract_Line__c cl: Trigger.new)
    {
        if(cl.Contract_Header_LOOKUP__c == Null)
        {
            cl.Contract_Header_LOOKUP__c = [SELECT id FROM Contract_Line__c WHERE Name =: cl.Contract_Header__c].id ;
        }
    }
}

 

This helped me (http://boards.developerforce.com/t5/Apex-Code-Development/Can-t-get-this-trigger-to-work-any-ideas-Populate-Lookup-field/m-p/341141#M60433), but I am stuck at this point...

 

Any help is greatly appreciated!

  • February 27, 2013
  • Like
  • 0

I'm trying to do a trigger that doesn't let anyone close the case if I have tasks opened in the case.

 

If you try to close the case an error will appear.

 

Code:

 

trigger ChamadoAbertoTarefaAberta on Case (after update) {

    {
        List <Task> statuslist = [SELECT id, Status FROM Task WHERE WhatId IN :trigger.new AND Status statuslist.add(t.WhatId, true)];
        MAP<id,string> statuslist= new LIST<Id,String>(); 
   		for(Task t : trigger.new) 
        }
            
            for(Case c : trigger.new()){
            if(map.get(c.Id) == true){
            c.addError(My error here); 
            }
            else{
            break; 
}
            }
}

 I don't know where I'm going wrong.

 

Thanks for help !

Hi Everyone.

 

When a Sales user from my production is viewing their Events on the calendar, it only links to the Account... is there a way to just have it link to the opportunity?

 

Anil

  • February 27, 2013
  • Like
  • 0

Hi,

I have two object QOD__c--> child object, Approval_Status__c is a field on this object

Project__c--> Parent Object, Project_State__c is a field on this object.

 

I'm writting a trigger whenevr Approval_Status__c changes and equal to Approved then update the Project__State__c to "Closed"

 

below is the trigger but m getting error on it...

trigger Populate on Quality_of_Delivery__c (after update) {

List<Project__c> Lstprj=new List<Project__c>(); Set<Id> PrjId =new Set<Id>();

Lstprj=[Select Id from Project__c];

for(Project__c proj : lstprj){

PrjId.add(proj.Id);

}

    Map<Id,Project__c> prj = new Map<Id, Project__c>([select Project_State__c,Id from project__c where id in :prjid]);//Getting error here..DML requires SObject or SObject list type: MAP<Id,Project__c> at line 30 column 13 

 

      for(Quality_of_Delivery__c q: Trigger.new)  

{  

 

if(trigger.oldmap.get(q.Id).Approved_Status__c!=trigger.newmap.get(q.Id).Approved_Status__c)  

 

    {  

 

    if(  trigger.newmap.get(q.Id).Approved_Status__c=='Approved'){

                     prj.get(q.Project__c).Project_State__c='Closed';      

                          }      

      }         

    update prj;  

        

                      }

  }

 

please look into this

 Hai every one.....

 

           I am new to sfdc......  I had one visualforce page with the following:-

                                                           ______________

                                        Location  |______________|  

                                                             _____________ 

                               Expected sal      |______________|

 

                                                            ______________

                                      Skill set       |______________|

 

                                                            ______________

                                    Experience   |______________|

 

                                                                             __________
                                                                            |      SEARCH |   

 

                        I had one position object  (custom) . i would like to perform search on  Location(us,uk) and expected sal (less than 2L,3L or >=6L etc) and Skill set(java,.net... etc) Experience(<2yrs,or >3yrs etc....) .

If user enter  any values in visual force page and clicks search button then we need to display the records belonging to his criteria .

But  iam unable to perform search on all Fields ....

i created one query but it is quering only with one field ineed to have with all fields.... can any one help me.....

provide any code snippet...

public with sharing class ItemEditController {

    private ApexPages.StandardController controller {get; set;}
  public List<applicant__c> searchResults {get;set;}
   public List<position__c> searchResult {get;set;}
  public string searchText {get;set;}
   public string searchwith {get;set;}
 
  // standard controller - could also just use custom controller
  public ItemEditController(ApexPages.StandardController controller) { }
 
  // fired when the search button is clicked
  public PageReference search() {
 
String qry = 'select First_Name__C,Last_Name__c, mobile__c,Skill_set__c,Experience__C,Expected_Annual_Salary__C,current_salary__C from applicant__c ' +
      'where First_Name__C LIKE \'%'+searchText+'%\' ';
    searchResults = Database.query(qry);
   return null;
    return Page.SearchApplicants;
  }
 
  // fired when the save records button is clicked
  public PageReference save() {
 
    try {
      update searchResults;
    } Catch (DMLException e) {
      ApexPages.addMessages(e);
      return null;
    }
 
    return new PageReference('/'+ApexPages.currentPage().getParameters().get('id'));
  }
 
  // takes user back to main record
  public PageReference cancel() {
    return new PageReference('/'+ApexPages.currentPage().getParameters().get('id'));
  }

 

  i hwant to set default value below is code

but its give error,

"Compile Error: expecting right curly bracket, found '[' at line"

 

[DefaultValue('Not Available')]
     public String CompanyName{get; set;}

HI All,

 

I have declared a global variable in outer class and trying to access that varibale in inner class method it is showing error.

 

Can any one help me plz it very urgernt.

global class GlobalTest{   

    global String value='Situ';      

    public class Myclass{            

          public void  gtestMethod(){                  

               System.debug(value);     

          }

      }  

}

Error is like Variable does not exist: value at line 6 column 24

Thanks

Situ

i figured this should be pretty simple. I have a custom object called ONSITE_PRODUCT__c

onsite_product__c has a lookup field called product__c which has a lookup relationship to the salesforce products object. 

 

ive created a new picklist field called New_products__c which also has a list of the same products as the product__c lookup field. I want a user to select a product from the New_products__c picklist and have that same product value saved as the product lookup field value.

 

heres my trigger

 

trigger UpdateOnsiteProduct on Onsite_Product__c (before insert,before update) {
    { 
        for (Onsite_Product__c a : Trigger.new) 
        { 
            a.Product__c = a.New_Products__c;
        }
    }
}

 

 

and this is the error i keep receiving

 

Error: Invalid Data. 
Review all error messages below to correct your data.
Apex trigger UpdateOnsiteProduct caused an unexpected exception, contact your administrator: UpdateOnsiteProduct: data changed by trigger for field Product: id value of incorrect type: XYZ PRODUCT

 

Thanks.