• gtindu
  • NEWBIE
  • 250 Points
  • Member since 2009

  • Chatter
    Feed
  • 10
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 9
    Questions
  • 42
    Replies

I am in the process of developing a controller in which I have to use global variables. While doing so I am receiving the below error. 

 

                My code :             

 

 public class PurchasedProducts {
    List<Contact> c; 
   
      
   public List<Contact> getPurchasedProducts() {
       if(c == null) c = [select id, name from contact WHERE FirstName =:User.FirstName];
       return c;
   }
   }

 

                Error      :   Invalid bind expression type of Schema.SObjectField for column of type String

 

I am trying to get the Account details of a logged in portal user using an apex class.

 

I might be wrongly referring the global variable ..Any help on this one is highly appreciated.

 

Thank you,

Sampath

Hi,

 

i have a trigger on Campaign member object that would add tasks to them.

Now the task  subject should be assigned dynamically.

 

what i mean by dynamically means, subject of task should be in the following way:

Contact/Lead name, Account Name/Company, Quarter, Year

 

Assume a campaign member of type Contact is added. Contact name is Peter Ray and is associated with a Account salesforce.

 

Subject should be : Peter ray, Salesforce, Q2, 2010.

how to get quarter is , dividing a year into 4 quarters starting from january.

 

I have the trigger running fine, but with a test class i am unable to cover some lines. the lines are highlighted in Red below.

 

Code:

 

trigger add_task on CampaignMember (before Insert) 
{
    Campaign c = [select Id,Special_Campaign__c from Campaign where Id = :Trigger.new[0].CampaignId];
    Date Present_Day=Date.today();
    DateTime Present_Day_Time=System.Now();
    integer Year=Present_Day.Year();
    integer Month=Present_Day.Month();
    Public String getQuarter()
    {
        If(Month==1 || Month==2 || Month==3)
            return 'Q1';
        else if(Month==4 || Month==5 || Month==6)
            return 'Q2';
        else if (Month==7 || Month==8 || Month==9)
            return 'Q3';
        else
            return 'Q4';
    }
    If(c.Special_Campaign__c==True)
    {
    List<Id> Contact_Lead_Ids= new List<Id>();
    
    for(CampaignMember cm : Trigger.New)
    {
        Contact_Lead_Ids.add(cm.ContactId);
        Contact_Lead_Ids.add(cm.LeadId);
    }
    
    List<Contact> contacts=[Select Id,OwnerId,Account.Name,FirstName,LastName from Contact where Id in :Contact_Lead_Ids];
    Map<Id,Contact> Cid_to_Sobject= new Map<Id,Contact>();
    
    List<Lead> leads=[select Id,Name,OwnerId,Company from Lead where Id IN :Contact_Lead_Ids];
    Map<Id,Lead> Lid_to_Sobject=new Map<Id,Lead>();
    
    for(Contact ct : contacts)
        Cid_to_Sobject.Put(ct.Id,ct);
    
    for(Lead l : leads)
        Lid_to_Sobject.Put(l.Id,l);
    
    List<Task> insert_Tasks=new List<Task>();
    for(CampaignMember cm2 : Trigger.New)
    {
        if(cm2.ContactId!=NULL)
        {
            Contact ct2=Cid_to_Sobject.get(cm2.ContactId);
            Task myTask=new Task(Whoid=ct2.Id,
                                 Subject=ct2.Account.Name +','+' '+ ct2.FirstName +' '+ct2.LastName + ','+' '+'CCD'+','+' '+getQuarter()+','+Year,
                                 ActivityDate=Present_Day,
                                 Priority='Medium',
                                 Type='Make a Call',
                                 Status='Started',                                 
                                 OwnerId=ct2.OwnerId);
            insert_Tasks.add(myTask);
            System.Debug('Task inserted to=='+ct2.Id);
        }
        else
        {
            Lead l2=Lid_to_Sobject.get(cm2.LeadId);
            Task myTask=new Task(WhoId=l2.Id,
                                 Subject=l2.Company + ','+' '+l2.Name+','+'CCD'+','+getQuarter()+','+Year,
                                 ActivityDate=Present_Day,
                                 Priority='Medium',
                                 Type='Make a Call',
                                 Status='Started',                                 
                                 OwnerId=l2.OwnerId);
            insert_Tasks.add(myTask);
            System.Debug('Task Inserted to Lead=='+l2.Id);
        }
    }
    Insert insert_Tasks;
   
}
}

Test class:

