• Eli Flores, SFDC Dev
  • NEWBIE
  • 289 Points
  • Member since 2011

  • Chatter
    Feed
  • 8
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 13
    Questions
  • 105
    Replies
HI, total noob here. 
I have a n object called Preference__c, has an account field, and has a contact field. What I am trying to do is simple, fill in the contact, the account is auto filled in. It works fine on the regular UI, but when doing the test method, thr trigger doesn't seem to be firing. Does it need a delay of some sort? 


The Trigger
=====================================================

trigger AutoPopulateCompany on Preference__c (before insert, before update)
{
    for(Preference__c pref: trigger.new){
        if(pref.Contact__c != null && pref.Account__c == null){
            //Instantiate the Preference class
            Preference.autoPopulateCompany(pref);
        }
    }   
}

Preference Class
=====================================================

public with sharing class Preference   
{
    //Used to populate the company of the account automatically if it is not filled in by the user
    public static void autoPopulateCompany(Preference__c preference)
    {
        set<Id> conIdSet = new set<Id>();
       
        conIdSet.add(preference.Contact__c);
       
        //Query for the account associated with the preference contact and place in a map
        map<id, contact> conMap = new map<id, contact>([SELECT id, accountid from contact where Id in: conIdSet]);
       
        //check if map is not empty (the contact's account is not null)
        if(!conMap.isEmpty())
        {
            preference.Account__c = conMap.get(preference.Contact__c).accountId;           
        }
    }
}

Test Class
=====================================================

@isTest
private class TestPreference
{
    private static testmethod void testAutoPopulateCompany()
    {
       //Test Data Prep
       //----------------------------------------------------
      
       //Create 2 test accounts
       Account acc1 = new Account();
       acc1.Name = 'Acc1-ACX';
       insert acc1;
      
       Account acc2 = new Account();
       acc2.Name = 'Acc2-ACX';
       insert acc2;
          
       //Create test contact with account 1
       Contact con1 = new Contact();
       con1.FirstName = 'con1';
       con1.LastName = 'ACX';
       con1.Account = acc1;
       insert con1;
      
       //Create test contact with account 2
       Contact con2 = new Contact();
       con2.FirstName = 'con2';
       con2.LastName = 'ACX';
       con2.Account = acc2;
       insert con2;
      
       //Create test contact with no account
       Contact con3 = new Contact();
       con3.FirstName = 'con3';
       con3.LastName = 'ACX';
       insert con3;
      
       //Test Create
       //----------------------------------------------------
      
       //Test Create with contact with account NOT filled in
       Preference__c pref = new Preference__c ();
       pref.Name = 'Test Pref 1';
       pref.Contact__c = con1.Id;
       insert pref;
      
       //Assert - Expected result: Preference Account filled in with Acc1
       pref = [SELECT Id, Account__c FROM Preference__c WHERE Id = :pref.Id];
       System.assertEquals(Acc1.Id, pref.Account__c);            
    }
}

The result
=================================================================

System.AssertException: Assertion Failed: Expected: 001F0000015bMbpIAE, Actual: null

The trigger should have populated pref.Account__c...but I get null. When I test on the actual UI, it works fine. 

Thanks in advance. 
Hey everyone,

I am trying to create a trigger to pull a Contacts Owner's Email and put it into an icontacts object. This is what I have but its erroring out on the second line (expecting a semi-colon, found 'OwnerIds').


trigger iContactEmailAlert on iContactforSF__iContact_Message_Statistic__c ( Before Insert, Before Update ) {

Set OwnerIds = New Set();

For ( iContactforSF__iContact_Message_Statistic__c a : Trigger.New)
{
//Adding the Owner's ids into a set
OwnerIds.Add ( a.Contact.OwnerID) ;
}

//Getting related contact owner's email address
Map conOwnerEmail = New Map( [Select Email From User Where ID IN:OwnerIds ] );

For ( iContactforSF__iContact_Message_Statistic__c a : Trigger.New)
{
//Populating the related contact's email address using Map functionality
a.ContactOwnerEmail__c = conOwnerEmail.get(a.Contact.OwnerID).Email ;
}
}   
   
I also need a test code after this. I still fairly new to coding.

Thanks for the help.
Dan
Hello everyone,
I am strugling with the following.  I want to populate a URL field that will include the Id of the inserted record through a Trigger.
It has to be an AFTER Insert trigger as it uses the Id of the inserted object.
I need this trigger to run in BULK (more tne 200 at a time), so I cannot use SOQL inside the trigger
How do you achieve this?
Thanks in advance for your herp.
Jerome
What determines how much data is shown after a Rest Request using HttpPost. My data being truncated. (, ...)