Public Class trigger_Testcls
{
    Static testMethod Void test_CM_Contacts()
    {
        Campaign camp=new Campaign(Name='Test Campaign',Special_Campaign__c=True,IsActive=True);
        Insert camp;
        Account acct= New Account(Name='Testing Account');
        Insert acct;
        List<Contact> ct= new List<contact>();
      
        
        for(Integer i=0;i<200;i++)
        {
            Contact c=New Contact(FirstName='Test',LastName='Contact',AccountId=acct.Id);
            ct.add(c);
           
        }
        Insert ct;
        
        
        List<CampaignMember> cm=New List<CampaignMember>();
        
        for(Integer i=0;i<200;i++)
        {
            CampaignMember Cts=New CampaignMember(CampaignId=camp.Id, ContactId=ct[i].Id);
            cm.add(Cts);
           
            
        }
        
        
        Test.StartTest();
        Insert cm;
        Test.StopTest();
        
        List<Task> inserted_Tasks= [Select Subject,Status from Task where Whoid IN : ct];
        for(Task t : inserted_Tasks)
        {
            System.assertEquals('Started',t.Status);
        }
        
    }
    
    Static testMethod Void test_CM_leads()
    {
        Campaign Camp=new Campaign(Name='Lead Campaign',Special_Campaign__c=True,isActive=True);
        Insert Camp;
       
        List<Lead> l= New List<Lead>();
        for(Integer i=0;i<200;i++)
        {
            Lead ld=New Lead(LastName='Testing Lead',Company='Leads',ownerId='005A0000000h2hh');
            l.add(ld);
        }
        Insert l;
        
        List<CampaignMember> cm= New List<CampaignMember>();
        for(Integer i=0;i<200;i++)
        {
            CampaignMember c= New CampaignMember(CampaignId=camp.Id, LeadId=l[i].Id);
            cm.add(c);
        }
        Test.StartTest();
        Insert cm;
        Test.StopTest();
        List<Task> inserted_Tasks= [Select Subject,Status from Task where Whoid IN : l];
        for(Task t : inserted_Tasks)
        {
            System.assertEquals('Started',t.Status);
        }
    }
}

How do i get coverage for the function that calculates quarter information.Any help/idea is highly appreciated.

 

Thanks,

Sales4ce

Would appreciate any advice on how to best re-write this trigger so I don't hit the SOQL limits on bulk loading. It works well for creating individual records. Thanks! I apologize the browser/message board won't allow me to format my posting so I am pasting it in text... 12345678 trigger ContactDuplicateTriggerOfficePhone on Contact (before insert) {for (Contact c : Trigger.new){Contact[] contacts= [select id from Contact where NameOffice_Combo__c=:c.NameOffice_Combo__c and NameOffice_Combo__c != ''];if (contacts.size() > 0) {c.LastName.addError('Contact cannot be created. A contact already exists with the same name/office phone combination.');} }}
  • June 17, 2010
  • Like
  • 0

I'm hoping to deploy a trigger rather soon that will update a Custom Object Master/Detail relationship by putting the correct Account on the record.  It works on some inserts, and not on others.

 

Here's what should happen:  When the API sends over a collection of up to 200 Ordered Ad records, the trigger should fire (Before Insert) and associate the Ordered Ad with the proper Account.  If no account is in the system, it should assign it to the placeholder account, "Unknown Account".  For reasons I'm not clear about, it isn't associating some records with the right account.  I can manually create a record, and it *always* associates with the right account... On Batch insert, however, it's pretty hit and miss.

 

Would appreciate anyone taking a look at this and see if there's some obvious reason for this strange behaviour.

 

Thanks in advance.

 

 

trigger updateOrderedAdsAccount on Ordered_Ads__c (before insert) 
	
	{
        //Create record set of Account Numbers to tie to Contract Owners
        Set<String> acctnums = new Set<String>();
        MAP<String, Id> orderedAdsAcctRel = new Map<String, Id>();
        for(Ordered_Ads__c a:trigger.new)
        {
        	acctnums.add(a.Admarc_Number__c); 
        }
                
       //Iterate through Accounts and fine matches for ID based on Account Number
        for (Account u:[select id, AccountNumber from Account where AccountNumber != null AND AccountNumber in :acctnums limit 1])
        {
        	String acctnum = u.AccountNumber;
        	orderedAdsAcctRel.put(acctnum, u.id);
        }
           
        //Iterate through Accounts a and update according to user data from Map
        for (Ordered_Ads__c a:trigger.new)
        {
        	if (orderedAdsAcctRel.containsKey(a.Admarc_Number__c))
        	{
        		Id u1 = orderedAdsAcctRel.get(a.Admarc_Number__c);
        		a.Account__c = u1;
        	}
        	else
        	{
        		a.Account__c = '0014000000Efgve';
        	}
        }
    }

 

 

Hi Everyone,

 

Can one help me in using base64 encoding directly in our code. If possible can you please give a sample code.

 

Thanks,

sujith

Hi,

 

I have 3 fileds.start date(text),end date(text) and student status[picklist(values are trial,active,paid)].here my condition is if the end date is greater than 3days of start date and if the student status is "trial" then i want to delete those records.

 

In my code it is not checking the dates,it deletes entire trial records.Plz tell me modifications on my code.

Here is my code..

 

trigger expiry on chiranjeevi__Obj_D__c (before insert,before update)
 {
  List<chiranjeevi__Obj_D__c> objdlist=new List<chiranjeevi__Obj_D__c>();
  for(chiranjeevi__Obj_D__c a : Trigger.new)
  {
   objdlist=[SELECT chiranjeevi__startdate__c,chiranjeevi__enddate__c ,chiranjeevi__student_status__c from chiranjeevi__Obj_D__c WHERE chiranjeevi__student_status__c='trial']; 
    
    if(a.chiranjeevi__enddate__c > a.chiranjeevi__startdate__c.addDays(3) ) 
       {   
         delete objdlist;
       }  
   
 }
}

 

 

plz tell me how to check the date fileds.

 

Thanks in advance,

Manu..

  • June 17, 2010
  • Like
  • 0

I'm using a query insdie a for loop to return the most recent date for a set of records.  I'm hitting governor limits because the query is inside the for loop.  I can normally externalize a query outside of a for loop using a map, but in this particular scenario, I'm not sure how to accomplish it.

 

Here is the trigger:

 

trigger SalesInvoiceTotalsToOpportunity on Sales_Invoice__c (after insert, after update) {

	Set<Id> opIds = new Set<Id>();
	for (Sales_Invoice__c si : Trigger.new) {
		opIds.add(si.Opportunity__c);
	}
	
	List<Sales_Invoice__c> salesInvoiceList = [Select Opportunity__c, Date__c, Payment_Posting_Date__c, Subtotal__c, Subtotal_Paid__c From Sales_Invoice__c Where Opportunity__c in: opIds];
	
	Map<Id, List<Sales_Invoice__c>> oppyToSalesInvoiceMap = new Map<Id, List<Sales_Invoice__c>>();
	
	for (Sales_Invoice__c salesInvoice : salesInvoiceList) {
		
		List<Sales_Invoice__c> salesInvoices = oppyToSalesInvoiceMap.get(salesInvoice.Opportunity__c);
		if (salesInvoices == null) { 
			
			salesInvoices = new List<Sales_Invoice__c>();
			oppyToSalesInvoiceMap.put(salesInvoice.Opportunity__c, salesInvoices);
		}
		salesInvoices.add(salesInvoice);
	}
	
	List<Opportunity> opps = [Select Date_Paid__c, Date_Invoiced__c, Total_Invoiced_Amt__c, Total_Paid_Amt__c From Opportunity Where Id in: opIds];

	Map<Id, Opportunity> oppMap = new Map<Id, Opportunity>();
	
	for (Opportunity opp : opps) {
		oppMap.put(opp.Id, opp);
	}
	
	List<Opportunity> oppsToUpdate = new List<Opportunity>();
	
	for (Id oppyId : oppyToSalesInvoiceMap.keySet()) {
		Decimal invoicedAmt = 0;
		Decimal totalPaid = 0;
		List<Sales_Invoice__c> salesInvoices = oppyToSalesInvoiceMap.get(oppyId);
		Set<Id> setIds = new Set<Id>();
		for (Sales_Invoice__c salesInvoice : salesInvoices) {
			invoicedAmt =  invoicedAmt + salesInvoice.Subtotal__c;
			totalPaid = totalPaid + salesInvoice.Subtotal_Paid__c;
			setIds.add(salesInvoice.Id);
		}
		
		List<Sales_Invoice__c> pymtPostingDate = [Select Payment_Posting_Date__c From Sales_Invoice__c Where Id in: setIds AND Payment_Posting_Date__c <> null ORDER BY Payment_Posting_Date__c DESC LIMIT 1];
		List<Sales_Invoice__c> pymtDate = [Select Date__c From Sales_Invoice__c Where Id in: setIds AND Date__c <> null ORDER BY Date__c DESC LIMIT 1];
		
		Opportunity o = oppMap.get(oppyId);
		o.Total_Invoiced_Amt__c = invoicedAmt;
		o.Total_Paid_Amt__c = totalPaid;
		if (pymtPostingDate.size() > 0) {
			o.Date_Paid__c = pymtPostingDate[0].Payment_Posting_Date__c;
		}
		if (pymtDate.size() > 0) {
			o.Date_Invoiced__c = pymtDate[0].Date__c;
		}
		oppsToUpdate.add(o);
		
	}
	
	update oppsToUpdate;
	

}

 

Notice the two queries inside the for loop.  The query returns a list that contains the most recent date for the field specified.  I cannot figure out how to get the query outside of the for loop because I need to run the query inside the loop to get the list of Sales_Invoice__c for each opportunity.

 

Is there a way around this?  I was thinking I could use a map somehow, but I cannot figure out how to do it.

 

Thanks for any help.

Hey all,

 

I have a NullPointerException in my trigger. The purpose of the trigger is to use Snapshot to find its parent Opportunity's Owner Id, then apply this Id to Snapshot.

 

 

trigger Insert_RelatedOwnerID_as_SnapShotPipeForecast_by_Opp on SnapShot_Pipe_Forecast_by_Opp__c (before insert) {
		Map<Id, SnapShot_Pipe_Forecast_by_Opp__c> smap = new Map<Id, SnapShot_Pipe_Forecast_by_Opp__c>([select id, Opportunity_lookup__r.OwnerId from SnapShot_Pipe_Forecast_by_Opp__c where id in :Trigger.newMap.keySet()]);
         	
         	for(SnapShot_Pipe_Forecast_by_Opp__c s: Trigger.new){
              s.OwnerId = smap.get(s.Id).Opportunity_lookup__r.OwnerId;
			}
}

 

 

 

The exception is thrown on line 2, column 191. I'm sure it's an easy fix, but I can't see it.

 

Any help is appreciated.

  • June 16, 2010
  • Like
  • 0

Hi,

Can we use Base64 directly in our class for encoding a certification file. If possible can you please tell me how.

 

Thanks.

I'm creating an application which involves creating a Master Object (Quality Document) and than creating many child objects (SDQA) which are used as forms. I have over 100 custom 'generic' fields for the child object which I adapt to whichever type of form I need the child object to be. I need to be able to clone the master object along with all of its child objects. I've created a method in a controller which does this, and it will clone the master object, and create records for the child objects--but the problem is that the child objects are not completely cloned--only a few of the fields actually get copied over. 

 

My Controller:

public class qualityDocumentExtension { 

private Quality_Document__c QD;

ApexPages.StandardController cont;

 

//Constructor, links QD to current VF pages Quality Document record