1
System.debug('Strg '+req.toString();
2
System.debug('my Rest Request '+req.params);

produces results as follows: see the ... in the examples below:

example one
reqRestRequest:[headers={Cache-Control=max-age=259200, CipherSuite=RC4-MD5 SSLv3 128-bits, Connection=keep-alive, Content-Type=application/x-www-form-urlencoded, Host=robson.secure.force.com, Referer=https://robson.secure.force.com/, User-Agent=ColdFusion, X-Salesforce-Forwarded-To=na1.salesforce.com, X-Salesforce-SIP=xx.xxx.xx.xxx}, httpMethod=POST, params={FormID=XXXXX, adid=texas, aid=1, areacode=xxx, campaign=777, email=myemail@gmail.com, next_url=http://www.robson.com/sem_v2/confirmation.cfm?wantDVD=0&dsd=15&display=&CFID=1234567&CFTOKEN=12345678, pginterest=on, postfix=1507, prefix=555, ...}, remoteAddress=xx.xxx.xx.xxxx, requestBody=Blob[0], requestURI=/sfwebtolead/Robson, resourcePath=/services/apexrest/*]


example two
FormID=FreeDVD, adid=internet, aid=, areacode=555, areasofinterest=, bst_tme=morning, campaign=485, control=0, ectrl=, email=name@emailaddress.com, ...


I believe the data/params in both cases is being truncated and appended with ...
I would like to return the full data so I can write it to a custom LOG file.
What determines how much data is show and where it stops and returns the ...

Thanks, Eric
I have a trigger in which I am assigning IDs to a list when the trigger is fired.  When I run a query against this list using WHERE ID IN:, the query does not return any duplicate values, which is causing a list index out of bounds error.

Here is my code for the assignment of the IDs to the initial list.

List<String> whatIDs = new List<String>();
   
    for (Task tk : Trigger.new){
       
        whatIDs.add(tk.whatID);
    }

And here is my code querying another object where the ID is found in that list.

List<Object1__c> oblist =  [SELECT ID, Name
                                                  FROM Object1__c
                                                  WHERE ID IN :whatIDs];

During testing, I had a list of 26 records in my initial list (whatIDs), but because my query is not returning duplicate values (there is one), I am only getting back 25 records.

Can anyone offer any suggestions/help?

Thanks.

-Paul
  • April 22, 2014
  • Like
  • 0
Hi, I'm struggling to find a way to replicate selecting a record in a visualforce page. Without somehow making the record in the test class selected nothing is being checked against the test code, Any help greatly appreciated! 
Extract from Test Class


// Set-up of Test Records here

// Set up visualforce parameters

PageReference pageRef = Page.CloneDeal;
PageRef.getParameters().put('id',Deal.id);

Test.setCurrentPage(pageRef);

// create an instance of the controller
Checkbox_class myPageCon = new Checkbox_class();



test.starttest();

mypageCon.getselected();
mypageCon.getselectedfee();
mypageCon.getselectedpay();
mypageCon.getselectediss();
mypageCon.getselectedtar();
mypageCon.getselectedaq();
myPageCon.getPayments();
myPageCon.getFees();
myPageCon.getPayments();
myPageCon.getIssuer();
myPageCon.getTargets();
myPageCon.getaq();
myPageCon.getex();
myPageCon.getDeals();



myPageCon.doClone();

test.stoptest();

e in the test class. 
Extract from Visualforce page

<apex:page controller="Checkbox_Class" Tabstyle="Deal_Protocol__c">
 <apex:stylesheet value="/sCSS/21.0/sprites/1297816277000/Theme3/def​ault/gc/versioning.css" /> 
  <apex:sectionHeader title="Clone Deal: "/>

  <apex:form id="theform" >
  <apex:PageBlock >
   <apex:PageBlockButtons >
   
      <apex:commandButton action="{!doClone}" value="Clone this Deal" /> 
      <apex:commandButton action="{!CloseFrm}" value="Cancel & Return" />
    </apex:PageBlockButtons>
 
            <apex:pageBlockSection Title="Transaction to be Cloned - Check box to select item(s) to clone">
                <apex:dataTable value="{!deals}" var="a" columnswidth="50px,50px" cellpadding="4" border="1">
                    <apex:column >
                        <apex:facet name="header"> <apex:inputCheckbox >
                            <apex:actionSupport event="onclick" action="{!GetSelected}" onsubmit="checkAll(this)" rerender="Selected_PBS"/>
                            </apex:inputCheckbox>
                        </apex:facet>
                        <apex:inputCheckbox value="{!a.selected}" id="checkedone">
                        <apex:actionSupport event="onclick" action="{!GetSelected}" rerender="Selected_PBS"/></apex:inputCheckbox>
                    </apex:column>
                    <apex:column headervalue="Deal Name" value="{!a.acc.Name}" />
                    <apex:column headervalue="Deal Type" value="{!a.acc.Agreement_Type__c}" />
                  
                </apex:dataTable>
            </apex:pageBlockSection>

<apex:pageBlockSection Title="List of Fees that can be cloned (does not include deleted fees)">
                <apex:dataTable value="{!fees}" var="f" columnswidth="50px,50px" cellpadding="4" border="1">
                    <apex:column >
                    
                        <apex:inputCheckbox value="{!f.selectedf}" id="checkedone">
                        <apex:actionSupport event="onclick" action="{!GetSelectedfee}" rerender="Selected_PBS"/></apex:inputCheckbox>
                    </apex:column>
                    <apex:column headervalue="Fee Name" value="{!f.fee.Name}" />
                    <apex:column headervalue="Playbook Category" value="{!f.fee.Playbook_Category__c}" />
                    <apex:column headervalue="Playbook Ref" value="{!f.fee.Playbook_Ref__c}" /> 
                                     
                </apex:dataTable>
            </apex:pageBlockSection>


Extract from Apex class

public class Checkbox_Class
{

    String DealID = ApexPages.currentPage().getParameters().get('id');

    List<DealWrapper> DealList = new List<DealWrapper>();
    List<FeeWrapper> FeeList = new List<FeeWrapper>();
    
     
    List<Deal_protocol__c> selectedDeal = new List<Deal_protocol__c>();
    List<Fees__c> selectedFee = new List<Fees__c>();
    
     
  
    public List<DealWrapper> getDeals()
    {
        for(Deal_protocol__c a : [select Id, Name,Agreement_Type__c from  Deal_protocol__c where id=:dealid limit 1])
        DealList.add(new DealWrapper(a));
        return DealList;
    }

  public List<FeeWrapper> getFees()
    {
        for(Fees__c f : [select Id, Name,Playbook_Category__c,Playbook_Ref__c from Fees__c where Deal_protocol_ref__c =:dealid and deleted__c=false order by playbook_category__c ASC])
        FeeList.add(new FeeWrapper(f));
        return FeeList;
    }

 public PageReference getSelected()
    {
        selectedDeal.clear();
        for(DealWrapper accwrapper : DealList)
        if(accwrapper.selected == true)
        selectedDeal.add(accwrapper.acc);
        return null;
    }
    
      public PageReference getSelectedFee()
    {
        selectedfee.clear();
        for(FeeWrapper fwrapper : FeeList)
        if(fwrapper.selectedf == true)
        selectedfee.add(fwrapper.fee);
        return null;
    }

    public class DealWrapper
    {
        public Deal_protocol__c acc{get; set;}
        public Boolean selected {get; set;}
        public DealWrapper(Deal_protocol__c a)
        {
            acc = a;
            selected = false;
        }
    }
    
     public class FeeWrapper
    {
        public Fees__c fee{get; set;}
        public Boolean selectedf {get; set;}
        public FeeWrapper(fees__c f)
        {
            fee = f;
            selectedf = false;
        }
     }


I am trying to build a List of records from a List of other objects. Afterwards I need to insert the new List created. However I get the error List Index out of bounds. Here follows the code:

             
List<Line__c> LMELI  = new List<Line__c>();

List<TX__c> Trx     = [SELECT  Id,  Amount__c
                                      FROM TX__c

integer i = 0;

for (TX__c PMT : Trx) {
            
            LMELI[i].MB__c                  = Ref__c;            //  I get the error  LIST INDEX out of bounds (0)      
            LMELI[i].Tx__c                     = PMT.Id;                                      
            LMELI[i++].Amount__c      = PMT.Amount__c;  
                        
    }  // for PMT ends here

   INSERT LMELI;
  • April 18, 2014
  • Like
  • 0
Public Class ContractFunctionsCloneContractAndOLIs
{

Public static void CloneMaintContractAndLineItems(Map<Id,Contract> oldMap, Map<Id,Contract> newMap)
      {
        List<Id> ContractToClone = new List<Id>();
        List<Id> ContractLineItemsToClone = new List<Id>();
       
        Date StartDate;
        Date EndDate;


       
      
        Integer NumberOfDays = 0;
        Integer NumberOfMonths = 0;
        Integer NumberOfYears = 0;
        Double YearTerm = 0;
        Integer NumberOfLeapYearDays = 0;
        Integer TermsByMonth = 0;
        Integer Prevcount =0;
       
        Boolean MaintTermMisMatch;
       
        String OriginalCase;
       
        Date CurrentDay;
        Date PrevCurrentDay;      

        Integer PrevNumberOfDays =0;
        Date PrevStartDate;
        Date PrevEndDate;
       
        Integer PrevNumberOfLeapYearDays =0;      
      
             
        for(Contract c : newMap.Values())
        {
            ContractToClone.add(c.Id);
      
        }

        
        for(Contract_Line_Item__c CLI :[Select id from Contract_Line_Item__c where Contract__c in :ContractToClone])
        {
            ContractLineItemsToClone.add(CLI.id);
        }
      
       Contract newContract = new Contract();
       
        if(ContractToClone.size() > 0 && ContractLineItemsToClone.size() > 0)
        {
            for(Contract c : [Select id, Status, Attn_To__c, Original_Case__c, Maintenance_out_of_sync__c, NewlyCreatedNumDays__c, DateFinal__c,PrevNumberOfDays__c, PrevStartDate__c, PrevEndDate__c, PrevNumberOfLeapYearDays__c, Term_In_Days__c, XNumberOfDays__c, AccountId, XNumberOfLeapYearDays__c, NumberOfLeapYearDays2__c, SpecialTerms, FEndDate__c, FCompareDayEndDate__c, Total_Maintenance_Price__c,Months_between_start_and_end__c,Override_Total_Price__c,StartDate, Contract_End_Date__c, Case__c, RecordTypeId from Contract where Id in :ContractToClone ])
            {

List<Contract> ContractsToInsert = new List<Contract>();
     

      
                newContract.Total_Maintenance_Price__c = c.Total_Maintenance_Price__c;
                newContract.Status = 'Pending';
                newContract.AccountId = c.AccountId;
                newContract.StartDate = c.Contract_End_Date__c + 1;
                newContract.RecordTypeId = ServiceClass.getRecordTypesNameMap('Contract').get('Maintenance Contract').Id;
                newContract.Parent_Contract__c = c.id;
               
                                            
                ContractsToInsert.add(newContract);
        insert(ContractsToInsert);  
       
         List<Contract_Line_Item__c> ContractLineItemsToInsert = new List<Contract_Line_Item__c>();
               
                String ContractId;
                String AccountId;
                String CaseId;
                String CLIStatus;
                           
            for(Contract insertedContracts : [Select Id, Case__c, AccountId from Contract where id in :ContractsToInsert])
            {
                ContractId = insertedContracts.id;
                AccountId = insertedContracts.AccountId;
                CaseId = insertedContracts.Case__c;
                CLIStatus = 'Pending';
               
               
               
                            }
            for(Contract_Line_Item__c cc : [Select id, Maintenance_Sales_Price__c, Contract_Line_Item_Status__c, Product_LU__c, Quantity__c, List_Price__c from Contract_Line_Item__c where Id in :ContractLineItemsToClone])
                {
                    Contract_Line_Item__c newCLI = new Contract_Line_Item__c();
                   
                   
                    newCLI.Contract_Line_Item_Status__c = CLIStatus;
                    newCLI.Contract__c = ContractId;
                    //newCLI.Case_Id__c = CaseId;
                    newCLI.Account__c = AccountId;
                    newCLI.Contract_Line_Item_Origin__c = 'Contract Clone Follow Up Contract';
                    newCLI.Product_LU__c = cc.Product_LU__c;
                    newCLI.Quantity__c = cc.Quantity__c;
                    newCLI.List_Price__c = cc.List_Price__c;    
                    newCLI.Maintenance_Sales_Price__c = cc.Maintenance_Sales_Price__c;
                    if(cc.Contract_Line_Item_Status__c == 'Do Not Renew')
                    {
                         newCLI.Contract_Line_Item_Status__c = 'Do Not Renew';
                    }        
                    if(cc.Contract_Line_Item_Status__c == 'Cancelled')
                    {
                         newCLI.Contract_Line_Item_Status__c = 'Cancelled';
                    }        
                    ContractLineItemsToInsert.add(newCLI);
                }
                insert(ContractLineItemsToInsert);
                update(ContractLineItemsToInsert);  
            }
       
       
          

      }}}

I have a requirement to add a blurb to the top of the Solutions tab... I'd like to not to rewrite the entire solution display system to accomodate the requirement... Any have some tips on how I can accomplish this?

I need to set my unit tests for specific ranges for closed cases but in my test method when i try to 

 

Case cs =new case();

...

cs.closedDate = datetime.now().addDays(-15);

 

It throws an error saying that closedate is not writeable. How can I set the closedate in my test classes?

Hi, I was attempting to demonstrate the case-insensitivity of 18 char ID to my peers and I can't seem to get it to work. 

 

I ran this soql query:

select id from account where ID = '0013000000Hk05sAAB'

 

 

which successfully reports 1 record. 

 

When I try the all lowercase version 

 

select id from account where id = '0013000000hk05saab'

 

 

It reports 0 records. 

 

Is this a bug? A limitation of SOQL? Did I misunderstand the case-insensitive nature of 18 char id? I'm confused why the 2nd one pulls up 0 records. 

Hi, I have this future method that errors out for having too many callouts frequently. I'd like to wrap my head around the batch apex concepts and add it to my toolbox so this project seems as good as any. Can someone help me with converting this methods to one that works by batches. Even just a high level walk through would be very helpful.

    @future (callout = true)
    public static void postToLCS(Map<Id, String> licenseXmlMap) {

        Boolean postToProd = false;
        String lcsEndpoint = '';
        String lcsUname = '';
        String lcsPwd = '';
        Map<String, Environment_Variables__c> envVarMap = Environment_Variables__c.getall();
        Map<Id, String> succLicRespMap = new Map<Id, String>();
        Map<Id, String> failLicRespMap = new Map<Id, String>();

        License__c[] licRecs = [SELECT Id, Last_Post_Date__c,
                                       Last_Post_Response__c
                                FROM   License__c
                                WHERE  Id IN: licenseXmlMap.keySet()];


        // LL - Get environment variables related to license posting
        if (envVarMap.get('use_prod_lcs').Value__c == 'true') { // LL - Check whether to post in DEV or PROD LCS
            // LL - Set PROD LCS endpoint and credentials
            lcsEndpoint = envVarMap.get('prod_lcs_endpoint').Value__c;
            lcsUname = envVarMap.get('prod_lcs_uname').Value__c;
            lcsPwd = envVarMap.get('prod_lcs_pwd').Value__c;
        } else {
            // LL - Set DEV LCS endpoint and credentials
            lcsEndpoint = envVarMap.get('dev_lcs_endpoint').Value__c;
            lcsUname = envVarMap.get('dev_lcs_uname').Value__c;
            lcsPwd = envVarMap.get('dev_lcs_pwd').Value__c;
        }
         
        Blob headerValue = Blob.valueOf(lcsUname + ':' + lcsPwd);
        String authorizationHeader = 'BASIC ' +
        EncodingUtil.base64Encode(headerValue);


        for (License__c l : licRecs) {

            if (!licenseXmlMap.get(l.Id).contains('Error') &&
                !licenseXmlMap.get(l.Id).contains('error')) {

                HttpRequest req = new HttpRequest();
                String lcsResp = '';
    
                req.setEndpoint(lcsEndpoint);
                req.setMethod('POST');
                req.setHeader('Authorization', authorizationHeader);
                req.setBody(licenseXmlMap.get(l.Id));
    
                Http http = new Http();
                HTTPResponse res;
    
                try {
    
                    if (!test.isRunningTest()) {
                        res = http.send(req);
                    }
                    
                    if (res != null) {
                        lcsResp = 'Status=' + res.getStatus() + ', StatusCode=' + res.getStatusCode();
                    }
    
                    // LL - Update LCS response fields if no exception encountered
                    l.Last_Post_Date__c = system.now();
                    l.Last_Post_Response__c = lcsResp;
    
                } catch (CalloutException ex) {

                    Util.sendErrEMail('Error encountered during license posting. Additional message: ' + ex.getMessage() + ' Generated xml: ' + licenseXmlMap.get(l.Id));
                    l.Last_Post_Date__c = system.now();
    
                    // LL - Inject the exception message in the Last Post Response field
                    l.Last_Post_Response__c = string.valueOf(ex);
                }
                    
            } else {

                Util.sendErrEMail('Error encountered in generating xml. License not posted to the LCS. Generated xml: ' + licenseXmlMap.get(l.Id));

                l.Last_Post_Date__c = null;
                l.Last_Post_Response__c = 'Error encountered in generating xml. License not posted to the LCS.';
            }

            // LL - TODO: Need to implement some logger mechanism...
        }

        // LL - Set static class to prevent recursive future calls
        ProcessorControl.inFutureContext = true;

        // Set database savepoint in event db transactions fail
        System.SavePoint sp = Database.setSavepoint();

        try {
            //update licRecs;
            
            Boolean hasError = false;
            Database.SaveResult[] updResult = database.update(licRecs, true);

            // LL - Check if error/s were encountered during the update
            for (Integer i=0; i < updResult.size(); i++) {
                if (!updResult[i].isSuccess()) {

                    // LL - Indicate that an error was encountered
                    hasError = true;

                    // LL - Exit the entire loop since an error was encountered
                    break;
                }
            }


            if (!hasError) {
                updateWowzaFromLicense();               
            }

        } catch (Exception e){
            // LL - Rollback transaction
            Database.rollback(sp);

            Util.sendErrEmail('Encountered an error updating license and/or wowza objects. Additional message ' + e.getMessage());
        }

    }

 

 

 

 I'm  having an issue with trying to hide column. I can't seem to make it so the header doesn't render.

 

stuff like this is  working fine:

 

 <apex:column headerValue="{!$ObjectType.Inventory__c.fields.Root_Cause__c.label}" rendered="{!$UserRole.Name != 'Plexus Partner User'}">
  <apex:outputText value="{!rmaInv.Inventory__r.Root_Cause__c}"/>
</apex:column>

 

 

 

But if i try a modestly more complex switch

 

It simple doesn't render the content but keeps the header entry intact so all the remaining cells are shifted to the left:

<apex:column rendered="{!AND($UserRole.Name != 'Partner User', rmaInv.Inventory__r.Confirmed_Diagnosis__c!='Completed by Partner')}">
  <apex:facet name="header">{! IF(AND($UserRole.Name != 'Partner User', rmaInv.Inventory__r.Confirmed_Diagnosis__c!='Completed by Partner'),'noheader',$ObjectType.Inventory__c.fields.Echo_Remote__c.label)}</apex:facet>
  {!AND($UserRole.Name != 'Partner User', rmaInv.Inventory__r.Confirmed_Diagnosis__c!='Completed by Partner')}<br />
  {!rmaInv.Inventory__r.Echo_Remote__c}<br/>
  {!IF(AND($UserRole.Name != 'Partner User', rmaInv.Inventory__r.Confirmed_Diagnosis__c!='Completed by Partner'),$ObjectType.Inventory__c.fields.Echo_Remote__c.label,'')}<br />
  {!$UserRole.Name != 'Partner User' && rmaInv.Inventory__r.Confirmed_Diagnosis__c!='Completed by Partner'} 
</apex:column>

 

 

The other weird thing is that no matter what I do, the expression in the <apex:facet> always seems to evaluate to true though in the next line where it's rendered into the sell, it correctly evaluates to the false.

 

Anyone have any ideas?

I'm trying to build a massLeadConverter for some data clean up and it keeps failing on older campaign members.

 

I have this stretch of code from an after update trigger on a lead:

 

for(CampaignMember cm :members) {
                
    cm.Status = Trigger.newMap.get(cm.LeadId).Status;
    totest = cm.Id;
    system.debug(totest);
    if (cm.CurrencyIsoCode != Trigger.newMap.get(cm.LeadId).CurrencyIsoCode){
        system.debug('switching  currency to '+string.valueOf(Trigger.newMap.get(cm.LeadId).CurrencyIsoCode));
        cm.CurrencyIsoCode = Trigger.newMap.get(cm.LeadId).CurrencyIsoCode;
    }
}
//Important! Available values for status from CampaignMember are assigned dynamically from
//parent Campaign record. Also they can be found as records of CampaignMemberStatus object.
            update members;

 and when  a lead with a currencyisocode of USD associated with a campaign member with a currencyisocode of 000 this this code. I get the debug message switching currencycode to USD but then it bombs out with this error.

 

First exception on row 0 with id 00v8000000J2fwhAAB; first error: INVALID_OR_NULL_FOR_RESTRICTED_PICKLIST, Currency ISO Code: invalid currency code: 000:

 

My vf page, controller, and trigger are all on api 25+.

 

I tried to correct the currencyisocode on the campaign member with Data Loader 25.0.2 and it givesme the  same error.

 

Then I tried to correct the record by adding the currencyisocode to detail  page. No amount of magic appears to be able to put it on there and make it actually appear.

 

I have system admin privileges and everything looks right on the permissions.

 

Anyone have any ideas on why I can't seem to update this field?

I'm trying to avoid proliferating customer profiles  based  on all the different configurations they could possibly have to see tabs.

 

Is there anyway to programatically hide or show customer portal tabs?

I'm trying to deploy a new custom object + and Apex Class + Test Class and a couple triggers. When I run my tests on my sandbox, it tests fine.

 

When I try to deploy it, it fails and says I have too many SOQL statements and throws the error on an unrelated trigger that should never get fired in my tests.

 

How can  I figure out where other stuff is being fired besides my test class?

I'm trying to create a formula field on Leads to show what stage a lead is in our sales lifecycle. It's all going smoothly until I try to determine if the associated opportunity is Won. I just can seem to figure out the proper method to pull it into the lead.

 

The standard formula field edit on leads will give me the ConvertedOpportunityID but it doesn't  allow me to access any information from the opportunity

 

I tried using a custom lookup  field  + a trigger but the trigger on the lead to populate the custom field but since the ConvertedOpportunityID is populated on conversaion, it's not accessible from before update trigger  and you can't use the after update option since the record at that point is locked.

 

Anyone have any success along these lines

I'm trying to create a formula field on Leads to show what stage a lead is in our sales lifecycle. It's all going smoothly until I try to determine if the associated opportunity is Won. I just can seem to figure out the proper method to pull it into the lead.

 

The standard formula field edit on leads will give me the ConvertedOpportunityID but it doesn't  allow me to access any information from the opportunity

 

I tried using a custom lookup  field  + a trigger but the trigger on the lead to populate the custom field but since the ConvertedOpportunityID is populated on conversaion, it's not accessible from before update trigger  and you can't use the after update option since the record at that point is locked.

 

Anyone have any success along these lines

 

I'm having a problem efficiently getting related field in a trigger. I have the following code

System.debug('User Contact ID='+myRecord.Time_Clock__r.Team_Member_Employee__c);
System.debug('Time Clock ID='+myRecord.Time_Clock__c);
Time_Clock__c myTimeClock = [select id,Team_Member_Employee__c from Time_Clock__c where Id=:myRecord.Time_Clock__c];
System.Debug('On Object Team_Member_Employee = '+myTimeClock.Team_Member_Employee__c);

 

And this is the result from the debug log

 

07:16:56.035 (35542000)|USER_DEBUG|[5]|DEBUG|User Contact ID=null
07:16:56.035 (35594000)|USER_DEBUG|[6]|DEBUG|Time Clock ID=a0gV00000008YBUIA2
07:16:56.047 (47935000)|USER_DEBUG|[10]|DEBUG|On Object Team_Member_Employee = 003V0000005F2uRIAS

 

My Question is why am I getting Null as Id in the first (myRecord.Time_Clock__r.Team_Member_Employee__c) get the correct Id in the3rd (instantiate a new Time_Clock__c then get Team_Member_Employee__c)?

 

Is there some trick to making myRecord.Time_Clock__r.Team_Member_Employee__c not null and in line with 3rd?

 

I need to run a further SOQL statement based on the Team_Member_Employee__c field and I'd like to avoid have two SOQL queries for one trigger pass. 

I'm having a problem finding the right syntax for a pretty simple SOQL query.

 

So i have a basic query

 

Select Time_Clock__r.Team_Member_Employee__c FROM Time_Record__c where Id='xxxx'

 

which will return the Contact Id. Now I need to get the User associated with that contact. I've tried

 

SELECT Id from User where ContactId in (Select Time_Clock__r.Team_Member_Employee__c FROM Time_Record__c where Id='a0D3000000CiPAk')

 

and

 

SELECT Id from User where ContactId = (Select Time_Clock__r.Team_Member_Employee__c FROM Time_Record__c where Id='a0D3000000CiPAk')

 

I can't seem to find the correct syntax to achieve this. I'd appreciate any help.

I'm running into a baffling problem in my test class. I can't figure out why it keeps faiing the validation check on what should be relatively straightforward code.

 

It's got to be something simple I'm just not seeing.

 

 

Here's the relevant code:

 

        //create test contact
        testContact.Account = testAccount;
        testContact.LastName = 'Test Last Name';
        testContact.RecordType = [select Id from RecordType where Name = 'Team Contacts' and SobjectType = 'Contact'];       
        System.debug('Record type: '+testContact.RecordType);
        insert testContact;


        //create test time record
        testTimeClock.Start_Time__c = date.valueOf('2011-12-20T23:01:01Z');
        testTimeClock.End_Time__c = date.valueOf('2011-12-20T23:45:01Z');
        testTimeClock.Rate_My_Day__c = 'I had a great day!';
        testTimeClock.Team_Member_Employee__c = testContact.Id;
        insert testTimeClock;

 Now the testTimeClock.Team_Member_Employee__c field has a lookup filter that requires the contact record to of the Team Contacts record type.

 

Whenever I run this code, it fails on the insert testTimeClock; with the following message:

 

08:17:46.303 (303452000)|EXCEPTION_THROWN|[27]|System.DmlException: Insert failed. First exception on row 0; first error: FIELD_FILTER_VALIDATION_EXCEPTION, Value does not exist or does not match filter criteria.: [Team_Member_Employee__c]
08:17:46.309 (309540000)|FATAL_ERROR|System.DmlException: Insert failed. First exception on row 0; first error: FIELD_FILTER_VALIDATION_EXCEPTION, Value does not exist or does not match filter criteria.: [Team_Member_Employee__c]

 

If there's someone who can help me see the error of my way, i'd be v. appreciative.

 

 

Hi there,

I have created a class that stores trigger names to be deactivated during tests (I try to make a lot of unit tests, so I'm not interested in firing all my triggers on every test, and it is better to disable some of them to avoid reaching SOQL limits). So my tests have something like this:

TriggerDisabler.Disable('MyTriggerName');

And my triggers now add something like this as their first lines:
if (TriggerDisabler.IsTriggerDisabled('MyTriggerName')) {
    return;
}

But I would like to make this more generic, using something like a "trigger.Name" or something (without queries) that could return me the trigger's name, or eventually changing that method call in the trigger to "TriggerDisabler.AmIDisabled()" which could handle this itself.

Is this possible? I took a quick look in some forums and examples but couldn't find any way to obtain the trigger's name.

Any other suggestions are also welcome!

Cheers.
Hello,

I just made this formula and thought it could save someone in the future some time.  Entering this into a formula field will give you the full state name based on abbreviation, just do a simple find and replace for "Field" in excel to edit the formula for your specific need.

if(Field='AL','Alabama',if(Field='AK','Alaska',if(Field='AZ','Arizona',if(Field='AR','Arkansas',if(Field='CA','California',if(Field='CO','Colorado',if(Field='CT','Connecticut',if(Field='DE','Delaware',if(Field='FL','Florida',if(Field='GA','Georgia',if(Field='HI','Hawaii',if(Field='ID','Idaho',if(Field='IL','Illinois',if(Field='IN','Indiana',if(Field='IA','Iowa',if(Field='KS','Kansas',if(Field='KY','Kentucky',if(Field='LA','Louisiana',if(Field='ME','Maine',if(Field='MD','Maryland',if(Field='MA','Massachusetts',if(Field='MI','Michigan',if(Field='MN','Minnesota',if(Field='MS','Mississippi',if(Field='MO','Missouri',if(Field='MT','Montana',if(Field='NE','Nebraska',if(Field='NV','Nevada',if(Field='NH','New Hampshire',if(Field='NJ','New Jersey',if(Field='NM','New Mexico',if(Field='NY','New York',if(Field='NC','North Carolina',if(Field='ND','North Dakota',if(Field='OH','Ohio',if(Field='OK','Oklahoma',if(Field='OR','Oregon',if(Field='PA','Pennsylvania',if(Field='RI','Rhode Island',if(Field='SC','South Carolina',if(Field='SD','South Dakota',if(Field='TN','Tennessee',if(Field='TX','Texas',if(Field='UT','Utah',if(Field='VT','Vermont',if(Field='VA','Virginia',if(Field='WA','Washington',if(Field='WV','West Virginia',if(Field='WI','Wisconsin',if(Field='WY','Wyoming','Other'))))))))))))))))))))))))))))))))))))))))))))))))))

Have a great day!
Hi All,

I am having a visualforce page, with a tabpanel component.
<apex:tabpanel switchType="client">
    <apex:tab name="tab1" onTabEnter="parent.setHeight(window);">
     ----------some content------
    </apex:tab>
     <apex:tab name="tab2" onTabEnter="parent.setHeight(window);">
     ----------some other content------
   </apex:tab>
</apex:tabpanel>
First tab will be having content of 1600 px height and second tab content will be having 400px height.

I am displaying this visualforce page in another vf page using an iframe.
I am setting the height of the iframe dynamically onload of the iframe, using the following javascript function.
   function setHeight(obj)
   {
        obj.style.height=obj.contentWindow.document.body.scrollHeight+'px';
    }
   ................
  <apex:iframe html-oncomplete="setHeight(this)" scrolling="false"/>


But when I click on any tab, in the iframe the parent method are not getting called.
Even I am not able to switch the tabs.

In the debug console, its showing an error like following:
"XMLHttpRequest cannot load ..... No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin '.....' is therefore not allowed access"


Can someone help me with this please?

Thanks
Hi,

I converted my date field in string, so I can updated my other field in account.

    for (Account acc: [SELECT Id, Data_pedido_AR__c, Data_pedido_SA__c FROM Account WHERE id IN: ids]){

    for (Case c: trigger.new) {
   
    if(c.motivo__c == 'Formandos AR' && c.Data_pedido_AR__c != null && Trigger.oldMap.get(c.id).Data_pedido_AR__c != c.Data_pedido_AR__c){
    Datetime d = Date.Valueof(c.Data_pedido_AR__c);   
    String dateStr = d.format('dd/MM/yyyy');
    System.debug('::::::::::: ' + dateStr) ;

        acc.Data_pedido_AR__c = dateStr;
    }
update acc;


It works fine but in my account my field is one day less.
If I put c.Data_pedido_AR__c = 20/05/2014
I get acc.Data_pedido_AR__c = 19/05/2014

Why?
Hi,

I'm getting an error as follows:

System.DmlException: ConvertLead failed. First exception on row 0; first error: UNKNOWN_EXCEPTION, An unexpected error occurred. Please include this ErrorId if you contact support: 395814895-36330 (1700716674): []

Class.MyLead.attachExistingConvert: line 52, column 1
Class.MyLead.convertLead: line 11, column 1
Trigger.LeadTrigger: line 4, column 1

Now, I'm not sure if I've posted in the right place but is there another support department I can contact to get more information on what is this UNKNOWN_EXCEPTION is?

Thanks

Hi Everybody,

I'm pretty new to Apex and have been trying to do a cross object field update. I have two objects Lead and Candidate_Non_Member_c and I want to have the field Candidate_Non_Member__c.Called_C equal to 1 when the Lead.Disposition = ' Registered'.  Also the only way to find the corresponding candidate to the lead is by phone number. Lead.Phone and Candidate_Non_Member__c.Formated_Phone_Number__c. 

This is what I have so far but I've been getting "Error: Compile Error: Expression cannot be assigned at line -1 column -1"

Any help would be great. 
 

Thanks!

trigger Lead_To_Candidate_2 on Lead (after insert, after update)
{
    String objemail;
    String objfirstname;
    String objphone;
   
    for(Lead obj: Trigger.new)
    {
        if (Lead.disposition__c = 'Registered')
        {
            objemail = obj.Email;
            objfirstname = obj.Name;
            objphone = obj.Phone;
        }
    }
   
    List<Candidate_Non_Member__c> candidate = new List<Candidate_Non_Member__c>([SELECT Id, Formated_Phone_Number__c, Called__c FROM Candidate_Non_Member__c WHERE Formated_Phone_Number__c = :objphone]);
    List<Candidate_Non_Member__c> candidateUpdateList = new List<Candidate_Non_Member__c>();
   
    for(Candidate_Non_Member__c c: candidate)
    {
        Candidate_Non_Member__c.Called__c = 1;
    }
        if(candidateUpdateList.size() > 0)
    {
        update candidateUpdateList;
    }
    }

Hi ,

I have a restful class with @HttpGet method, this method having soql query and it will return based on what we are sending as a parameter.

I need to implement this in visualforce page, visualforce page having one text box when user enter value in the text box those value should be passed into the @httpGet method, and that particular text box should return a result(Searched Item).

Please help me to this problem...!

I have a customer email handler class that takes email messages and does some actions.  One of the things it does is create a comment on the appropriate case with the body of the email included.

The comment that it creates contains some language pertaining to the email, when it was received, the source, and a list of any attachments included.  I have set the piece the code up to automatically reduce the length of the comment to fall well within the 4000 character limit, but for some reason the code is still throwing errors when emails are received that are too long.

Here is a snippet of the code:
        string commentBody;       
        commentBody += 'Email Subject:  ' + email.subject + ' \r\n';    
        commentBody +=  ' \r\n';
        commentBody +=  'Email Body:  ' + ' \r\n';
        if(email.plainTextBody.length() > 3500){
         commentBody = commentBody + email.plainTextBody.trim().left(3500)+ '\r\n' + '\r\n' + '**NOTE: EMAIL BODY TRUNCATED IN COMMENT. SEE EMAIL ATTACHED TO CASE FOR FULL TEXT**';         
        }else{
         commentBody += email.plainTextBody.trim();
        }     
        if(fileAttachmentNames.size() > 0){
            string attachmentsText;
            attachmentsText += ' \r\n';
            attachmentsText += ' \r\n';
            attachmentsText += 'Attachments received:  ';           
            For(String faName :fileAttachmentNames){
                attachmentsText += ' \r\n';
                attachmentsText += faName;
            }
            commentBody = commentBody.left(3500 - attachmentsText.length());
            commentBody += attachmentsText;
        }
       
        newComment.CommentBody = commentBody.trim();
        insert newComment;

However, as I am using the left() method to reduce the length of the comment to 3500 characters I am still getting this error when the email is too long:
"System.DmlException: Insert failed. First exception on row 0; first error: STRING_TOO_LONG, Body: data value too large:"  The error is being thrown on the INSERT line, not before so it is acting like the comment body is too long or something.  Is it possible that the left() method is ignoring HTML values in the string or something?  What other methods should I use to help make sure that the comment stays within the 4000 character limit?
 

Thanks,

Jeremy Stender

Hi,

We have installed package in production / test org. When we try to navigate from one visual force page to another visual force

page in "Sites", we see issue with binding input field.

Issue seems to be happening when we use external template page ( template which is not packaged in our package ) and not with

the template page which we ship.

We looked closely at external template for wrong Namespace use but doesn't found anything.

Also, when the page is loaded for the first time it's working fine, on click of "Save" button, we redirect page to another

visual force page and at that time the issue is coming.

When we submit ( save ), it try to reload the page and that's where it breaks with above error. On First load, it doesn't have

any issue with binding.

On that page, after doing some debugging, we understood that, it has some issue with the binding variable for Input field (i.e

if we use input text, input text area etc, it works fine ).

Here is what the Visual force error looks like ::

Could not resolve field 'Response__c' from value binding '{!RQR.RQResponse.Response__c}' in page portalresponseentry

We are using wrapper class and dynamically binding field using that wrapper class with "Input Field".

Above visual force page and controller are not changed since last release of our package. Between last relase and current

release of our product there has been release by salesforce. This issue seems to happen after latest salesforce ( spring )

release. Before that this page was working fine.

In non package environment, we couldn't reproduce the issue.

Please find below sample code with comments ::

===========================================================================================
/*
Controller class which extends portal base controller.
In Base controller, we have method to identify template.

Template page can be configured different for different production orgs.
It would be external template page for branding etc.

If external template is not specified, we use our internal tempalte page ( internal == shipped with package )
*/

public without sharing class EnterMultipleResponses extends PortalBaseController
{
    public List<ResponsesWrapper> m_prqdetails {get; set;}

    public List<ResponsesWrapper> getPortalResponses()
    {
        // This method creats list of wrapper class
    }

    // This method save and redirect
    public PageReference saveAndRedirect()
    {
        PageReference redirectPage = new PageReference(Page.PortalHomePageSelector.getUrl());
        redirectPage.setRedirect(true);
        return redirectPage;
    }

    // Inner class
    public class ResponsesWrapper implements Comparable
    {
        public Requirement_Question_Response__c RQResponse {get;set;}
    }
}

======== Page code =================================

<apex:page standardcontroller="Requirement_Question_Response__c" recordSetVar="allRQRs" extensions="EnterMultipleResponses"

sidebar="false" showHeader="false">
<apex:form >
 
  <!-- strTemplatePageName , comes from what is configured for that client -->
 
  <apex:composition template="{!strTemplatePageName}">
  <apex:define name="mainContents">
  
   <apex:repeat value="{!PortalResponses}" var="RS">
    <apex:pageBlockTable value="{!RS.m_prqdetails}" var="RQR">
     <apex:inputText value="{!RQR.RQResponse.Response__c}" />
    </apex:pageBlockTable>
   </apex:repeat>

  </apex:define>
  </apex:composition>
</apex:form>
</apex:page>

Thanks.
HI, total noob here. 
I have a n object called Preference__c, has an account field, and has a contact field. What I am trying to do is simple, fill in the contact, the account is auto filled in. It works fine on the regular UI, but when doing the test method, thr trigger doesn't seem to be firing. Does it need a delay of some sort? 


The Trigger
=====================================================

trigger AutoPopulateCompany on Preference__c (before insert, before update)
{
    for(Preference__c pref: trigger.new){
        if(pref.Contact__c != null && pref.Account__c == null){
            //Instantiate the Preference class
            Preference.autoPopulateCompany(pref);
        }
    }   
}

Preference Class
=====================================================

public with sharing class Preference   
{
    //Used to populate the company of the account automatically if it is not filled in by the user
    public static void autoPopulateCompany(Preference__c preference)
    {
        set<Id> conIdSet = new set<Id>();
       
        conIdSet.add(preference.Contact__c);
       
        //Query for the account associated with the preference contact and place in a map
        map<id, contact> conMap = new map<id, contact>([SELECT id, accountid from contact where Id in: conIdSet]);
       
        //check if map is not empty (the contact's account is not null)
        if(!conMap.isEmpty())
        {
            preference.Account__c = conMap.get(preference.Contact__c).accountId;           
        }
    }
}

Test Class
=====================================================

@isTest
private class TestPreference
{
    private static testmethod void testAutoPopulateCompany()
    {
       //Test Data Prep
       //----------------------------------------------------
      
       //Create 2 test accounts
       Account acc1 = new Account();
       acc1.Name = 'Acc1-ACX';
       insert acc1;
      
       Account acc2 = new Account();
       acc2.Name = 'Acc2-ACX';
       insert acc2;
          
       //Create test contact with account 1
       Contact con1 = new Contact();
       con1.FirstName = 'con1';
       con1.LastName = 'ACX';
       con1.Account = acc1;
       insert con1;
      
       //Create test contact with account 2
       Contact con2 = new Contact();
       con2.FirstName = 'con2';
       con2.LastName = 'ACX';
       con2.Account = acc2;
       insert con2;
      
       //Create test contact with no account
       Contact con3 = new Contact();
       con3.FirstName = 'con3';
       con3.LastName = 'ACX';
       insert con3;
      
       //Test Create
       //----------------------------------------------------
      
       //Test Create with contact with account NOT filled in
       Preference__c pref = new Preference__c ();
       pref.Name = 'Test Pref 1';
       pref.Contact__c = con1.Id;
       insert pref;
      
       //Assert - Expected result: Preference Account filled in with Acc1
       pref = [SELECT Id, Account__c FROM Preference__c WHERE Id = :pref.Id];
       System.assertEquals(Acc1.Id, pref.Account__c);            
    }
}

The result
=================================================================

System.AssertException: Assertion Failed: Expected: 001F0000015bMbpIAE, Actual: null

The trigger should have populated pref.Account__c...but I get null. When I test on the actual UI, it works fine. 

Thanks in advance. 
Hi All - I'm somewhat familiar with the Non-Selective query problem, however, this one has got me stumpped.  My company has a full sandbox and I have my own development sandbox.  The same piece of code in our Full Sandbox and Production is causing a non-selective query in my dev sandbox.  No issue at all in Full SB or Production.

The query is as follows:  Note that this is in an After Update / After Insert Opportunity Trigger helper class.

for(CampaignMember cm: [SELECT id, ContactId FROM CampaignMember WHERE Campaign.Id =: campaignId])
{
    existingCampMembers.add(cm.ContactId);
}

I have one campaign member on one campaign in my dev sandbox.....that's it!!

If I execute query in developer console it returns the record.  If I execute anonymous, it finds the record no problem.  Also, if I were to change the filter to specify a contactid instead of campaign.id I do not get non-selective error.  So clearly there is something going on with Campaign.Id, but why here and not in Full SB or Production?

So does anyone have any ideas as to why I'm getting a non-selective query in my dev sandbox but not full sb or production?

Thank you in advance for any suggestions.

Jason

Below is the complete error message.

Error: Invalid Data.
Review all error messages below to correct your data.
Apex trigger OpportunityTrigger caused an unexpected exception, contact your administrator: OpportunityTrigger: execution of AfterUpdate caused by: System.QueryException: Non-selective query against large object type (more than 100000 rows). Consider an indexed filter or contact salesforce.com about custom indexing. Even if a field is indexed a filter might still not be selective when: 1. The filter value includes null (for instance binding with a list that contains null) 2. Data skew exists whereby the number of matching rows is very large (for instance, filtering for a particular foreign key value that occurs many times): Class.OpportunityTriggerLogic.addCampMbrToBldrPrgm: line 79, column 1
  • May 06, 2014
  • Like
  • 0
Hey everyone,

I've written an After Insert trigger that looks at the Created By ID and then transfers the record to a different owner. Here are the issues:

-You can't update the same record in an After trigger or else you'll get the "Record is read-only" error
-I can't use a Before trigger, since my trigger is looking at an ID, which doesn't exist yet in a Before trigger

So how would I go about modifying my code to do what I need? I've heard that I need to either "clone the record" or "query anew", but I'm not exactly sure how to use those approaches with my example. 

Please take a look at my trigger and let me know what I should change. (By the way, this trigger also sends an email, as you can see) .

Here is the error when I test it out in the Sandbox:

User-added image


Here is the trigger (I've bolded the line where the error occurs):

public class ClassLibraryTaskEmail{
    
    public void sendEmail(List<Task> tasks){
        
        Set<String> contactsInTrigger = new Set<String>();
        Map<String,String> contactMap = new Map<String,String>();
        Map<String,String> IDmap = new Map<String,String>();
        List<Task> tasksToTransfer = new List<Task>();
        
        FOR(Task tk : tasks){
            IF(tk.WhoId != NULL && string.valueOf(tk.WhoId).startsWith('003')){
                contactsInTrigger.add(tk.WhoId);
                contactMap.put(tk.Id,tk.WhoId);
            }
        }
        
        List<Contact> validContacts = [SELECT
                                      	Id,AccountId,Account.Assigned_ID__c
                                       FROM
                                      	Contact
                                       WHERE
                                      	Id In: contactsInTrigger];
        
        FOR(Contact c : validContacts){
            IDmap.put(c.Id,c.Account.Assigned_ID__c);
        }
        
        FOR(Task tsk : tasks){
            IF(string.valueOf(tsk.CreatedById).contains('005A0000002rvG0')){
                ID newOwner = IDmap.get(contactMap.get(tsk.Id));
                tsk.OwnerId = newOwner;
                tasksToTransfer.add(tsk);
            }
        }
        
        List<Messaging.SingleEmailMessage> mails = New List<Messaging.SingleEmailMessage>();
        List<String> emails = New List<String>();
        
        List<User> recipients = [SELECT
                                	Id, Email
                                 FROM
                                	User
                                  WHERE
                                	Library_Task_Recipient__c = TRUE];
        
        FOR(User u : recipients){
            IF(u.Email != NULL){
            
            	emails.add(u.Email);
                
            }
            
        }
        
        FOR(Task t : tasks){
            
            IF(emails.size() > 0 && string.valueOf(t.CreatedById).contains('005A0000002rvG0')){
                
                Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
                
                List<String> sendTo = New List<String>();
                
                mail.setToAddresses(emails);
                mail.setReplyTo('greg@offerpop.com');
                mail.setSenderDisplayName('Greg Annunziata');
                
                mail.setSubject('Library Contact Has Filled Out Form');
                String body = 'Greetings director, <br><br>';
                body += 'A contact under a Library account has filled out a form. Please follow up.<br><br>';
                body += 'A link to the task can be found here: https://na7.salesforce.com/'+ t.Id;
                mail.setHtmlBody(body);
                
                mails.add(mail);
                               
            }
            
        }
        
        Messaging.sendEmail(mails);
        UPDATE tasksToTransfer;
        
    }

}

Thanks!
-Greg
Hi,

I am creating a task and reminder using workflow when certain conditions satisfy.
It creates a task with reminder as default(8 AM)
but i want to set it something similar to custom datetime field on task.For example, if my custom field value is set to 3/15/2014   5:40PM then i want reminder time to set to 6 PM .
I am writing a trigger to achieve this but not sure of time rounding to nearest time.please help.
Hi,
I'm pretty new in SF development and I would like to perform the following : when an opportunity is changing the status to closed won, I would like to show the page layout of a custom object.  I've written the following Apex code (for my test I imagine that my custom object is Account object), it seems that my condition is good but the account page doesn't display.  Could you please help me ?

Didier

Here is my code

trigger Action_on_Closed_Won on Opportunity (after update)
{
    Opportunity ops_new = Trigger.new[0];
    Opportunity ops_old = Trigger.old[0];
   
    if ( ops_new.IsWon && !ops_old.IsWon )
    {
        System.debug( 'Before Account' );
        Account a = new Account();
        System.debug( 'After Account' );
    }
    else
    {
        System.debug( 'Else' );
    }
}
I have a requirement like this. Please reply to me ASAP.

In Lead standard object I have created one custom field called Compaign Name. I want to populate this field based on compaign history field called Status and Start date fields. Based on below criteria it would have populate...

If compaign history contains morethan one record then  based on most recent Date (Consider Start Date, Time Stamp field) record compaign Name should populate on Lead object custom field. I have already tried with  trigger and its working fine but businees said do not use trigger because each lead getting compaigns morethan 3000 per day so, it could be a performance issue when we use trigger. Please suggest me any other solution by using Reports or other solution. I am struggling with this requirement ...please help me.

Regards,
kk

Note : 

Hi,

I have a custom field where is stored a 15 digits Id.
I need to build a String csv with the 18 digits version of this Id.
In my Execute anonymous window, I tried a simple

system.debug(Id.valueOf('101c00000001GWe'));

 


and got

USER_DEBUG|[2]|DEBUG|101c00000001GWeAAM

 


Wonderful, that's what I need !  But when I try to write in my class

csv += Id.valueOf(var);

 


I get an ugly

Save error: variable does not exist: Id

 



I finally did what I need by creating a variable with

Id myId = String.valueOf(var); 
csv += myId;

 


But I don't understand why the documented static method Id.valueOf works in anonymous code and not in a class ?

 

I have a custom object, that includes multiple fields,

 

But the account and contact names are taken from the respective account and contact standard objects,

 

So if you go in the custom object fields, you will se that they are lookup fields for those standard objects,

 

Question: The following few lines call a specific user data based on their IP address:

 

public with sharing class main_sub {
    public List<Trainee__c> trainee{get;set;}
    public List<Contract> license{get;set;}

public PageReference Sub{
license = new List<Contract>();


license  = [select StartDate,

Host_Name__c,License_Type__c,Volume_Serial_Number__c,Expiration_Date__c,Physical_Address__c from Contract where Physical_Address__c=:'IP ADDRESS' ]; 



}
}

 

How can I call the Account name and Contact name for that IP address?

 

If someone can provide a link to an example that explains this, That would be great,

 

Thanks