  public qualityDocumentExtension (ApexPages.StandardController qdController) {

this.QD = (Quality_Document__c)qdController.getRecord();

cont = qdController;

}//end constructor 

 

public PageReference cloneDoc() {

Quality_Document__c newQD = QD.clone(false,true);

newQD.Name += ' (CLONE - RENAME)';

insert newQD;

 

//Iterate through attached SDQAs and create clones

List<SDQA__c> sdqas = QD.SDQAs__r;

for(SDQA__c S : sdqas) {

SDQA__c newS = S.clone(false,true);

newS.Quality_Document__c = newQD.Id;

insert newS;

}

//Navigate to view the cloned Document

PageReference theRef = new PageReference('/apex/QualityDocumentOverride?id=' + newQD.Id); theRef.setRedirect(true);

return theRef;

}//end cloneDoc method

 

 I simply call the cloneDoc() method from a commandbutton component on the Quality Document.

 

Please offer any solutions you may have =) 

 

Message Edited by dwwright on 03-29-2010 11:04 AM

When using InlineEditSupport with picklist fields - there is some odd behaviour occuring -

 

If the select dropdown happens to fall over another inlineEditSupport control [which almost always will be the case] - once you hover over an item in the dropdown that sits in front of another inlineEditControl - the select dropdown disappears.

 

In internet explorer (6-8 at least)

1. Have a pageBlock with 1 column and two fields that are dropdowns...

2. Initiate the inline edit and move the mouse over the select options down the page

3. When you end up at an option that sits in front of the second field - the select box disappears....

 

 

Ouch is this frustrating.

 

 

  • February 11, 2011
  • Like
  • 0

When creating the sortable list for jQuery - someone got a little too quote happy.  Below i highlighted the offending code.  in makeAllMapList - there is an open quotation mark in front of the id.  when it tries to build directions list for callout - $('#allDestinationList').sortable('toArray'); is returning an array with empty data in Chrome (rightly so - as sortable looks for options.attribute || id ... and the extra quotation mark is KILLING me.  Can someone from Force.com labs please update the page so that it will work in something besides internet explorer... or at the very least, release it as an UNMANAGED package so that this wouldn't be an issue... a perfect chance to promote GitHub!

 

    function makeAllMapList(){
        var pp;
        var t ='<ul id='allList' class="Connected" style="height:500px; ">';
        for(pp=0; pp<allMapItems.length; pp++){
            t+='<li class=\'item\' "id=\''+allMapItems[pp].id+'\'><img src=\''+allMapItems[pp].myIcon.image+'\' width=\'15\'/><img id=\'Event'+allMapItems[pp].id+'\' src=\'{!URLFOR($Resource.FN__Plus)}\' width=\'10\'/> '+allMapItems[pp].name+'</li>';
        }
        t+='</ul>';
  • January 18, 2011
  • Like
  • 0

When trying to utilize this on our Winter 11 sandbox - or in NA6 after update - 

Save error: Method does not exist or incorrect signature: System.isRunningTest()

 

Despite the API docs listing:

 

The following are the static methods for System.

isRunningTest BooleanReturns true if the currently executing code was called by code contained in a method defined as testMethod,false otherwise. Use this method if you need to run different code depending on whether it was being called from a test.

 

 

And the apex class metadata:

<?xml version="1.0" encoding="UTF-8"?>
    <apiVersion>20.0</apiVersion>
    <status>Active</status>
</ApexClass>

 

<?xml version="1.0" encoding="UTF-8"?><ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">

    <apiVersion>20.0</apiVersion>

    <status>Active</status>
</ApexClass>

  • October 04, 2010
  • Like
  • 0

I have an @future method that runs to reassign open approval requests based on Out of office rules.  If I don't have the method decorated @future - I have no issues everything works fine.  But if I decorate the method @future - i get a NullReference exception 

 

 

System.DmlException: Update failed. First exception on row 0 with id 04iXXXXXXXXXXXXXXX; first error: UNKNOWN_EXCEPTION, java.lang.NullPointerException: Argument Error: Parameter value is null: []

 

The only thing that changed is the @future decorator.  I would like to use this in Code Scheduler - but I also get the same error.  Anyone worked around this?

 

 

 

  • August 13, 2010
  • Like
  • 0

This just started happening in the last week (ironically since our instance was upgraded to Summer 10)

 

The following code (which worked before) is now failing miserably - and i cannot even catch the exception to degrade gracefully

 

		List<Period> fys = new List<Period>([Select p.Type, p.StartDate, p.Number, p.Id, p.EndDate From Period p where StartDate <= :date.today() and EndDate >= :date.today()]);
		for(Period f : fys)
		{
			if (f.Type == 'Year')
				this.fiscalYear = f.Number;
			else if (f.Type == 'Quarter')
				this.fiscalQuarter = f.Number;
			else if (f.Type == 'Month')
				this.fiscalMonth = f.Number;				
			else if (f.Type == 'Week')
				this.fiscalWeek = f.Number;

		}

Integer rowLimit = Limits.getLimitQueryRows() == 500 ? 10 : (Limits.getLimitQueryRows() - Limits.getQueryRows());

List<Opportunity> opportunities = new List<Opportunity>([SELECT id, name, account.name, owner.userrole.name FROM Opportunity Where Close_Fiscal_Month__c =: this.fiscalMonth AND Close_Fiscal_Year__c =: this.fiscalYear ORDER BY ForecastCategory LIMIT :rowLimit])

 The error occurs in instantiating the List from the SOQL query... which has always worked FLAWLESSLY for us before... 

 

I could understand the error with maybe some notification... or if there wasn't a way to work around it 

 

List<Opportunity> opportunities = new List<Opportunity>();

for (Opportunity o : [SELECT id, name, account.name, owner.userrole.name FROM Opportunity Where Close_Fiscal_Month__c =: this.fiscalMonth AND Close_Fiscal_Year__c =: this.fiscalYear ORDER BY ForecastCategory LIMIT :rowLimit])
  opportunities.add(o);

 

The workaround is PAAAAINFULLY slow - and has to have a far greater performance impact on the server than the original.  Is this a permanent change... if so - yikes.

 

 

We are running into issues with undeleting Opportunities with a master-detail relationship to a child object... and there can be many children records...

When actually undeleting (from apex or from recycling bin) - we'll ALWAYS get "Too Many SOQL Queries"... it orginates from our BeforeUpdate trigger on the child record.  It appears all of the children are being processed individually through the trigger instead of batched...

 

So even if we only had 1 SOQL query - 20 children records - and we're broken again... and it isn't calling the undelete trigger action on the child records - its calling Before/After Update... so theres no way to skip processing.

 

Am I missing something? Surely this isn't working as intended.

  • April 08, 2010
  • Like
  • 0

Is there any way to reassign an approval request with comments?  I have found that I can update the ActorId on the ProcessInstanceWorkitem object, however - I cannot update ProcessInstanceStep to include comments...

 

The Approval.ProcessWorkitemRequest class is useless for reassignment - you can only Approve, Reject, Recall.  I have found that if you set the Action to "Reassigned" it will not complain - but you will get the below error when calling it...

 

core.workflow.process.WorkitemAction cannot be cast to core.workflow.process.ReassignAction

  • March 23, 2010
  • Like
  • 0

User profile has Create and Customize Reports property active...

User has Read/Write to the report folder...

 

The user can create and edit... but not delete.

Any ideas?

  • February 09, 2010
  • Like
  • 0

<apex:pageBlock id="rerenderMe"> <apex:inputField value="{!Quote__c.Custom_Long_Text_Area__c}" /> <apex:actionRegion> <apex:inputField value="{!Account.Custom_Text_Field__c}" /> <apex:image title="Refresh" alt="Refresh" url="{!$Resource.iconref}" width="12" height="12" style="margin:0 1px;cursor:pointer;"> <apex:actionSupport action="{!doNothing}" event="onclick" reRender="rerenderMe" /> </apex:image> </apex:actionRegion> </apex:pageBlock> <apex:pageBlock> <apex:inputField value="{!Account.Custom_Multiselect_Picklist__c}"/> </apex:pageBlock>

 

In the above - if i monitor the POSTs with Fiddler and/or Firebug - i get the same thing every time.  The WHOLE form is submitted.  I have a large VF page, with many fields (including a few long text areas) that i'd love to use actionregions on to improve page performance (and server performance) - but they just submit the whole form.  And with the long text areas with a lot of content, it just takes forever to process.
  • January 21, 2010
  • Like
  • 0
<apex:image url="https://c.cs7.content.force.com/servlet/servlet.ImageServer?id={!TD_Logo}&oid={!$Organization.Id}"/>

I remove all hardcoding but this one is giving me problems.  Is there a command to pull the org instance?

Hi,

 

 How can we do something like Set History Tracking for OpportunityTeamMember? OWD setting for Opportunity in my org is Private. Please help.

 

Thanks and Regards.

Hi,

 

I've got a VisualForce PDF page that I'd like to add some sort of audit trail on when the page is generated.

 

I've got an object created to store the data, and the code to insert the data I want to capture into the object, but it turns out that I'm not able to run DML within (say) the constructor of the controller to log that is being used.  Has anyone done this sort of audit trail before? If so, how did you do it? 

 

Thanks,

Michael

Hello All,

 

I'm receiving a 'Duplicate id in list' error.  I am trying to total the number of projects associated to an opportunity.  The join between these two is a lookup field on projects.

 

I am receiving this error...

 

System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, trgOpp_FIProjectOnlyCount: execution of AfterInsert caused by: System.ListException: Duplicate id in list: 006S0000004dleLIAQ Trigger.trgOpp_FIProjectOnlyCount: line 21, column 5: []

 

Trigger

 

trigger trgOpp_FIProjectOnlyCount on SFDC_Project__c (after insert, after update) {
 //Find ID for 'File Integration Project - Document' and 'File Integration Project - Master' Record Type 
    Id RecType = [Select r.Id from RecordType r WHERE r.Name = 'File Integration Project - Document' AND r.SobjectType = 'SFDC_Project__c' Limit 1].Id;
	Id RecType2 = [Select r.Id from RecordType r WHERE r.Name = 'File Integration Project - Master' AND r.SobjectType = 'SFDC_Project__c' Limit 1].Id;
	
    List<Opportunity> opptys = new List<Opportunity>();
    integer pct;
    for(SFDC_Project__c p : trigger.new){
        if(p.RecordTypeId == RecType || p.RecordTypeId == RecType2){
            pct = [Select Count() FROM SFDC_Project__c p 
                                WHERE p.Opportunity__c = :p.Opportunity__c
                                AND p.Project_State__c != 'Completed'
                           ];

       Opportunity oid = [Select Count_of_FI_Projects__c from Opportunity WHERE id =:p.Opportunity__c ];
            oid.Count_of_FI_Projects__c = pct;
          
       opptys.add(oid);
       }
    }
    system.debug('\n' + opptys + '\n');
    Database.update(opptys);
}

 

 

UnitTest

 

@isTest
private class testOpp_FIProjectOnlyCount {

    static testMethod void myUnitTest() {
        // TO DO: implement unit test
 
        Id RecType = [Select r.Id from RecordType r WHERE r.Name = 'File Integration Project - Document' AND r.SobjectType = 'SFDC_Project__c' Limit 1].Id;
		Id RecType2 = [Select r.Id from RecordType r WHERE r.Name = 'File Integration Project - Master' AND r.SobjectType = 'SFDC_Project__c' Limit 1].Id;     	
		List<SFDC_Project__c> projList = new List<SFDC_Project__c>();
		
        Account a = new Account();
        	a.Name = 'Test Vendor Account';
        	a.Type = 'Vendor';
        	a.Industry = 'Unknown';
        	a.ERP_Acct_App__c = 'Unknown';
        	Database.insert(a);
        	System.debug(a.ID);
			Account acct = [Select ID From Account a Limit 1];  
        	ID aid = acct.Id;
        Account b = new Account();
        	b.Name = 'Test Retailer Account';
        	b.Type = 'Buyer';
        	b.Industry = 'Unknown';
        	b.ERP_Acct_App__c = 'Unknown';
			Database.insert(b);
			Account acct2 = [Select ID From Account b Limit 1];
        	ID bid = acct2.Id;
        Campaign c = new Campaign();
        	c.Name = 'Test Campaign';
        	c.IsActive = True;
        	Database.insert(c);
        	Campaign cam = [Select ID From Campaign c Limit 1];
        	ID cid = cam.ID;
        Contact con = new Contact();
        	con.LastName = 'Test Last Name';
        	con.AccountId = aid;
        	Database.insert(con);
        	Contact cont = [Select ID From Contact con Limit 1];
        	ID conid = cont.ID;
        Opportunity mo = new Opportunity();
        	mo.CampaignId = cid;
        	mo.Name = 'Test Master Opportunity';
        	mo.LeadSource = 'Other';
        	mo.StageName = 'Suspect - 0%';
        	mo.CloseDate = system.today();
        	mo.AccountId = aid;
        	Database.insert(mo);
        	Opportunity o = [Select ID From Opportunity mo Limit 1];
        	ID moid = o.ID;       	
        SFDC_Project__c mproj = new SFDC_Project__c();
        	mproj.Name = 'Test Master Project';
        	mproj.Project_Type__c = 'File Integration';
        	mproj.SFDC_Project_Status__c = 'Not Started';
        	mproj.RecordTypeId = RecType2;
        	mproj.Account__c = aid;
        	mproj.Related_to_Account_c__c = bid;
        	mproj.Contact__c = conid;
        	mproj.Opportunity__c = moid;
        	Database.insert(mproj);
        	SFDC_Project__c proj = [Select ID From SFDC_Project__c mproj Limit 1];
        	ID mprojid = proj.ID;  	

        for(Integer i=0; i<21; i++){
        	SFDC_Project__c p = new SFDC_Project__c();
        		p.Name = 'Test Doc Project ' + i;
        		p.Parent_Implementation_Project__c = mprojid;
        		p.Project_Type__c = 'File Integration';
        		p.SFDC_Project_Status__c = 'Not Started';
        		p.RecordTypeId = RecType;
        		p.Account__c = aid;
        		p.Related_to_Account_c__c = bid;
        		p.Contact__c = conid;
        		p.Opportunity__c = moid;
        		projList.add(p);
        }
        Database.insert(projList);
        System.assert(mo.Count_of_FI_Projects__c == 22); 
    }
}

 

 

Any suggestions?

 

Thanks,

 

Christian

 

 

  • February 24, 2011
  • Like
  • 0

I am in the process of developing a controller in which I have to use global variables. While doing so I am receiving the below error. 

 

                My code :             

 

 public class PurchasedProducts {
    List<Contact> c; 
   
      
   public List<Contact> getPurchasedProducts() {
       if(c == null) c = [select id, name from contact WHERE FirstName =:User.FirstName];
       return c;
   }
   }

 

                Error      :   Invalid bind expression type of Schema.SObjectField for column of type String

 

I am trying to get the Account details of a logged in portal user using an apex class.

 

I might be wrongly referring the global variable ..Any help on this one is highly appreciated.

 

Thank you,

Sampath

When using InlineEditSupport with picklist fields - there is some odd behaviour occuring -

 

If the select dropdown happens to fall over another inlineEditSupport control [which almost always will be the case] - once you hover over an item in the dropdown that sits in front of another inlineEditControl - the select dropdown disappears.

 

In internet explorer (6-8 at least)

1. Have a pageBlock with 1 column and two fields that are dropdowns...

2. Initiate the inline edit and move the mouse over the select options down the page

3. When you end up at an option that sits in front of the second field - the select box disappears....

 

 

Ouch is this frustrating.

 

 

  • February 11, 2011
  • Like
  • 0

Can any one tell me how can i implement a spell check functionality in salesforce.

I tried many things but nothing seems to be working inside salesforce..plz help...

When creating the sortable list for jQuery - someone got a little too quote happy.  Below i highlighted the offending code.  in makeAllMapList - there is an open quotation mark in front of the id.  when it tries to build directions list for callout - $('#allDestinationList').sortable('toArray'); is returning an array with empty data in Chrome (rightly so - as sortable looks for options.attribute || id ... and the extra quotation mark is KILLING me.  Can someone from Force.com labs please update the page so that it will work in something besides internet explorer... or at the very least, release it as an UNMANAGED package so that this wouldn't be an issue... a perfect chance to promote GitHub!

 

    function makeAllMapList(){
        var pp;
        var t ='<ul id='allList' class="Connected" style="height:500px; ">';
        for(pp=0; pp<allMapItems.length; pp++){
            t+='<li class=\'item\' "id=\''+allMapItems[pp].id+'\'><img src=\''+allMapItems[pp].myIcon.image+'\' width=\'15\'/><img id=\'Event'+allMapItems[pp].id+'\' src=\'{!URLFOR($Resource.FN__Plus)}\' width=\'10\'/> '+allMapItems[pp].name+'</li>';
        }
        t+='</ul>';
  • January 18, 2011
  • Like
  • 0

When trying to utilize this on our Winter 11 sandbox - or in NA6 after update - 

Save error: Method does not exist or incorrect signature: System.isRunningTest()

 

Despite the API docs listing:

 

The following are the static methods for System.

isRunningTest BooleanReturns true if the currently executing code was called by code contained in a method defined as testMethod,false otherwise. Use this method if you need to run different code depending on whether it was being called from a test.

 

 

And the apex class metadata:

<?xml version="1.0" encoding="UTF-8"?>
    <apiVersion>20.0</apiVersion>
    <status>Active</status>
</ApexClass>

 

<?xml version="1.0" encoding="UTF-8"?><ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">

    <apiVersion>20.0</apiVersion>

    <status>Active</status>
</ApexClass>

  • October 04, 2010
  • Like
  • 0

I have an @future method that runs to reassign open approval requests based on Out of office rules.  If I don't have the method decorated @future - I have no issues everything works fine.  But if I decorate the method @future - i get a NullReference exception 

 

 

System.DmlException: Update failed. First exception on row 0 with id 04iXXXXXXXXXXXXXXX; first error: UNKNOWN_EXCEPTION, java.lang.NullPointerException: Argument Error: Parameter value is null: []

 

The only thing that changed is the @future decorator.  I would like to use this in Code Scheduler - but I also get the same error.  Anyone worked around this?

 

 

 

  • August 13, 2010
  • Like
  • 0

Hi ,

I am trying to learn writing apex triggers. I tried to updte the annual revenue field with 100000, if the account name is abs., but i am unable to succeed in writing this code. Can anyone suggest me or correct me.

 

trigger test1 on Account (before insert, before update) {
list<account> a= new list<account>();
for(account acc: [select id, name from account limit 10])
{
if(acc.name=='abs')
 acc.annualrevenue='100000';
}
}

trigger test1 on Account (before insert, before update) {
list<account> a= new list<account>();
for(account acc: [select id, name from account limit 10]){if(acc.name=='abs') acc.annualrevenue='100000';
}}

I am looking for a way to run Apex code, or possibly a trigger, whenever an Account is viewed. The Apex code will be used to update a field at the account level, but I don't want to wait for the Account to be updated.

 

Is this possible?

Hi,

 

i have a trigger on Campaign member object that would add tasks to them.

Now the task  subject should be assigned dynamically.

 

what i mean by dynamically means, subject of task should be in the following way:

Contact/Lead name, Account Name/Company, Quarter, Year

 

Assume a campaign member of type Contact is added. Contact name is Peter Ray and is associated with a Account salesforce.

 

Subject should be : Peter ray, Salesforce, Q2, 2010.

how to get quarter is , dividing a year into 4 quarters starting from january.

 

I have the trigger running fine, but with a test class i am unable to cover some lines. the lines are highlighted in Red below.

 

Code:

 

trigger add_task on CampaignMember (before Insert) 
{
    Campaign c = [select Id,Special_Campaign__c from Campaign where Id = :Trigger.new[0].CampaignId];
    Date Present_Day=Date.today();
    DateTime Present_Day_Time=System.Now();
    integer Year=Present_Day.Year();
    integer Month=Present_Day.Month();
    Public String getQuarter()
    {
        If(Month==1 || Month==2 || Month==3)
            return 'Q1';
        else if(Month==4 || Month==5 || Month==6)
            return 'Q2';
        else if (Month==7 || Month==8 || Month==9)
            return 'Q3';
        else
            return 'Q4';
    }
    If(c.Special_Campaign__c==True)
    {
    List<Id> Contact_Lead_Ids= new List<Id>();
    
    for(CampaignMember cm : Trigger.New)
    {
        Contact_Lead_Ids.add(cm.ContactId);
        Contact_Lead_Ids.add(cm.LeadId);
    }
    
    List<Contact> contacts=[Select Id,OwnerId,Account.Name,FirstName,LastName from Contact where Id in :Contact_Lead_Ids];
    Map<Id,Contact> Cid_to_Sobject= new Map<Id,Contact>();
    
    List<Lead> leads=[select Id,Name,OwnerId,Company from Lead where Id IN :Contact_Lead_Ids];
    Map<Id,Lead> Lid_to_Sobject=new Map<Id,Lead>();
    
    for(Contact ct : contacts)
        Cid_to_Sobject.Put(ct.Id,ct);
    
    for(Lead l : leads)
        Lid_to_Sobject.Put(l.Id,l);
    
    List<Task> insert_Tasks=new List<Task>();
    for(CampaignMember cm2 : Trigger.New)
    {
        if(cm2.ContactId!=NULL)
        {
            Contact ct2=Cid_to_Sobject.get(cm2.ContactId);
            Task myTask=new Task(Whoid=ct2.Id,
                                 Subject=ct2.Account.Name +','+' '+ ct2.FirstName +' '+ct2.LastName + ','+' '+'CCD'+','+' '+getQuarter()+','+Year,
                                 ActivityDate=Present_Day,
                                 Priority='Medium',
                                 Type='Make a Call',
                                 Status='Started',                                 
                                 OwnerId=ct2.OwnerId);
            insert_Tasks.add(myTask);
            System.Debug('Task inserted to=='+ct2.Id);
        }
        else
        {
            Lead l2=Lid_to_Sobject.get(cm2.LeadId);
            Task myTask=new Task(WhoId=l2.Id,
                                 Subject=l2.Company + ','+' '+l2.Name+','+'CCD'+','+getQuarter()+','+Year,
                                 ActivityDate=Present_Day,
                                 Priority='Medium',
                                 Type='Make a Call',
                                 Status='Started',                                 
                                 OwnerId=l2.OwnerId);
            insert_Tasks.add(myTask);
            System.Debug('Task Inserted to Lead=='+l2.Id);
        }
    }
    Insert insert_Tasks;
   
}
}

Test class:

Public Class trigger_Testcls
{
    Static testMethod Void test_CM_Contacts()
    {
        Campaign camp=new Campaign(Name='Test Campaign',Special_Campaign__c=True,IsActive=True);
        Insert camp;
        Account acct= New Account(Name='Testing Account');
        Insert acct;
        List<Contact> ct= new List<contact>();
      
        
        for(Integer i=0;i<200;i++)
        {
            Contact c=New Contact(FirstName='Test',LastName='Contact',AccountId=acct.Id);
            ct.add(c);
           
        }
        Insert ct;
        
        
        List<CampaignMember> cm=New List<CampaignMember>();
        
        for(Integer i=0;i<200;i++)
        {
            CampaignMember Cts=New CampaignMember(CampaignId=camp.Id, ContactId=ct[i].Id);
            cm.add(Cts);
           
            
        }
        
        
        Test.StartTest();
        Insert cm;
        Test.StopTest();
        
        List<Task> inserted_Tasks= [Select Subject,Status from Task where Whoid IN : ct];
        for(Task t : inserted_Tasks)
        {
            System.assertEquals('Started',t.Status);
        }
        
    }
    
    Static testMethod Void test_CM_leads()
    {
        Campaign Camp=new Campaign(Name='Lead Campaign',Special_Campaign__c=True,isActive=True);
        Insert Camp;
       
        List<Lead> l= New List<Lead>();
        for(Integer i=0;i<200;i++)
        {
            Lead ld=New Lead(LastName='Testing Lead',Company='Leads',ownerId='005A0000000h2hh');
            l.add(ld);
        }
        Insert l;
        
        List<CampaignMember> cm= New List<CampaignMember>();
        for(Integer i=0;i<200;i++)
        {
            CampaignMember c= New CampaignMember(CampaignId=camp.Id, LeadId=l[i].Id);
            cm.add(c);
        }
        Test.StartTest();
        Insert cm;
        Test.StopTest();
        List<Task> inserted_Tasks= [Select Subject,Status from Task where Whoid IN : l];
        for(Task t : inserted_Tasks)
        {
            System.assertEquals('Started',t.Status);
        }
    }
}

How do i get coverage for the function that calculates quarter information.Any help/idea is highly appreciated.

 

Thanks,

Sales4ce

Would appreciate any advice on how to best re-write this trigger so I don't hit the SOQL limits on bulk loading. It works well for creating individual records. Thanks! I apologize the browser/message board won't allow me to format my posting so I am pasting it in text... 12345678 trigger ContactDuplicateTriggerOfficePhone on Contact (before insert) {for (Contact c : Trigger.new){Contact[] contacts= [select id from Contact where NameOffice_Combo__c=:c.NameOffice_Combo__c and NameOffice_Combo__c != ''];if (contacts.size() > 0) {c.LastName.addError('Contact cannot be created. A contact already exists with the same name/office phone combination.');} }}
  • June 17, 2010
  • Like
  • 0

Hi,

 

I have 3 fileds.start date(text),end date(text) and student status[picklist(values are trial,active,paid)].here my condition is if the end date is greater than 3days of start date and if the student status is "trial" then i want to delete those records.

 

In my code it is not checking the dates,it deletes entire trial records.Plz tell me modifications on my code.

Here is my code..

 

trigger expiry on chiranjeevi__Obj_D__c (before insert,before update)
 {
  List<chiranjeevi__Obj_D__c> objdlist=new List<chiranjeevi__Obj_D__c>();
  for(chiranjeevi__Obj_D__c a : Trigger.new)
  {
   objdlist=[SELECT chiranjeevi__startdate__c,chiranjeevi__enddate__c ,chiranjeevi__student_status__c from chiranjeevi__Obj_D__c WHERE chiranjeevi__student_status__c='trial']; 
    
    if(a.chiranjeevi__enddate__c > a.chiranjeevi__startdate__c.addDays(3) ) 
       {   
         delete objdlist;
       }  
   
 }
}

 

 

plz tell me how to check the date fileds.

 

Thanks in advance,

Manu..

  • June 17, 2010
  • Like
  • 0