• Starz26
  • PRO
  • 4926 Points
  • Member since 2011

  • Chatter
    Feed
  • 188
    Best Answers
  • 4
    Likes Received
  • 2
    Likes Given
  • 119
    Questions
  • 1347
    Replies

Hello,

 

In my test method it looks like there is no pricebook record I can use.

The following code returns the value 0 while I have 4 Pricebook records in my sandbox.

 

System.debug('There is '+[SELECT COUNT() FROM Pricebook2]+ ' Pricebook(s)');

 

 

Do I have to recreate all records in the test method in order to use them?

I attempted SF Support twice to fix this issue, which has failed to resolve the issue.  So, I wanted to take it to the developer community to see if it is a problem with only us or if it's something larger.

 

We have a couple of classes that give the functionaly to change the users' passwords by calling System.setPassword(<UserId>, <Password);  These classes have been unchanged for many months and we have been deploying other code just fine.  This was the case until the Winter '14 update.  Ever since that update we have not been able to deploy *any* code due to those two classes erroring out with an Unexpected_Exception.  This happens even if we try to deploy an empty class.  If we comment out the lines (thus removing that functionality), the deployments are successful. 

One more oddity about this is that the test methods for these classed succeed if they are ran; it only fails during a deploy.

 

So, does anyone use this functionality/call?  Are they experiencing problems deploying?

  • October 31, 2013
  • Like
  • 0

Hi all,

I've got a Too many query rows problem in a class.

I've got a custom object, call Prodotti_promozioni_commerciali__c, from I want to create a custom dashboard. This object is a sort of "Bridge object" and has a relationship with Prodotto__c object, who has a Famiglia_dsh__c and a Set_Prod_dsh__c fields, and a relationship with account, who has a ACCOUNTCATEGORY_MI__c fields. It is correlated to another custom object (Promozione_commerciale__c) too. The idea is this: I select from a wizard a family, and I can see for every family the percentage of account related with a promotion (represented with Prodotti_promozioni_commerciali__c object) between total accounts . Every family has 3 or 4 sets correlated to it, and every account can have one between four category: A, B, C,D. The dashboard is composed by lines and columns, the lines represent the set of products for each family, the columns represent possible account category. I have also a datetime picker in order to specify the dates range in which the Prodotti_promozioni_commerciali__c must be shown, depending of Data_adesione__c field of Promozione_commerciale__c object. I have a Bonus picklist Yes/no/all too, if I select Yes, I should see only records with Bonus__c checkbox field = true, same thing if select No, while if I select all I should see both records.

In my code I make a for loop for each product set, like this: in this case I consider only A category, for B,C,D category code is similar.

 

for (string selectedSetProd: listasetProdotti) {

listapromcommA = new set<string>();
List<Prodotti_promozioni_commerciali__c> listaaccounttotA = new List<Prodotti_promozioni_commerciali__c>();
if(selectedBonus == 'all'){
listaaccounttotA = [select Promozione_commerciale__r.Referente__r.AccountId,
Promozione_commerciale__r.Referente__r.Account.ACCOUNTSTATUS_MI__c,
Promozione_commerciale__r.Referente__r.Account.ACCOUNTCATEGORY_MI__c,
Promozione_commerciale__r.Referente__r.Account.RecordType.DeveloperName,
Promozione_commerciale__r.Referente__r.Account.Form_Acc_Cat__c from
Prodotti_promozioni_commerciali__c where Promozione_commerciale__r.Referente__r.Account.Ownerid in:utentiriferimento
AND Promozione_commerciale__r.Referente__r.Account.ACCOUNTSTATUS_MI__c = 'Attivo'
AND Promozione_commerciale__r.Referente__r.Account.RecordType.DeveloperName = 'Ambulatorio'
AND Promozione_commerciale__r.Referente__r.Account.ACCOUNTCATEGORY_MI__c = 'A'
AND Promozione_commerciale__r.Referente__r.Account.ABILITATED_MI__c = true
AND Promozione_commerciale__r.Referente__r.Account.CHECKACCOUNT_MI__c = true
AND Prodotto__r.Famiglia_dsh__c =:selectedFamilyNew
AND Prodotto__r.Set_Prod_dsh__c =:selectedSetProd
AND Promozione_commerciale__r.Data_adesione__c >=: datainizio
AND Promozione_commerciale__r.Data_adesione__c <=: datafine
AND Promozione_commerciale__r.Stato__c = 'Approvata'
];

}
else
{
listaaccounttotA = [select Promozione_commerciale__r.Referente__r.AccountId,
Promozione_commerciale__r.Referente__r.Account.ACCOUNTSTATUS_MI__c,
Promozione_commerciale__r.Referente__r.Account.ACCOUNTCATEGORY_MI__c,
Promozione_commerciale__r.Referente__r.Account.RecordType.DeveloperName,
Promozione_commerciale__r.Referente__r.Account.Form_Acc_Cat__c from
Prodotti_promozioni_commerciali__c where Promozione_commerciale__r.Referente__r.Account.Ownerid in:utentiriferimento
AND Promozione_commerciale__r.Referente__r.Account.ACCOUNTSTATUS_MI__c = 'Attivo'
AND Promozione_commerciale__r.Referente__r.Account.RecordType.DeveloperName = 'Ambulatorio'
AND Promozione_commerciale__r.Referente__r.Account.ACCOUNTCATEGORY_MI__c = 'A'
AND Promozione_commerciale__r.Referente__r.Account.ABILITATED_MI__c = true
AND Promozione_commerciale__r.Referente__r.Account.CHECKACCOUNT_MI__c = true
AND Prodotto__r.Famiglia_dsh__c =:selectedFamilyNew
AND Prodotto__r.Set_Prod_dsh__c =:selectedSetProd
AND Promozione_commerciale__r.Data_adesione__c >=: datainizio
AND Promozione_commerciale__r.Data_adesione__c <=: datafine
AND Promozione_commerciale__r.Stato__c = 'Approvata'
AND Bonus__c =: selectedBonusBool];
}

for(Prodotti_promozioni_commerciali__c ppc:listaaccounttotA){
listapromcommA.add(ppc.Promozione_commerciale__r.Referente__r.AccountId);
}

List<AggregateResult> countaccountpromoAntintA = [SELECT count(Id) conteggiopromo
FROM Account
WHERE Id in: listapromcommA
];

 if(listaaccounttotA.size()> 0) {
DHW_Merial_2__c dmerial = new DHW_Merial_2__c();
dmerial.name = 'prova';
if(listaaccounttotA.size()> 0){
dmerial.Form_Account_accountStatus__c = listaaccounttotA.get(0).Promozione_commerciale__r.Referente__r.Account.ACCOUNTSTATUS_MI__c;
dmerial.Form_ProdottiPromozioniComm_Prodotto_Fam__c = selectedFamilyNew;
dmerial.Form_ProdottiPromozioniComm_Prodotto_Set__c = selectedSetProd;
dmerial.Form_Account_Category__c = listaaccounttotA.get(0).Promozione_commerciale__r.Referente__r.Account.ACCOUNTCATEGORY_MI__c;
dmerial.Form_Account_RecordTypeId__c = listaaccounttotA.get(0).Promozione_commerciale__r.Referente__r.Account.RecordType.DeveloperName;
}

if( String.valueOf(countaccountpromoAntintA.get(0).get('conteggiopromo')) == null || String.valueOf(countaccountpromoAntintA.get(0).get('conteggiopromo')) == 'NaN'
|| countaccountpromoAntintA.get(0).get('conteggiopromo') == '0'
|| countaccountpromoAntintA.get(0).get('conteggiopromo') == 0){

 

dmerial.Count_account_promo__c = 0;
}
else
{
dmerial.Count_account_promo__c = Integer.valueOf(countaccountpromoAntintA.get(0).get('conteggiopromo'));
}

if( String.valueOf(countaccountotaleA.get(0).get('conteggiotot')) == null || String.valueOf(countaccountotaleA.get(0).get('conteggiotot')) == 'NaN' ){
dmerial.Count_account__c = 0;
}
else
{
dmerial.Count_account__c = Integer.valueOf(countaccountotaleA.get(0).get('conteggiotot'));
}
dmerial.name = 'testdmerial'+ Date.today();
insert dmerial;

List<DHW_Merial_2__c> numero = [select Count_account_percent__c from DHW_Merial_2__c where id =: dmerial.id limit 1];

if(numero.size()> 0){
numeropercent = numero.get(0).Count_account_percent__c;

}
acccounta = dmerial.Count_account__c;


if(conteggioA == 0){
percentuale1a = numeropercent;
accpromo1a = dmerial.Count_account_promo__c;
}
else if(conteggioA == 1){
percentuale2a = numeropercent;
accpromo2a = dmerial.Count_account_promo__c;
}
else if(conteggioA == 2){
percentuale3a = numeropercent;
accpromo3a = dmerial.Count_account_promo__c;
}
else if(conteggioA == 3){

percentuale4a =numeropercent;
system.debug('percentuale 4a debug' + numeropercent);
accpromo4a = dmerial.Count_account_promo__c;

}
conteggioA++;


}
if(acccounta== 0){
formulaaccpromoa = 0;
}
else {



formulaaccpromoa = (100 * (Integer.valueOf(countaccountpromoAntintAtuttiprod.get(0).get('conteggiopromo'))))/acccounta; 

}

 

For a particular family, cause there are several records, more than other families records, I obtain a "Too many query rows", if I check All bonus , and I check a large range of dates. How can I solve this, without riducing number of records obtained with where filters?

Do I have to re-write code?

Thank you in advance for your support

 

Maria

Hello Helper

 

 

I am having a problem with controller.getSelected();    apex code

 

I have a simple visual  force  page  and an extension class

 

I have a custom button  on a related list  of an object

 

I want to select a few items  on the related list  and perform a mass update on the selected  child  records

 

in the constructor  of the extension class  I call:

 

public MyExtensionClass(ApexPages.StandardSetController controller)

{

 

...

MyChildCustomObject[] EAs = controller.getSelected();

 

if(EAs.size() == 0)
{
SerrMsg = 'Select at least 1 event attendee to update.';
ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,SerrMsg));
errorMsg = true;
return;
}

 

 

..

 

 

}

 

the size  of the EAs  array is always  0

 

 

I am missing something?

 

Regards

Csaba

 

 

 

 

 

 

 

 

 

  • October 30, 2013
  • Like
  • 0

The following code works as far as attaching a visualforce pdf and emailing it to who I want.  

 

What I need help with is that I would like to build a regular HTML email template and call it from my code.

 

Anyone that contributes will get kudos.

 

Here is the code:

 

 public PageReference emailPDF() {
 
     
    List<Contract> ContractToUpdate = new List<Contract>();
    
    for(Contract c : [Select Id, Invoice_Sent__c from Contract where Id =:ParentId])
    {
            c.Invoice_Sent__c = True;
            ContractToUpdate.add(c);
    }

    update ContractToUpdate;
    
 
     ToAddresses = new List <String>();
     ToAddresses.add(cc.Finance_Contact_Email__c);
     
     Subject = 'Hope this works';
     Body = 'This is a test';
 
 
     Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
     PageReference pdf = Page.ContractPDFCreation;
     pdf.getParameters().put('id',parentId); 
     pdf.setRedirect(true);
     
     Blob b; 

        b = pdf.getContent();

      
     Messaging.EmailFileAttachment efa = new Messaging.EmailFileAttachment();
     efa.setFileName('Invoice.pdf');
     efa.setBody(b);
  
     email.setSubject( subject );
     email.setToAddresses( ToAddresses );
     email.setPlainTextBody( body );
     
     email.setFileAttachments(new Messaging.EmailFileAttachment[] {efa}); 
     
     Messaging.SendEmailResult [] r = 
     Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email}); 
    
     return new PageReference('/'+parentId); 
}

 Thank you,

Steve Laycock

 

 

I realize there is a ton of material out there around bulk, batch, scheduled, @future apex, and that's actually my problem...  I'm not really sure what avenue to pursue.  For the sake of simplicity, this existing class updates the description field on Account using a @future HTTP callout (right from a great tutorial on cheenath.com):

 

public class AccountUpdater {

  //Future annotation to mark the method as async.
  @Future(callout=true)
  public static void updateAccount(String id, String name) {

    //construct an HTTP request
    HttpRequest req = new HttpRequest();
    req.setEndpoint('http://cheenath.com/tutorial/sfdc/sample1/data.txt');
    req.setMethod('GET');

    //send the request
    Http http = new Http();
    HttpResponse res = http.send(req);

    //check the response
    if (res.getStatusCode() == 200) {

      //update account
      Account acc = new Account(Id=id);
      acc.Description = res.getBody();
      update acc;
    } else {
      System.debug('Callout failed: ' + res);
    } 
  }
}

 

 

I have a trigger to fire that method after insert, and it works great.  My goal is to run the above @future method 'updateAccount', against all existing Accounts once per month (or a large subset determined by a query) Could you outline the archetecture of the system you'd use? 

 

I am fuzzy around how many classes I need to build (one to schedule, one to batch, one to execute, one to query?) and how they connect.  Can I reuse my existing @future method?  I get lost between batch apex, scheduled apex, how the limits hinder each avenue, etc. 

 

Thanks!

  • July 02, 2013
  • Like
  • 0

I have 100 accounts.I am forming one map with following values.

 

Map<String,String> accounts = new Map<String,String>();

for(Account a : AccountList){

string accountIds = a.Id+'str';

accounts.put(accountIds,a.Name)

}

 

I am using this map in inside of JS function.

 

JS code:

 $(document).ready(function() {

<apex:repeat value="{!AccountList}" var="acct">

 

var CRE = accountId+'str';

var Mapvalue = '{!accounts['+CRE+']}';
console.log('::::::::CRE:::::::'+CRE);

<apex:repeat/>

});

 

I am getting the below error:

 

Map key +CRE+ not found in map

Error is in expression '{!Mapvalue['+CRE+']}' in component <apex:repeat> in page accountsearch
 
Is any one help to get this value of Key(AccountId + string value)?

 

I wrote a trigger to create a task when a certain field is updated.  The trigger works fine and as expected.  However, everytime I run the test class I get the following error:

 

System.DmlException: Update failed. First exception on row 0 with id a0NW0000000ddmlMAA; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, Create_Make_1st_Call: execution of AfterUpdate

caused by: System.NullPointerException: Attempt to de-reference a null object

Trigger.Create_Make_1st_Call: line 43, column 1: []
Class.TestClass_SD_Member_Mailing_History.myUnitTest: line 39, column 1

 

Here is my Test Class:

@isTest
class TestClass_SD_Member_Mailing_History {    
static testMethod void myUnitTest() {        
// TO DO: implement unit test       

// Create SD Member Record
SD_Member__c sd = New SD_Member__c(First_Name__c = 'John', 
                                   Last_Name__c = 'Smith', 
                                   Ins_ID_Member__c = '123456', 
                                   Ins_ID_Suscriber__c = '456789',
                                   address__c = '123 Main Stret', 
                                   city__c = 'Aster', 
                                   state__c = 'CT', 
                                   zip__c = '06001', 
                                   name = 'John Smith',
                                   Lost_Contact_Follow_Up__c = False,
                                   Mailing_Cycle__c='Week 2.1');
insert sd;
          
// Create Mailing Order
printsf__Collateral_Order_History__c PO = new printsf__Collateral_Order_History__c(Name='Dummy Order 02',
                                                                                   printsf__Order_Number__c=2);
Insert po;                                                                                              

// Create SD Mailing History Item
printsf__Collateral_Send_History__c MH = new printsf__Collateral_Send_History__c(Name='Test Mailer Entry XYZ',
                                                                                 printsf__Recipient_ID__c = sd.id,
                                                                                 printsf__Send_History_ID__c = 123654,
                                                                                 printsf__Order__c = po.id);
Insert MH;

//Test Order Execute logic for send "make first Call" task
SD_Member_Mailing_History__c SDMH = New SD_Member_Mailing_History__c(Mailer_History_Item__c =MH.id ,
                                                                     SD_Member_Stakeholders__c = sd.id);
Insert SDMH;

SDMH.Order_Executed__c = True;
system.debug(sd.id);
Update SDMH;


}}

 

Here is my trigger.

trigger Create_Make_1st_Call on SD_Member_Mailing_History__c (After Update) {
//This is the real one!!!!!!

// Variables
    Date CallDate1 = DateTime.now().addDays(-10000).date();

// Create my own Right Text Function
public String right(String s, Integer i) {
        if (s == null || s == '' || i <=0 ) {
            return '';
        } else if (i >= s.length()) {
            return s;
        } else {
            return s.subString(s.length() - i, s.length());
        }
} 
//-----------------------------------------------------------------------

 // Find Entries that meet criteria and new Entries to create
SD_Member_Mailing_History__c [] qualifiedEntry = new SD_Member_Mailing_History__c[0];
Task [] newTask = new Task[0];

// Map of SD Member Ids
    Map<Id,SD_Member__c> members = new Map<Id,SD_Member__c>();
    
// Find qualifing Entries
For (SD_Member_Mailing_History__c record:trigger.new)  
    If(record.Order_executed__c ==True)
           qualifiedEntry.add(record);  

//Obtain SD Member Ids 
For(SD_Member_Mailing_History__c record:qualifiedEntry)   
    members.put(record.SD_Member_Id__c,null); 
    
// If there are any members to query, do so.
   If(!members.isempty())
       members.putall([Select id, Mailing_Cycle__c, Ownerid from SD_Member__c where id in :members.keyset()]);       

// For each qualifing record, create a task.
For(SD_Member_Mailing_History__c record:qualifiedEntry){
// Check to see what mailing cycle the SD Member is in to determine when to make the follow up call         
         If(right(members.get(record.SD_Member_id__c).Mailing_Cycle__c,1)=='1') {
           newtask.add(new task(whatid=(record.SD_Member_id__c),subject='Make 1st Follow Up Call',ActivityDate=record.Date_Delivered__c+3,Status='Not Started', ownerid=members.get(record.SD_Member_id__c).ownerid));
         } Else If(right(members.get(record.SD_Member_id__c).Mailing_Cycle__c,1)=='2') {
             newtask.add(new task(whatid=(record.SD_Member_id__c),subject='Make 1st Follow Up Call',ActivityDate=record.Date_Delivered__c+4,Status='Not Started', ownerid=members.get(record.SD_Member_id__c).ownerid));
         } Else If(right(members.get(record.SD_Member_id__c).Mailing_Cycle__c,1)=='3') {
             newtask.add(new task(whatid=(record.SD_Member_id__c),subject='Make 1st Follow Up Call',ActivityDate=record.Date_Delivered__c+5,Status='Not Started', ownerid=members.get(record.SD_Member_id__c).ownerid));
         } Else If(right(members.get(record.SD_Member_id__c).Mailing_Cycle__c,1)=='4') {
             newtask.add(new task(whatid=(record.SD_Member_id__c),subject='Make 1st Follow Up Call',ActivityDate=record.Date_Delivered__c+6,Status='Not Started', ownerid=members.get(record.SD_Member_id__c).ownerid));
         } Else If(right(members.get(record.SD_Member_id__c).Mailing_Cycle__c,1)=='5') {
             newtask.add(new task(whatid=(record.SD_Member_id__c),subject='Make 1st Follow Up Call',ActivityDate=record.Date_Delivered__c+7,Status='Not Started', ownerid=members.get(record.SD_Member_id__c).ownerid));
         } Else If(right(members.get(record.SD_Member_id__c).Mailing_Cycle__c,1)=='6') {
             newtask.add(new task(whatid=(record.SD_Member_id__c),subject='Make 1st Follow Up Call',ActivityDate=record.Date_Delivered__c+8,Status='Not Started', ownerid=members.get(record.SD_Member_id__c).ownerid));
         } Else If(right(members.get(record.SD_Member_id__c).Mailing_Cycle__c,1)=='7') {
             newtask.add(new task(whatid=(record.SD_Member_id__c),subject='Make 1st Follow Up Call',ActivityDate=record.Date_Delivered__c+9,Status='Not Started', ownerid=members.get(record.SD_Member_id__c).ownerid));
         } Else If(right(members.get(record.SD_Member_id__c).Mailing_Cycle__c,1)=='8') {
             newtask.add(new task(whatid=(record.SD_Member_id__c),subject='Make 1st Follow Up Call',ActivityDate=record.Date_Delivered__c+10,Status='Not Started', ownerid=members.get(record.SD_Member_id__c).ownerid));
         } Else If(right(members.get(record.SD_Member_id__c).Mailing_Cycle__c,1)=='9') {
             newtask.add(new task(whatid=(record.SD_Member_id__c),subject='Make 1st Follow Up Call',ActivityDate=record.Date_Delivered__c+11,Status='Not Started', ownerid=members.get(record.SD_Member_id__c).ownerid));
         //Old Activity Date Logic
         //ActivityDate=DateTime.now().addDays(11).date()
         } 
}
   // Insert new task records into database.
      insert newtask;
}

 

 

Everything was working fine until I changed one line of code in my trigger.  

 

I change the if statements from 

 

newtask.add(new task(whatid=(record.SD_Member_id__c),subject='Make 1st Follow Up Call',ActivityDate=DateTime.now().addDays(11).date(),Status='Not Started', ownerid=members.get(record.SD_Member_id__c).ownerid));
         

 To

 

newtask.add(new task(whatid=(record.SD_Member_id__c),subject='Make 1st Follow Up Call',ActivityDate=record.Date_Delivered__c+11,Status='Not Started'

Any Ideas

 

I need to deploy to production some code, and cannot because only 36% (9/25) of this trigger is covered.

 

I also need to remove this trigger (it's old and is no longer valid for the business - and was written by someone else).

 

Can someone help me with this test class for the following trigger?  Everything in RED is not being tested.

 

I am new to writing triggers and test classes - so any help is greatly appreciated for this newbie....

 

Thanks, 
Chris

 

Here is the Trigger:

 

	  trigger Lead_UpdateAccountsOwner on Lead (after update) {
 2	  
 3	  System.debug('DEBUG::DEBUG-->Lead_UpdateAccountOwner - Converted Account ID : '  + trigger.new[0].convertedAccountId );
 4	      
 5	      List<String> lstOfProfiles=new List<String>();
 6	      lstOfProfiles.add('Product Specialist Standard User');
 7	      lstOfProfiles.add('Product Specialist System Admin User');
 8	      
 9	      List<String> roleNames= new List<String>();
 10	      roleNames.add('PM SuperUser');
 11	      //calling function from validating class
 12	       Boolean resultp=ProfileValidator.validateLoginUserProfile(lstOfProfiles);
 13	       Boolean result = false;
 14	       result=  ProfileValidator.CheckLoginUserRole(UserInfo.getUSerId());
 15	       
 16	    if(result == true)
 17	    {
 18	   

//get converted account ids in set

 19	      set<id> accountIds = new Set<Id>();
 20	      set<id> contactIds = new Set<Id>();
 21	      
 22	      for(Lead ld: trigger.new)
 23	      {
 24	          accountIds.add(ld.convertedAccountId);
 

25

	          contactIds.add(ld.convertedContactId);
 26	      }
 27	      
 28	      //query all converted accounts with owenr id
 29	      Map<id,Account> map_AssociatedAccounts = new Map<id,Account> ([SELECT id, OwnerId from Account WHERE id in: accountIds and Type = 'Prospect']);
 30	      Map<id,Contact> map_AssociatedContacts = new Map<id,Contact> ([SELECT id, OwnerId from Contact WHERE id in: contactIds]);
 31	      
 32	      //change owner of associated accounts
 33	      for(Lead ld: trigger.new)
 34	        {
 35	           Account act = map_AssociatedAccounts.get(ld.convertedAccountId);
 36	           if(act!=null)
 37	            {
 38	               act.OwnerId = ld.OwnerId;
 39	            }
 40	           
 41	           Contact con = map_AssociatedContacts.get(ld.convertedContactId);
 42	           if(con!=null)
 43	            {
 44	               con.OwnerId = ld.OwnerId;
 45	            }
 46	        }
 47	      
 48	      //update accounts
 49	      update map_AssociatedAccounts.values();
 50	      update map_AssociatedContacts.values();
 51	  
 52	  
 53	    }
 54	   
 55	  
 56	  }

 

See associated Test Classes below (60% 9/15):

 

global class LeadOwnerChange implements Database.Batchable<sObject>
{
List<Group> que;
public  LeadOwnerChange ()
 {
   que = new List<Group>(); 
   que = [Select Id ,Type,Name From Group where Name = 'Product Specialist Marketing Group' and type='queue' limit 1];
 }
public String Query{get;set;}
 
 
global Database.QueryLocator start(Database.BatchableContext BC)
   {
     return Database.getQueryLocator(Query);
   }

 global void execute(Database.BatchableContext BC,List<Lead> batch)
   { 
   if(que.size()>0)
   {
     for (Lead led :batch)
      {
      System.Debug('BBBBBBBBBBB'+que);
         System.Debug('AAAAAAAAAA'+led);
        led.OwnerId= que[0].id;
      }
   update batch;
    
   }
   }
  global void finish(Database.BatchableContext BC) 
  {
    
  }
}

 

Here is a second Test Class that is trying to do something...  (25% 1/4)

 

global with sharing class ScheduleLeadOwnerChange implements Schedulable 
{   
    global void execute(SchedulableContext SC)
     {
 
         LeadOwnerChange leadUpdate = new LeadOwnerChange();
         leadUpdate.Query = 'Select l.Id From Lead l  where l.IsConverted = false and l.CreatedDate   < LAST_90_DAYS';
         
         
         Database.ExecuteBatch(leadUpdate ,200);
         
         
         }
}

 

  • May 20, 2013
  • Like
  • 0

Hi there,

 

I'm new to SF and have never used Apex, but it looks if this is where I have to end up. I'm trying to create my organization's implementation of SF and have reached a dead end. I would prefer to have a simple fix without spending many days learning Apex, so I would really super appreciate it if someone could share what this trigger's code should look like.

 

I am trying to automatically populate a lookup field on a custom object, InteractionParticipant__c. When a user enters a contact into the contact lookup field (Contact__c) on this object, I would like the account lookup field (Account__c) to be updated with the contact's associated account. It seems like I can't do this through workflow rules. Happy to take suggestions as to other ways to do this as well.

 

Thanks so much!

  • January 23, 2013
  • Like
  • 0

Hi,

 

Any body know about how to integrate salesforce with survey monky

please send user gude or document.

 

 

Thank you

I am trying to create a visualforce page that will show what % of a sales reps total funnel is represented by a given opportunity. 

 

I have been working on the controller for this, but keep getting an error: 

Error: Compile Error: Return value must be of type: Decimal at line 14 column 9

 

public class OpportunityExt {

    private final Opportunity opp;
    
    public OpportunityExt(ApexPages.StandardController stdController) {
        this.opp = (Opportunity)stdController.getRecord();
    }

    public integer getOpenTasks() {
        return [SELECT count() FROM task WHERE whatid = :opp.id and IsClosed=false];
    } 
    
    public decimal getFunnel() {
        return [SELECT Sum(Amount) FROM opportunity WHERE ownerid = :opp.ownerid];
    }
}

 I have also tried Integer, but I was under the impression that currency fields were stored as decimal... 

 

Has anybody run into something like this before? 

I would like to make it required to have a "type" when someone clicks "new task" or "log a call" under the activity level.  I was told by Salesforce that since this is a standard field you can not make it required and you can't create custom fields under "activity".  So is there anyone that can somehow program this for me?  Thanks in advance!

  • September 07, 2012
  • Like
  • 0
I created a trigger that would look through a custom objects records that is related via a lookup to the case object. The validation does work and stops the case from being closed if training hasn't been completed or cancelled, while that said then the training status would be in Pending or Scheduled status.

Below is the trigger I'm using, the problem I need to solve is when the validation via the trigger below is triggered, the big nasty error message below this trigger code appears at the top of the case when I'd rather it just say, "Training has not been completed or cancelled"...  Any ideas?
 
trigger CaseCloseTrigger on Case (after update) {
    public class CaseCloseException extends Exception{}
 
    for(Training_Information__c customobj : [Select Id, Status__c From Training_Information__c Where Case__c in: Trigger.newMap.keySet() AND Case_Status__c = 'Completed']){
        if(customobj.Status__c == 'Pending' || customobj.Status__c == 'Scheduled'){
            throw new CaseCloseException('Training has not been completed.');
        }
    }
}



Error: Invalid Data. Review all error messages below to correct your data. Apex trigger CaseCloseTrigger caused an unexpected exception, contact your administrator: CaseCloseTrigger: execution of AfterUpdate caused by: CaseCloseTrigger.CaseCloseException: Training has not been completed.: Trigger.CaseCloseTrigger: line 8, column 1

Hi,

 

I've got an issue that I've yet to find a good solution.  It seems that others have solved it for their needs, but for me, it continues to plague me.  Here's the issue:

 

I have a VF page that prints out to PDF.  The VF Page is using a standard controller for the Opportunity table.  In my Opportunity table, I have a CUSTOM field (Customer_Contact__c) that's a lookup to a Contact record. Below is my VF code:

 

<apex:page standardController="Opportunity" recordSetVar="SelectedOpps" renderAs="pdf">
    <apex:variable var="number" value="{!0}"/>
    <apex:repeat value="{!selected}" var="SelectedOpp">
        <apex:variable var="number" value="{!number + 1}"/>
        <Scout9:StandardSheetLabel LabelNumber="{!number}" ProductName="5164" Brand="Avery" ShowBorder="false">
            <br></br><br></br><br></br><br></br><br></br><br></br><br></br>
            <table width="100%" height="100%" cellpadding="2">
                <tr>
                    <td><apex:outputText value="{!SelectedOpp.Customer_Contact__c}"/></td>
                </tr>
                <tr>
                    <td><apex:outputText value="{!SelectedOpp.Account.Name}"></apex:outputtext></td>
                </tr>
                <tr>
                    <td><apex:outputText escape="false" value="{!SelectedOpp.Customer_Mailing_Address__c}"></apex:outputtext></td>
                </tr>
            </table>
        </Scout9:StandardSheetLabel>
    </apex:repeat>
</apex:page>

 

The code above will display the contact's ID value, which is great and all, but I need the contact's name, not the ID.  Changing the above line to:

 

<td><apex:outputText value="{!SelectedOpp.Customer_Contact__c.Name}"/></td>

 

Only leads to the following error message:

 

"Error: Unknown property String.Name."

 

I've tried changing outputText to outputField, but that yields the name as a link, but I don't want a link. I just need to get the name value.  Does anyone know what's going on?  It would seem that the ".Name" notation only works for standard fields.

 

Help! ~ Thanks in Advance!

  • September 04, 2012
  • Like
  • 0

Hi guys I am trying to counting total rows in opportunity object using count() but its giving me an errors says  Compile Error: Illegal assignment from LIST<SObject> to Integer at line 95 column 11

 


let me show you what I am doing.

 

String soql = 'select count() from lead where Ownerid=:18digit_id and IsConverted=false';

 

Integer leadCount = Database.query(soql);  // Getting error here.

 

Any One had a problem before?

 

Thanks guys

 

Hi,

 

when running a test class in a patch org, i get errors due to the fact that i haven't set up an approval process definition. Since this is a patch org, i don't want to have to set up a process definition every time we open up a new patch org.

 

Any suggestions how to deal with this? I know we can't create a process definition in apex, that would have been simple..

 

Thx in advance!

Marco

 

  • August 22, 2012
  • Like
  • 0

I have VP/Apex Class that updates a record.When the page first loads it grabs the first record that meets a particular criteria.

 

Here is the code that runs when the record is submitted. What should happen is upon submission it should update a checkbox (and some other fields) and then set the PageReference to the same page and then reload that page.

 

One of the criteria for the selected record is that the Resume Review Completed field should be false therefore after a submission the current record should drop out. (which it does if I reload manually)

 

 

public pageReference doSubmitReview()
	{
        
        if (ResumeStatus != '' && ResumeStatus != null)
        {
        	cRC.Status__c = ResumeStatus;	
        }
        cRC.Resume_Review_Completed__c = true;
        Update cRC;

        nextlink = '/apex/TBR_Resume_Review';
        PageReference nextPage = new PageReference(nextlink);
        return nextPage;
			
	}

What I notice is the bottom part (not url) seems to reload, it almost appears as if its reloading cache of the prior page load. If I manually choose to click reload I get the results I expect.

 

Is there something else I should be doing to force a proper reload.

 

 

This may be a simple yes or no question. I'm trying to update a field based on a string. Example.

 

//Create contact to update and set string to the email field.

Contact TestContact = new Contact(Id = '003121212121212');

string conField = 'Email';

 

//Update contact email field.

testContact.conField = 'test@email.com';

update testContact;

 

What I'm trying to do is access a field name for an object based on a string. Is this possible at all in APEX?

 

Below is a simple test I have written, all it suppose to do is a select an account and upsert it. No matter what I try I cannot get the select statement to any return values. I've opened it up to accept anything but it seems no matter what I do and not matter what object I try no records are returned. 

 

I'm at a loss to why no values are returned when I am certain there are many rows. I am logged in as Platform sys admin when running these tests. I'm using force.com development environment. 

 

Is there a limit or something in SF I'm running into or ??

 

Help me.. Will Robinson

 

public class ShareTriggerTestMethod 
  {
    static testMethod void MySharingTest()
      {    
         
        //get a acount to update

        account acc = [select Id, name, comment__c from account limit 1];

     

         acc.comment__c = 'test';
         
         // upsert data causing the trigger to fire.
         Test.startTest();
           upsert acc;
         Test.stopTest();
      }
  }

  • August 08, 2012
  • Like
  • 0
Is it just me or is this Dev Console useless?

1. Randomly just stops updating
2. most recent logs do not appears at the top (Unless you manually sort
3. On opening, get error that log not found (just annoying)
4. Cannot clear logs. If you try to all sorting is lost.
5. On resume, sorting is lost. logs may or may not start reappearing.
6. Filter by key word does not find results even though the word is in the file.
7. Cannot clear test logs

It is really become a useless tool at ths point

So is there any way to use HTTPmock methods when writing test methods for a Batch Class?

 

I have put the test.setMock inside the test.startTest

 

There is NO DML going on either in the batch, the setup for the test or the mock interface....

 

I always get the you have uncommitted work pending when the callout is initiated by the execute method of the batch class....

 

 

  • September 21, 2013
  • Like
  • 0

Ok. In the first class, I am following the usual pattern for a getter however the returned value is ALWAYS NULL. If I debug in the last line of the if statement the oppQualifiedDate is set, but dubugging right before the return it is null:

 

    public map<ID,Date> oppQualifiedDate{
    
        get{
            //system.debug(logginglevel.error,opps);        
            if(oppQualifiedDate == null){
                //For some reason if I do not do it this way, oppQualified date is always returned as null
                Map<ID,Date> oppQualifiedDate = New Map<ID,Date>();

                for(OpportunityHistory oh : [Select OpportunityID, StageName, CreatedDate, CloseDate 
                                            From OpportunityHistory 
                                            Where OpportunityID IN :opps.keySet()
                                            ORDER BY OpportunityID, StageName ASC]){
                
                    if(oppQualifiedDate.containsKey(oh.OpportunityID))
                        continue;
                    
                    if(oh.StageName.left(1).isNumeric()){
                        if(integer.valueOf(oh.StageName.left(1)) > 1)
                            oppQualifiedDate.put(oh.OpportunityID,oh.createdDate.date());
                            
                    }                            

                }
//This has the appropriate values set               
system.debug(logginglevel.error,oppQualifiedDate);                                                                                               
            }
//Here it is now null            
system.debug(logginglevel.error,oppQualifiedDate);                                                                                   
            return oppQualifiedDate;
        
        }
        
        private set;
    
    
    
    }

 

Now, if I use a tmp variable to set the map and then set oppQualifiedDate to that variable the return value is correct....

 

    public map<ID,Date> oppQualifiedDate{
    
        get{
            //system.debug(logginglevel.error,opps);        
            if(oppQualifiedDate == null){
                //For some reason if I do not do it this way, oppQualified date is always returned as null
                Map<ID,Date> tmp = New Map<ID,Date>();

                for(OpportunityHistory oh : [Select OpportunityID, StageName, CreatedDate, CloseDate 
                                            From OpportunityHistory 
                                            Where OpportunityID IN :opps.keySet()
                                            ORDER BY OpportunityID, StageName ASC]){
                
                    if(tmp.containsKey(oh.OpportunityID))
                        continue;
                    
                    if(oh.StageName.left(1).isNumeric()){
                        if(integer.valueOf(oh.StageName.left(1)) > 1)
                            tmp.put(oh.OpportunityID,oh.createdDate.date());
                            
                    }                            

                }
                oppQualifiedDate = tmp;
system.debug(logginglevel.error,oppQualifiedDate);                                                                                               
            }
            system.debug(logginglevel.error,oppQualifiedDate);                                                                                   
            return oppQualifiedDate;
        
        }
        
        private set;
    
    
    
    }

 

It this normal? Why would I have to set the oppQualifiedDate to a temporary variable for it to properly be returned?

 

 

I have a checkbox on a VF page that when checked sets a controller value to TRUE.

 

It rerenders and outputpanel with an apex:inputfield inside that displays a value say 12345.

 

The action on the checkbox causes the controller to set the value of the field in the controller (the same field that in in the inputfield) to say 4567.

 

Saving the record at this point save the correct value 4567 in the record.

 

HOWEVER, if I uncheck the checkbox, the outputpanel is again shown (rendered is based on the controller variable for the checkbox), BUT the value in the inputfield is the original value. 

 

If I save at this point the value saved is 12345.

 

Example code would be

 

 

public class simpletest{

public account a {get;set;}
public boolean isselected {get;set;}

    public simpletest(apexpages.standardcontroller con){
        a = (account)con.getRecord();
        a.BillingPostalCode = '12345';
    }


    public void changevalue(){
    
        if(isselected)
            a.billingpostalcode = '99999';
    
    }

}

 

<apex:page standardcontroller="Account" extensions="simpletest">
<apex:form >
  <apex:inputCheckbox value="{!isselected}" >
  <apex:actionSupport event="onchange" action="{!changeValue}" rerender="opp"/>
</apex:inputCheckBox>

<apex:outputPanel id="opp" layout="block">
<apex:pageblock id="thepgblk" rendered="{!!isSelected}">
<apex:pageblockSection >
<apex:inputfield value="{!a.billingPostalCode}"/>
</apex:pageblockSection>
</apex:pageblock>
</apex:outputPanel>
<apex:commandButton value="Save" action="{!save}" rerender="nothing"/>
</apex:form>
</apex:page>

 

 

 

anyone have any ideas as to why when the outputpanel is shown again it is not updated with the current value but infact reset the value to what was originally there?

 

Steps to reproduce:

 

1. Open VF page with know account id as ID parameter

2. Check the check box

   - The outputpanel dissapears and the controller sets the zip to 99999

3. Click save

4. Note on the account the billing zip is 99999

 

Not open the page again

 

1. Check the check box (we proved that is set the zip to 9999 above

2. Now uncheck the checkbox

3. NOTE the input field has 12345 in it

4. Click save

5. Note the Zip is now 12345

   - No where in the controller did it set the value back.

  - It appears when the outputpanel is rendered again only the setters fire and the getters do not. (Is this expected)

Neat little trick in case you need it:

 

1. Create the class for the Inbound Email Handler:

 

 

global class myHandler implements Messaging.InboundEmailHandler {
      global Messaging.InboundEmailResult handleInboundEmail(Messaging.InboundEmail email, Messaging.InboundEnvelope envelope) {
          Messaging.InboundEmailResult result = new Messaging.InboundEmailresult();
          
          
          if(email.htmlBody.contains('We have received the following request to add this'))
              sendVerificationEmail(email, 'YOUR EMAIL ADDRESS HERE');
          
          
          return result;
      }

    
    private void sendVerificationEmail(Messaging.InboundEmail email, String toAddress){
    
    
        Messaging.reserveSingleEmailCapacity(1);
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        String[] toAddresses = new String[] {toAddress};

        
        mail.setToAddresses(toAddresses);
        mail.setSenderDisplayName('WHATEVER YOU WANT HERE');

        mail.setSubject('WHATEVER YOU WANT HERE');
        mail.setPlainTextBody(email.plainTextBody);
        mail.setHtmlBody(email.htmlBody);
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });

    
    
    }

  }

 

2. Create the email service

3. Copy the email service address

4. Create a new Org Default Email Addres using the address from the email service

5. It will send the confirmation email to the email handler which will forward it on to the email address you specified so you can click the link to verify

6. Now you can use the address in workflows.

 

Why would you want to do this:

 

** So you can send email notifications to addresses using workflow so you do not have issues with gov limits. The email can be replied to and then you can proccess the reply (Like in a custom approval process).

 

 

 

After I insert a record I would like to have access to the value of an AutoNumber field.

 

I see to recall a way to load / get a record based on an sObject but cannot locate it (Or I am crazy).

 

I would like to not have to do an SOQL statement if at all possible. One would think there would be a way to do it. All attemps to reference the field after inserting the sObject return null since it was not part of the sObject statement I inserted and since I cannot set the value, I cannot add the field in the statement.

I have tried everything:

 

Developer Console filters set to Error for all except Debug for Profiling

System monitoring everything set to none except Profiling

Apex Class, override and everything set to none excep profiling.

 

 

I still get max log sixed reached and never get to any profiling information. Here is a sample:

 

25.0 APEX_PROFILING,FINE
22:45:46.032 (32459000)|EXECUTION_STARTED
22:45:46.032 (32499000)|CODE_UNIT_STARTED|[EXTERNAL]|066Z00000004uBF|VF: /apex/pv_chem_bgreport_test
22:45:46.587 (587183000)|CODE_UNIT_STARTED|[EXTERNAL]|01pF0000002f6RI|PV_CHEM_BGReportController <init>
22:45:50.894 (4894671000)|CODE_UNIT_FINISHED|PV_CHEM_BGReportController <init>
22:45:50.894 (4894751000)|CODE_UNIT_STARTED|[EXTERNAL]|01pF0000002f6RI|PV_CHEM_BGReportController get(sParticipants)
22:45:50.894 (4894778000)|CODE_UNIT_STARTED|[EXTERNAL]|01pF0000002f6RI|sParticipants
22:45:50.894 (4894794000)|CODE_UNIT_FINISHED|sParticipants

 I thought all of this would be gone. Is that not the case? If so I cannot get around it as it displays ALL the values passed into the methods and there is a lot of data there.

 

 

Here is an example of one line with all the data being passed in showing

 

22:45:51.052 (5052874000)|CODE_UNIT_STARTED|[EXTERNAL]|PV_DemingRegAnalysisController set(objpv,PVReportObjects_Copy:[PTSampleType={c=venipuncture, i=skin puncture}, PVID=a2CF00000004zGqMAI, Panel=null, allPVData=(pvData&colon;[Name=PTINR, Panel=PT, SampleID=19, Units=INR, isOutlier=null, x1=2.7, x2=2.7, y1=2.2, y2=2], pvData&colon;[Name=PTINR, Panel=PT, SampleID=17, Units=INR, isOutlier=null, x1=1.2, x2=1.2, y1=1.1, y2=1.1], pvData&colon;[Name=PTINR, Panel=PT, SampleID=18, Units=INR, isOutlier=null, x1=3.7, x2=3.7, y1=2.8, y2=3.1], pvData&colon;[Name=PTINR, Panel=PT, SampleID=15, Units=INR, isOutlier=null, x1=1.7, x2=1.7, y1=1.5, y2=1.5], pvData&colon;[Name=PTINR, Panel=PT, SampleID=16, Units=INR, isOutlier=null, x1=1.9, x2=1.9, y1=2.1, y2=2], pvData&colon;[Name=PTINR, Panel=PT, SampleID=13, Units=INR, isOutlier=null, x1=1.4, x2=1.4, y1=1.5, y2=1.6], pvData&colon;[Name=PTINR, Panel=PT, SampleID=14, Units=INR, isOutlier=null, x1=1.5, x2=1.5, y1=1.4, y2=1.5], pvData&colon;[Name=PTINR, Panel=PT, SampleID=11, Units=INR, isOutlier=null, x1=2.1, x2=2.1, y1=2, y2=2.2], pvData&colon;[Name=PTINR, Panel=PT, SampleID=12, Units=INR, isOutlier=null, x1=2.9, x2=2.9, y1=3, y2=2.6], pvData&colon;[Name=PTINR, Panel=PT, SampleID=21, Units=INR, isOutlier=null, x1=3.1, x2=3.1, y1=2.4, y2=2.1], ...), anaStatPrecision={actwbt={CV=2, Diff=2, General=0, Intercept=1, Mean=1, R=2, Range=0, SD=2, Slope=1, Sxx=2, ...}, angap={CV=2, Diff=2, 

 This continues on and wraps for another 100 or so lines all for one line in the debug log where the filter is set to none.

 

Anyone have any ideas?

Can a managed package access custom objects in the destination org?

 

More specifically:

 

Suppose:

 

1. I have an object in the managed package and the Name field is the API name of a custom object in the destination org entered by the destination org, and a fldname field is the field name of the object

2. Can a trigger that is part of my managed package access the value of the field in #1 in any way like a describeglobal call or something using the values entered by the destination org?

 

 

 

I need to Open a new window after saving an object from the VF Page.

 

1. Command button calls the method to create the record

2. oncomplete I need to open a popup window.

 

I tried everything I can think of but for some reason it seems you cannot open a new window after the ajax call...

 

put thin in your command button and no window will open:

 

oncomplete="window.open('http://www.google.com'); return false;"

 

any ideas on how to open a new window after the controller method is finished/

Greetings,

 

I have an outPanel that is being hidden on load. On the clik of a button it loads the records related to the fields.

 

On Page load, the  outPutPanel visible, then hidden.

On button click, the outPanel is shown 

The fields have the correct values.

 

Upon changing the values and clicking a command button that calls a custom save method, system debug shows that the setter method for the record related to the field in theoutPutPanel is never called and the values of the record is as they were before editing.

 

It there an issue with breaking the link to the controller setter method when an inputField is hidden?

 

How can I get the controller to set the value of an inputField that was shown, hidden, and shown again?

If Apex runs in system mode, then why does getContentasPDF() not work if the user does not have access to the VF page.

 

I want to control when a page is generated via code. Because of the above, In order to do so I have to give the users access to the VF page and thus they can generate it anytime as long as they know the pagename and how to construct the url.....

 

 

If we are not using the seealldata = true and thus have to create ALL records then why does the validation rules that fire during test methods see all data?

 

We have a few validation rule that check to ensure a field is unique. One of them being email.

 

In test methods I use a lot of test@tes.com for email addresses and sometimes users will create records with test@test.com. When the test methods are run after that they fail the validation rule.

 

For now, I will have to create a more uniwue email that users are not likely to use.

 

Anyone else observed this?

 

 

Greetings,

 

I have a page where the readonly attribute is set to true. This is done to overcome the limit of 50,000 records in an aggregate query..

 

How do I perform a unit test using this attribute? I have tried setting the application mode to read only to no avail. The test method still fails for > 50K query rows. The page works fine when viewing but I cannot get the test method to pass.

 

What am I missing.

 

Here is the unit test:

 

@isTest
private class TestRRPage {

    static testMethod void myUnitTest() {
                            
        PageReference pageRef2 = new PageReference('/apex/RRSpage');
        Test.setCurrentPage(pageRef2);
        test.setReadOnlyApplicationMode(true);        
        RRStatusController r = new RRStatusController();
        
        test.startTest();
        r.AssignRefferals();
        test.stopTest();
        
        r.ISERROR = False;
        r.ErrorMsg ='No Message';
        system.debug('\n\n RRS = '+r.RRS);
    }
}

 

Also,

 

The docs state that controller methods can be annotated as @readonly but the error occurs that it must be scheduleable or a webservice method. How do you mark a controller method as readOnly? Do I have to make it a webservice method?

 

I have configured Live agent for the org, created skills, assigned the System Admin Profile to all the skills. Created a button and deployment.

 

I create a Sites VF page using the code from the deployment guide.

 

No matter what I do, the Offline element always shows. I cannot get the online element to show despite two live agents being logged into the live agent console and the status as available.

 

Anyone have any ideas? btw, this is in sandbox.

 

here is the VF code, very basic, right now just trying to get the ONLINE element to display.

 

<apex:page >
  <h1>Welcome</h1>
   Thank you for contacting customer support
   <!-- START Button code -->
      <a id="liveagent_button_online_573W00000004CAL" href="javascript&colon;//Chat" style="display: none;" onclick="liveagent.startChat('573W00000004CAL')">ONLINE</a><div id="liveagent_button_offline_573W00000004CAL" style="display: none;">OFFLINE</div><script type="text/javascript">
if (!window._laq) { window._laq = []; }
window._laq.push(function(){liveagent.showWhenOnline('573W00000004CAL', document.getElementById('liveagent_button_online_573W00000004CAL'));
liveagent.showWhenOffline('573W00000004CAL', document.getElementById('liveagent_button_offline_573W00000004CAL'));
});</script>

   <!-- END Button code -->
   
   <apex:outputtext value="TEST TEXT"/>
   
   <!-- Deployment code -->
<script type='text/javascript' src='https://c.la2cs.salesforceliveagent.com/content/g/deployment.js'></script>
<script type='text/javascript'>
liveagent.init('https://d.la2cs.salesforceliveagent.com/chat', '572W00000004C9X', '00DW0000000IRe9');
</script>
</apex:page>

 

Is there a way to instantiate a List when the type is not known?

 

I have the type of the field but need to create a list of that specific type, since the type may change I would like to be able to declare the List type dynamically.

 

The reason is the List will be used in a query and I cannot simply use the List<Object> in the query.....

 

1. I have the Schema.DisplayType of the field

2. I need to create a list of that displaytype and I do not wish to hardcode the type

 

If I use the IN: Operation in the SOQL query it errors when using a list of type Object.

If I try to convert the field to string using string.valueOf then the query errors when the field I am comparing is not a string.

 

Anyone have any ideas? 

 

btw, it is assumed that the field I am comparing in the query before the IN is the same type as the field in the list that I am binding to

I have a page block section that is not rendered on initial page load. It is using a sObject property on a custom controller

 

i.e. 

 

public Account a {get;set;}

 

If I render the section on load, any values entered will be saved when the user clicks the command button that calls my save method and the fields are populated.

 

If the section is not rendered on page load, all values are null regardless of what the user enters when I render the section.

 

Anyone have any Ideas? I know this is probably basic and I am just missing something here.

I tried the suggestion in this thread:

 

http://boards.developerforce.com/t5/Visualforce-Development/open-new-window-in-remoteAction-response/m-p/372345#M44231

 

and still no window opens up.

 

I have tried everything I can think of and it just will not open a new window.

 

Here is my current code:

 

function processAppt(scannedID, numGuests){
    Visualforce.remoting.Manager.invokeAction(
        '{!$RemoteAction.APPT_AppointmentCheckInController.createAppt}', 
        scannedID, numGuests, 
        function(result, event){
            if (event.status) {
                    window.open(/apex/badge_temp?id=' + result);
 
            } else if (event.type === 'exception') {

            } else {
                
            }

        }, 
        {escape: false}
    );

    rerenderMsgs();

}

 Anyone have anoy other ideas?

 

 

I have a requirement to create a VF page that will print to a badge. The printable area is 2.5in x 3.5in

 

I have tried

 

@page {
size: 2.5in 3.5in landscape;
}

 

to no avail in my css.

 

Does anyone know if this can be accomplished? the paper is a custom thermal label not avery

Is there a way to post an XML to salesforce using just a Username and password in the XML? 

 

Sceniero:

 

An external system can send an outbound XML to a designated URL. The XML can contain elements for Username and password. I need for it to goto a salesforce instance and be processed.

 

There is no other ability to interact using oauth, saml, etc. 

 

I could construct the URL to loginto salesforce using the un and pw parameters I believe, but if so where would the xml be parsed.

 

I am thinking it is not possible. Anyone have ideas?

Greetings,

 

I have implemented partial page refreshing based on a value in a select list. It works fin for existing records, however, when creating a new record the section does not show or hide...

 

i am using a standard controller for most of the work with a little bit of code from an extentions that has nothing to do with the selectList in question.

 

Anyone have ideas as to why it works with existing records and not for new records? it seems the update to the picklist 

 

here is the relevan portion of the vf code

 

<apex:actionRegion >
		<apex:pageblockSection id="vid_details" title="Video Details">
			
			<apex:inputField value="{!Video_Content__c.Name}" required="true"/>
			
			
			<apex:inputField value="{!Video_Content__c.Link_Type__c}" label="Link Type" id="lnktype">
				<apex:actionSupport event="onchange" rerender="wistiaplayeroptions" oncomplete="toggleOptions();"/>
			</apex:inputField>
	   		
			<!-- <apex:pageBlockSectionItem/>
	   		<apex:inputField value="{!Video_Content__c.Location__c}"/> -->

	   		<apex:inputField value="{!Video_Content__c.Video_Height__c}"/>
	   		<apex:inputField value="{!Video_Content__c.Video_Width__c}"/>	
			
		</apex:pageblockSection>
	</apex:actionRegion> 

<apex:outputPanel id="wistiaplayeroptions">

		<apex:pageBlockSection id="wistia_player_options_section" title="Wistia Player Options" rendered="{!Video_Content__c.Link_Type__c == 'Wistia'}">
			<apex:inputField value="{!Video_Content__c.Big_Play_Button__c}"/>
			<apex:inputField value="{!Video_Content__c.Controls_Visible_on_Load__c}"/>
			<apex:inputField value="{!Video_Content__c.Small_Play_Button__c}"/>
			<apex:inputField value="{!Video_Content__c.Autoplay__c}"/>
			<apex:inputField value="{!Video_Content__c.Playbar__c}"/>
			<apex:inputField value="{!Video_Content__c.Fullscreen_Button__c}"/>
			<apex:inputField value="{!Video_Content__c.Volume_Control__c}"/>
			<apex:inputField value="{!Video_Content__c.End_Behavior__c}"/>
		</apex:pageBlockSection>

	</apex:outputPanel>

 

 

 

  • September 28, 2012
  • Like
  • 0

Neat little trick in case you need it:

 

1. Create the class for the Inbound Email Handler:

 

 

global class myHandler implements Messaging.InboundEmailHandler {
      global Messaging.InboundEmailResult handleInboundEmail(Messaging.InboundEmail email, Messaging.InboundEnvelope envelope) {
          Messaging.InboundEmailResult result = new Messaging.InboundEmailresult();
          
          
          if(email.htmlBody.contains('We have received the following request to add this'))
              sendVerificationEmail(email, 'YOUR EMAIL ADDRESS HERE');
          
          
          return result;
      }

    
    private void sendVerificationEmail(Messaging.InboundEmail email, String toAddress){
    
    
        Messaging.reserveSingleEmailCapacity(1);
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        String[] toAddresses = new String[] {toAddress};

        
        mail.setToAddresses(toAddresses);
        mail.setSenderDisplayName('WHATEVER YOU WANT HERE');

        mail.setSubject('WHATEVER YOU WANT HERE');
        mail.setPlainTextBody(email.plainTextBody);
        mail.setHtmlBody(email.htmlBody);
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });

    
    
    }

  }

 

2. Create the email service

3. Copy the email service address

4. Create a new Org Default Email Addres using the address from the email service

5. It will send the confirmation email to the email handler which will forward it on to the email address you specified so you can click the link to verify

6. Now you can use the address in workflows.

 

Why would you want to do this:

 

** So you can send email notifications to addresses using workflow so you do not have issues with gov limits. The email can be replied to and then you can proccess the reply (Like in a custom approval process).

 

 

 

Simply updating the event does not send out the invites. Is there a way via apex to send updates to attendees when an event is updated?

I see this question come up often and after having to fight with it again today, I thought I would post a quick quick with tips and tricks:

 

 

What you think should work

 

<apex:commandButton action="{!someAtion}" value="Click Me">
     <apex:param assignTo="{!conVariable}" name="con" id="con" value="123"/>
</apex:commandButton>

 Well, let me tell you, this DOES NOT work.

 

  - Why - A little bug with the command button and param. Commandlink works, but the command button requires something more to get it to set the value of the controller variable.

 

How to fix it

 

 1. Create a hidden output panel on the page, and simply rerender it. This will cause the command button to set the controller vairable as expected.

 

<apex:outputPanel id="hidden" rendered="false"/>

<apex:commandButton action="{!someAtion}" value="Click Me" reRender="hidden">
     <apex:param assignTo="{!conVariable}" name="con" id="con" value="123"/>
</apex:commandButton>

 

Calling Javascript with the button and setting the variable, what you think would work

 

<apex:commandButton onclick="someFunction();" value="Click Me" rerender="hidden">
     <apex:param assignTo="{!conVariable}" name="con" id="con" value="123" />
</apex:commandButton>

 

     Well this does not work either - You need BOTH the action and rerender to be present. Well shucks, I do not want to call the controller, I want to call a jave method....

 

How to make it work

 

1. Add a method to your extenstion / controller

 

public void doNothing(){

   //Do absolutely nothing

}

 2. Modify the button as follows:

 

<apex:commandButton action="{!doNothing}" onclick="someFunction();" value="Click Me" rerender="hidden">
     <apex:param assignTo="{!conVariable}" name="con" id="con" value="123"/>
</apex:commandButton>

 

Bam. The controller variable is set as expected.

 

Why would you use this? Well here was my flow:

 

1. On click of a button I needed to set the value of a controller variable which will be used in a query

2. Before the actual method in the controller ran, I needed to run some java to manipulate the DOM

3. After the method ran, I needed to check the results

 

1: Button -> doNothing -> call Java Function

2. Java Function DOM Stuff -> ActionFunction

3. ActionFunction -> Run Controller method -> onComplete -> Java Function passin in result variable from controller

4. Java Function More DOM Manipulation or Action Function stuff based on result.

 

Hope this helps someone


Hi,
I found the same question that was posted back in 2007; however, there was no answer to the question so I decided to ask again.

Is there a way to hide or show custom button on a standard page based on a condition.  In my case I want the button only to show if a system administrator is logged in, all other users should not see this button as it would be used to do some adminstrative work  such as call a VF page/controller.


How to call the controller to VF page with parameter?I have two Visual force pages, and two controllers

VF Page:DEMO
<apex:page standardController="Account" extensions="NewAndExistingController" id="demoId" >
    <apex:pageBlock >
     <br> </br>
<apex:outputField value="{!a.Id}"/> <br> </br>
      </apex:pageBlock>
       <apex:form >
     
          <apex:pageBlock >
               <apex:commandButton value="Call visualforce Page" action="{!click}"/>
          </apex:pageBlock>
     </apex:form>
    
  
</apex:page>

VF page:XYZ

<apex:page standardController="Order__c" extensions="MyOrderPadController" >
    <apex:detail />
        <apex:form >
    
        <apex:pageBlock >
       
            <apex:pageBlockButtons >
                <apex:commandButton action="{!save}" value="Save"/>
                <apex:commandButton action="{!edit}" value="Edit"/>
                <apex:commandButton action="{!reset}" value="Cancel" />
            </apex:pageBlockButtons>
           
           
            <apex:pageBlockSection columns="2" title="Order Pad">
            <apex:inputField value="{!Order__c.Order_Description__c}"  />
                    <apex:inputField value="{!Order__c.Creat_Date__c}"  />
                    <apex:inputField value="{!Order__c.Closed_Date__c}"  />
                     <apex:inputField value="{!Order__c.Conformation__c}"  /> 
                  
                     
            </apex:pageBlockSection>
        </apex:pageBlock>
    </apex:form>
   
</apex:page>

Controller:NewAndExistingController

public class NewAndExistingController {Public Account a{get;set;}public String accId;    public NewAndExistingController(ApexPages.StandardController controller) {    try{    a =[select id,name,accountnumber,annualrevenue from account where id=:controller.getId()];    MyOrderPadController.staticVar =a.Id;    }catch(exception e){}    }         public PageReference click() {        PageReference openvfpage = New Pagereference('/apex'+'/XYZ);     openvfpage.setRedirect(false);  return openvfpage ;        }    public NewAndExistingController() {    }   }

Controller: MyOrderPadController
public class MyOrderPadController {    public Order__c order{ get; private set; }        public static  String staticVar;       public String instanceVar {get; set;}           NewAndExistingController  test = new NewAndExistingController ();           public MyOrderPadController ()       {            instanceVar = staticVar;       }    public MyOrderPadController(ApexPages.StandardController sc) {        order = (Order__c)sc.getRecord();       }public PageReference edit()      {            return null;             }     public PageReference reset()     {          PageReference newpage = new PageReference(System.currentPageReference().getURL());          newpage.setRedirect(true);          return newpage;    }     public PageReference save()      {          TRY          {                             order.Name = 'Demo Test Order '+order.Order_Description__c;               order.Order_Description__c =order.Order_Description__c+':====>'+staticVar ;                order.Account__c = '0019000000NAr7bAAD';//for testing only                            IF(order.Conformation__c == TRUE){                                              INSERT order;                     PageReference newpage = new PageReference(System.currentPageReference().getURL());                    newpage.setRedirect(true);                    return newpage;                         }                                                            }                       catch(System.DMLException e)           {            ApexPages.addMessages(e);            SYSTEM.DEBUG('ERROR ORDER PAD CONTROLLER :'+e);            return null;          }        //  After Save, navigate to the default view page:        //return (new ApexPages.StandardController(order)).view();        return null;             }   }

The  "DEMO" VF page added to Account under the one section ,As of  now I am getting  Account Id in the controller "NewAndExistingController" .This controller again called to the VF page "XYZ" .How to access this Account id in controller "MyOrderPadController".

I want get account id in the "MyOrderPadController" Any idea please share with me.

Regards,
Ramesh

I am trying to get build a trigger when the custom object sitevist has the record type daily select and the field baseboard_stairway__C is false then create a care.  i saved without any errors but then i save the new sitevisit i get the following error

 

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

 

Here is my code:  please show me what i am missing

 

 

trigger SV_Cases on SiteVisit__c (after insert) {
 List<Case>cases=new List<Case>();
  Id rtId = [select Id,name from RecordType where name='Label of the record type' and SObjectType='sitevisit' limit 1].Id;  
    for(sitevisit__C b:Trigger.new)
        {
             if(rtID=='012a0000001NYfi'){
     if(b.baseboard_stairway__c == 'False' )
    {
    Case newCase=new Case(subject='Test',Status='New',Origin='Web');
    insert newCase; 

Hi

 

I am a new to apex so could somebody help me with this???

 

In my custom settings I have Object called MyPersonalSettings__c in my code I have something like:

 

settings = MyPersonalSettings__c.getValues('mypersonalsettings')

 

But it is possible to replace 'mypersonalsettings' with somethng like a method: for example getValues(method) where method could have something like that

if (condition == true)

  set mypersonalsettings

else if (condition  == false)

  set yoursettings

else ..

 

Could somebody provide my with some example, I will be very appreciate for that 

 

Thank

 

 

I have a single Map that works as  custom object cache for all organization.


I can't use custom settings because this is a legacy system and all data is stored in a custom object.
I tried to declare the Map as static but all users rebuild the object in each request.

Any suggestions?

  • November 28, 2013
  • Like
  • 0

I have the following class:

 

    Public Class Ahrec
    {
        Date ActivityDate{get; set;}
        String Client{get; set;}
        String Subject {get; set;}
        String Descrip  {get; set;}
        String Status {get; set;}
        Boolean isClosed {get; set;}
        Integer Ctr {get; set;}
        Id AccountId {get; set;}
        Id TaskId {get; set;}
    }

    I then create a list called lstAhrecs of this classs

   

    List<Ahrec> lstAhrecs = new List<Ahrec>()

 

   My class list then gets populated from a SOQL query.

 

   What I want to do now is SORT the class list by ActivityDate DESCENDING.

 

   Can anyone show me code on how to do this?

   Thanks so much in advance!

 

 

 

and load the list from a SOQL query...

 

   What I would now like to do is SORT the list by ActivityDate in a descending order.

 

   List<Ahrec> mylist

 

 

Hello Helpers

 

 

I have a VF page  with a command  button (among others)

 

<apex:commandButton action="{!MycontrolerFunction}"  value="{!someValue}"/>

 

when the MyControllerFuntion is finished I want to redirect  to a new page

 

For this I am using:

 

PageReference pageRef = new PageReference('/apex/MySecondPage');
pageRef.setRedirect(true);
return pageRef;

 

 

This open the new VF page  on the same  tab overwriting the initial page

 

What I want to achieve  is to  open the new VF page on a new  tab

 

 

Is it possible

 

Thanks in advance 

csbaa

  • November 22, 2013
  • Like
  • 0

Hello,

 

In my test method it looks like there is no pricebook record I can use.

The following code returns the value 0 while I have 4 Pricebook records in my sandbox.

 

System.debug('There is '+[SELECT COUNT() FROM Pricebook2]+ ' Pricebook(s)');

 

 

Do I have to recreate all records in the test method in order to use them?

I'm running into a bulk update issue on the trigger below. I thought that I properly structured the apex for bulkification but apparently I didn't and I'm stuck. I'd really appreciate some help. Thanks.

 

trigger UpdateAgentCaseCommissionOnCaseUpdate on Insurance_Case__c (after update) {

  Map<Id, Insurance_Case__c> cases = new Map<Id, Insurance_Case__c>();
  Map<Id, Insurance_Case__c> casesstatus = new Map<Id, Insurance_Case__c>();
  Agent_Cases_Commissions__c[] accToUpdate = new Agent_Cases_Commissions__c[0];
  
  for(Insurance_Case__c record: Trigger.new){
    Insurance_Case__c oldcase = Trigger.oldMap.get(record.Id);
    if(record.Status__c != oldcase.Status__c && record.Status__c != 'Submitted'){
      casesstatus.put(record.Id, record);
    } else {
      cases.put(record.Id, record);
    }
  }
  
  Agent_Cases_Commissions__c[] accstatus = [SELECT Id, Insurance_Case__c, Contract_Type__c FROM Agent_Cases_Commissions__c WHERE Insurance_Case__c IN :casesstatus.keyset() AND Contract_Type__c = 'Agent Contract'];
  Agent_Cases_Commissions__c[] accnostatus = [SELECT Id, Insurance_Case__c, Contract_Type__c FROM Agent_Cases_Commissions__c WHERE Insurance_Case__c IN :cases.keyset() AND Contract_Type__c = 'Agent Contract'];
  
  for(Agent_Cases_Commissions__c acc :accstatus){
    acc.Case_Status_Change__c = TRUE;
    accToUpdate.add(acc);
  }
  
  for(Agent_Cases_Commissions__c acc2 :accnostatus){
    accToUpdate.add(acc2);
  }
  
  if(!accToUpdate.isEmpty())
  update accToUpdate;

}

 

I see the below error message when trying to use a custom functionality. I dont see this error when I am logged in as System Admin, but I do see the below error when I am logged in as any other user. Does anyone know what the below error means.

 

"The configuration of your org has changed, please reload the page. Missing dependent object: Field: Organization.OrganizationType
An unexpected error has occurred. Your solution provider has been notified. "

I attempted SF Support twice to fix this issue, which has failed to resolve the issue.  So, I wanted to take it to the developer community to see if it is a problem with only us or if it's something larger.

 

We have a couple of classes that give the functionaly to change the users' passwords by calling System.setPassword(<UserId>, <Password);  These classes have been unchanged for many months and we have been deploying other code just fine.  This was the case until the Winter '14 update.  Ever since that update we have not been able to deploy *any* code due to those two classes erroring out with an Unexpected_Exception.  This happens even if we try to deploy an empty class.  If we comment out the lines (thus removing that functionality), the deployments are successful. 

One more oddity about this is that the test methods for these classed succeed if they are ran; it only fails during a deploy.

 

So, does anyone use this functionality/call?  Are they experiencing problems deploying?

  • October 31, 2013
  • Like
  • 0

hi

 

I have a trigger which will be fired under some condition.

It works perfect and fine if i just give insert.

If i also include update,I get error :

How can i get ride of this?

please help

System.AsyncException: Future method cannot be called from a future or batch method

Hi all,

I've got a Too many query rows problem in a class.

I've got a custom object, call Prodotti_promozioni_commerciali__c, from I want to create a custom dashboard. This object is a sort of "Bridge object" and has a relationship with Prodotto__c object, who has a Famiglia_dsh__c and a Set_Prod_dsh__c fields, and a relationship with account, who has a ACCOUNTCATEGORY_MI__c fields. It is correlated to another custom object (Promozione_commerciale__c) too. The idea is this: I select from a wizard a family, and I can see for every family the percentage of account related with a promotion (represented with Prodotti_promozioni_commerciali__c object) between total accounts . Every family has 3 or 4 sets correlated to it, and every account can have one between four category: A, B, C,D. The dashboard is composed by lines and columns, the lines represent the set of products for each family, the columns represent possible account category. I have also a datetime picker in order to specify the dates range in which the Prodotti_promozioni_commerciali__c must be shown, depending of Data_adesione__c field of Promozione_commerciale__c object. I have a Bonus picklist Yes/no/all too, if I select Yes, I should see only records with Bonus__c checkbox field = true, same thing if select No, while if I select all I should see both records.

In my code I make a for loop for each product set, like this: in this case I consider only A category, for B,C,D category code is similar.

 

for (string selectedSetProd: listasetProdotti) {

listapromcommA = new set<string>();
List<Prodotti_promozioni_commerciali__c> listaaccounttotA = new List<Prodotti_promozioni_commerciali__c>();
if(selectedBonus == 'all'){
listaaccounttotA = [select Promozione_commerciale__r.Referente__r.AccountId,
Promozione_commerciale__r.Referente__r.Account.ACCOUNTSTATUS_MI__c,
Promozione_commerciale__r.Referente__r.Account.ACCOUNTCATEGORY_MI__c,
Promozione_commerciale__r.Referente__r.Account.RecordType.DeveloperName,
Promozione_commerciale__r.Referente__r.Account.Form_Acc_Cat__c from
Prodotti_promozioni_commerciali__c where Promozione_commerciale__r.Referente__r.Account.Ownerid in:utentiriferimento
AND Promozione_commerciale__r.Referente__r.Account.ACCOUNTSTATUS_MI__c = 'Attivo'
AND Promozione_commerciale__r.Referente__r.Account.RecordType.DeveloperName = 'Ambulatorio'
AND Promozione_commerciale__r.Referente__r.Account.ACCOUNTCATEGORY_MI__c = 'A'
AND Promozione_commerciale__r.Referente__r.Account.ABILITATED_MI__c = true
AND Promozione_commerciale__r.Referente__r.Account.CHECKACCOUNT_MI__c = true
AND Prodotto__r.Famiglia_dsh__c =:selectedFamilyNew
AND Prodotto__r.Set_Prod_dsh__c =:selectedSetProd
AND Promozione_commerciale__r.Data_adesione__c >=: datainizio
AND Promozione_commerciale__r.Data_adesione__c <=: datafine
AND Promozione_commerciale__r.Stato__c = 'Approvata'
];

}
else
{
listaaccounttotA = [select Promozione_commerciale__r.Referente__r.AccountId,
Promozione_commerciale__r.Referente__r.Account.ACCOUNTSTATUS_MI__c,
Promozione_commerciale__r.Referente__r.Account.ACCOUNTCATEGORY_MI__c,
Promozione_commerciale__r.Referente__r.Account.RecordType.DeveloperName,
Promozione_commerciale__r.Referente__r.Account.Form_Acc_Cat__c from
Prodotti_promozioni_commerciali__c where Promozione_commerciale__r.Referente__r.Account.Ownerid in:utentiriferimento
AND Promozione_commerciale__r.Referente__r.Account.ACCOUNTSTATUS_MI__c = 'Attivo'
AND Promozione_commerciale__r.Referente__r.Account.RecordType.DeveloperName = 'Ambulatorio'
AND Promozione_commerciale__r.Referente__r.Account.ACCOUNTCATEGORY_MI__c = 'A'
AND Promozione_commerciale__r.Referente__r.Account.ABILITATED_MI__c = true
AND Promozione_commerciale__r.Referente__r.Account.CHECKACCOUNT_MI__c = true
AND Prodotto__r.Famiglia_dsh__c =:selectedFamilyNew
AND Prodotto__r.Set_Prod_dsh__c =:selectedSetProd
AND Promozione_commerciale__r.Data_adesione__c >=: datainizio
AND Promozione_commerciale__r.Data_adesione__c <=: datafine
AND Promozione_commerciale__r.Stato__c = 'Approvata'
AND Bonus__c =: selectedBonusBool];
}

for(Prodotti_promozioni_commerciali__c ppc:listaaccounttotA){
listapromcommA.add(ppc.Promozione_commerciale__r.Referente__r.AccountId);
}

List<AggregateResult> countaccountpromoAntintA = [SELECT count(Id) conteggiopromo
FROM Account
WHERE Id in: listapromcommA
];

 if(listaaccounttotA.size()> 0) {
DHW_Merial_2__c dmerial = new DHW_Merial_2__c();
dmerial.name = 'prova';
if(listaaccounttotA.size()> 0){
dmerial.Form_Account_accountStatus__c = listaaccounttotA.get(0).Promozione_commerciale__r.Referente__r.Account.ACCOUNTSTATUS_MI__c;
dmerial.Form_ProdottiPromozioniComm_Prodotto_Fam__c = selectedFamilyNew;
dmerial.Form_ProdottiPromozioniComm_Prodotto_Set__c = selectedSetProd;
dmerial.Form_Account_Category__c = listaaccounttotA.get(0).Promozione_commerciale__r.Referente__r.Account.ACCOUNTCATEGORY_MI__c;
dmerial.Form_Account_RecordTypeId__c = listaaccounttotA.get(0).Promozione_commerciale__r.Referente__r.Account.RecordType.DeveloperName;
}

if( String.valueOf(countaccountpromoAntintA.get(0).get('conteggiopromo')) == null || String.valueOf(countaccountpromoAntintA.get(0).get('conteggiopromo')) == 'NaN'
|| countaccountpromoAntintA.get(0).get('conteggiopromo') == '0'
|| countaccountpromoAntintA.get(0).get('conteggiopromo') == 0){

 

dmerial.Count_account_promo__c = 0;
}
else
{
dmerial.Count_account_promo__c = Integer.valueOf(countaccountpromoAntintA.get(0).get('conteggiopromo'));
}

if( String.valueOf(countaccountotaleA.get(0).get('conteggiotot')) == null || String.valueOf(countaccountotaleA.get(0).get('conteggiotot')) == 'NaN' ){
dmerial.Count_account__c = 0;
}
else
{
dmerial.Count_account__c = Integer.valueOf(countaccountotaleA.get(0).get('conteggiotot'));
}
dmerial.name = 'testdmerial'+ Date.today();
insert dmerial;

List<DHW_Merial_2__c> numero = [select Count_account_percent__c from DHW_Merial_2__c where id =: dmerial.id limit 1];

if(numero.size()> 0){
numeropercent = numero.get(0).Count_account_percent__c;

}
acccounta = dmerial.Count_account__c;


if(conteggioA == 0){
percentuale1a = numeropercent;
accpromo1a = dmerial.Count_account_promo__c;
}
else if(conteggioA == 1){
percentuale2a = numeropercent;
accpromo2a = dmerial.Count_account_promo__c;
}
else if(conteggioA == 2){
percentuale3a = numeropercent;
accpromo3a = dmerial.Count_account_promo__c;
}
else if(conteggioA == 3){

percentuale4a =numeropercent;
system.debug('percentuale 4a debug' + numeropercent);
accpromo4a = dmerial.Count_account_promo__c;

}
conteggioA++;


}
if(acccounta== 0){
formulaaccpromoa = 0;
}
else {



formulaaccpromoa = (100 * (Integer.valueOf(countaccountpromoAntintAtuttiprod.get(0).get('conteggiopromo'))))/acccounta; 

}

 

For a particular family, cause there are several records, more than other families records, I obtain a "Too many query rows", if I check All bonus , and I check a large range of dates. How can I solve this, without riducing number of records obtained with where filters?

Do I have to re-write code?

Thank you in advance for your support

 

Maria

Hello Helper

 

 

I am having a problem with controller.getSelected();    apex code

 

I have a simple visual  force  page  and an extension class

 

I have a custom button  on a related list  of an object

 

I want to select a few items  on the related list  and perform a mass update on the selected  child  records

 

in the constructor  of the extension class  I call:

 

public MyExtensionClass(ApexPages.StandardSetController controller)

{

 

...

MyChildCustomObject[] EAs = controller.getSelected();

 

if(EAs.size() == 0)
{
SerrMsg = 'Select at least 1 event attendee to update.';
ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,SerrMsg));
errorMsg = true;
return;
}

 

 

..

 

 

}

 

the size  of the EAs  array is always  0

 

 

I am missing something?

 

Regards

Csaba

 

 

 

 

 

 

 

 

 

  • October 30, 2013
  • Like
  • 0

I have some batchable apex, in the execute() method, udpates are done to pricebookentry.

 

I'm getting a weird mixed DML error.  Originally I had pricebookentry and a custom table updated in the execute() but to be safe, I took out the other update.  Now the execute() is issueing exactly one DML to pricebookentry for a few hundred rows.  I still get the mixed dml error.  Not sure how I could get a mixed dml error when there is exactly one DML issued.

 

09:23:22.107 (92107648000)|EXCEPTION_THROWN|[68]|System.DmlException: Update failed. First exception on row 0 with id 01u40000002CKwBAAW; first error: MIXED_DML_OPERATION, DML operation on setup object is not permitted after you have updated a non-setup object (or vice versa): CustomFieldDefinition, original object: PricebookEntry: []

 

The message doesn't make much sense as it says there's an attempt to update "CustomFieldDefinition".  That sounds like metadata, not data.  And as I mentioned, there is exactly one dml, to pricebookentry.

 

Yes, I did open a case with Tech Support.   I updated the logic to a single DML this morning and added that to the case, still waiting on a response after that update.

 

I thought I'd post here anyway in case anyone else has experienced this anomoly.

System.DmlException: Update failed. First exception on row 0 with id 006e00000049qyNAAQ; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, GlobalOpportunitySoldOrMissed: execution of AfterUpdate

caused by: System.LimitException: Apex CPU time limit exceeded

 

What does this error message mean?  

 

Thank you!

  • September 09, 2013
  • Like
  • 0

I have embed a google maps in one of my custom objects. Based on the customer's address, the map is being displayed on the page. But how can I generate geocode (latitude and longitude) for the address? Any suggestions please.

Thank you in advance!

  • April 24, 2012
  • Like
  • 0

I have some batchable apex, in the execute() method, udpates are done to pricebookentry.

 

I'm getting a weird mixed DML error.  Originally I had pricebookentry and a custom table updated in the execute() but to be safe, I took out the other update.  Now the execute() is issueing exactly one DML to pricebookentry for a few hundred rows.  I still get the mixed dml error.  Not sure how I could get a mixed dml error when there is exactly one DML issued.

 

09:23:22.107 (92107648000)|EXCEPTION_THROWN|[68]|System.DmlException: Update failed. First exception on row 0 with id 01u40000002CKwBAAW; first error: MIXED_DML_OPERATION, DML operation on setup object is not permitted after you have updated a non-setup object (or vice versa): CustomFieldDefinition, original object: PricebookEntry: []

 

The message doesn't make much sense as it says there's an attempt to update "CustomFieldDefinition".  That sounds like metadata, not data.  And as I mentioned, there is exactly one dml, to pricebookentry.

 

Yes, I did open a case with Tech Support.   I updated the logic to a single DML this morning and added that to the case, still waiting on a response after that update.

 

I thought I'd post here anyway in case anyone else has experienced this anomoly.

Thinking of enabling #Communities for your customer? Then be aware of the current #Gotcha that the default Apex Classes that are created when you enable your first Community do not ALL have code coverage >75%.

What this means:
You can enable Communities in Production, however as soon as you attempt to migrate anything from a sandbox into Production that triggers all tests to be run (doesn't have to be just code), your migration will fail as three of the classes only have 33%, 20% and 21%.

Let me repeat that, you might only be migrating a bunch of new custom fields and page layouts and the Change Set (or Eclipse/ANT) will fail.

I hit this problem this week in a go-live deployment so had to update Apex Classes to achieve average total code coverage >75% in order to proceed with our deployment.

The PM of Communities knows about the problem and advises he is looking at a fix, but in the meantime here are the four Apex Classes that need to be updated.

 

CommunitiesLandingControllerTest.cls

Just a one liner for this test class

/**
 * An apex page controller that takes the user to the right start page based on credentials or lack thereof
 */
@IsTest public with sharing class CommunitiesLandingControllerTest {
  @IsTest(SeeAllData=true) public static void testCommunitiesLandingController() {
    // Instantiate a new controller with all parameters in the page
    CommunitiesLandingController controller = new CommunitiesLandingController();

    // 25-Jun-2013 Manu Erwin - Fixing insufficient code coverage for default Communities Apex Tests
    PageReference pageRef = controller.forwardToStartPage();
  }
}

 

CommunitiesLoginControllerTest.cls

Just a one liner for this test class

/**
 * An apex page controller that exposes the site login functionality
 */
@IsTest global with sharing class CommunitiesLoginControllerTest {
  @IsTest(SeeAllData=true) 
  global static void testCommunitiesLoginController () {
    CommunitiesLoginController controller = new CommunitiesLoginController ();

    // 25-Jun-2013 Manu Erwin - Fixing insufficient code coverage for default Communities Apex Tests
    PageReference pageRef = controller.forwardToAuthPage();
  }  
}

 

CommunitiesSelfRegControllerTest.cls

A few controller variables to set prior to calling the controller method for the original test method, followed by a couple of additional test methods for further coverage.

/**
 * An apex page controller that supports self registration of users in communities that allow self registration
 */
@IsTest public with sharing class CommunitiesSelfRegControllerTest {
  @IsTest(SeeAllData=true) 
  public static void testCommunitiesSelfRegController() {
    CommunitiesSelfRegController controller = new CommunitiesSelfRegController();

    // 25-Jun-2013 Manu Erwin - Fixing insufficient code coverage for default Communities Apex Tests
    controller.firstName = 'Bob';
    controller.lastName = 'Jones';
    controller.email = 'bob@jones.com';
    controller.password = '8yhMsHDN&ituQgO$WO';
    controller.confirmPassword = '8yhMsHDN&ituQgO$WO';
    controller.communityNickname = 'bob-jones-testing';

    PageReference pageRef = controller.registerUser();
  }
  // 25-Jun-2013 Manu Erwin - Fixing insufficient code coverage for default Communities Apex Tests
  @IsTest(SeeAllData=true) 
  public static void testInvalidPassword() {
    CommunitiesSelfRegController controller = new CommunitiesSelfRegController();
    controller.firstName = 'Bob';
    controller.lastName = 'Jones';
    controller.email = 'bob@jones.com';
    controller.password = '8yhMsHDN&ituQgO$WO';
    controller.confirmPassword = 'not the same';
    controller.communityNickname = 'bob-jones-testing';

    PageReference pageRef = controller.registerUser();
    System.assert(pageRef == null, 'The returned page reference should be null');
  }
  // 25-Jun-2013 Manu Erwin - Fixing insufficient code coverage for default Communities Apex Tests
  @IsTest(SeeAllData=true) 
  public static void testNullPassword() {
    CommunitiesSelfRegController controller = new CommunitiesSelfRegController();
    controller.firstName = 'Bob';
    controller.lastName = 'Jones';
    controller.email = 'bob@jones.com';
    controller.communityNickname = 'bob-jones-testing';

    PageReference pageRef = controller.registerUser();
    System.assert(pageRef == null, 'The returned page reference should be null');
  }
}

 

CommunitiesSelfRegController.cls

A few additions to this class to set the Profile and Account Ids for portal user creation. Update the ProfileId value based on the "portal" license(s) (e.g., Customer Portal, Customer Community, etc) and set the AccountId to that of the Account you wish to use for self-registration. Note: this needs to be set even if you're not using self-registration so the class can be tested.

Plus some debug statements so I could see what was happening and needed to be tested.

/**
 * An apex page controller that supports self registration of users in communities that allow self registration
 */
public with sharing class CommunitiesSelfRegController {

  public String firstName {get; set;}
  public String lastName {get; set;}
  public String email {get; set;}
  public String password {get; set {password = value == null ? value : value.trim(); } }
  public String confirmPassword {get; set { confirmPassword = value == null ? value : value.trim(); } }
  public String communityNickname {get; set { communityNickname = value == null ? value : value.trim(); } }
  
  public CommunitiesSelfRegController() {}
  
  private boolean isValidPassword() {
    return password == confirmPassword;
  }

  public PageReference registerUser() {
  
    // it's okay if password is null - we'll send the user a random password in that case
    if (!isValidPassword()) {
      System.debug(System.LoggingLevel.DEBUG, '## DEBUG: Password is invalid - returning null');
      ApexPages.Message msg = new ApexPages.Message(ApexPages.Severity.ERROR, Label.site.passwords_dont_match);
      ApexPages.addMessage(msg);
      return null;
    }  

    // 25-Jun-2013 Manu Erwin - Fixing insufficient code coverage for default Communities Apex Tests
    //String profileId = ''; // To be filled in by customer.
    //String roleEnum = ''; // To be filled in by customer.
    //String accountId = ''; // To be filled in by customer.

    // Set this to your main Communities Profile API Name
    String profileApiName = 'PowerCustomerSuccess';
    String profileId = [SELECT Id FROM Profile WHERE UserType = :profileApiName LIMIT 1].Id;
    List<Account> accounts = [SELECT Id FROM Account LIMIT 1];
    System.assert(!accounts.isEmpty(), 'There must be at least one account in this environment!');
    String accountId = accounts[0].Id;
    
    String userName = email;

    User u = new User();
    u.Username = userName;
    u.Email = email;
    u.FirstName = firstName;
    u.LastName = lastName;
    u.CommunityNickname = communityNickname;
    u.ProfileId = profileId;
    
    String userId = Site.createPortalUser(u, accountId, password);
   
    if (userId != null) { 
      if (password != null && password.length() > 1) {
        System.debug(System.LoggingLevel.DEBUG, '## DEBUG: User creation successful and password ok - returning site.login');
        return Site.login(userName, password, null);
      }
      else {
        System.debug(System.LoggingLevel.DEBUG, '## DEBUG: User creation successful but password not ok - redirecting to self reg confirmation');
        PageReference page = System.Page.CommunitiesSelfRegConfirm;
        page.setRedirect(true);
        return page;
      }
    }
    System.debug(System.LoggingLevel.DEBUG, '## DEBUG: User creation not successful - returning null');
    return null;
  }
}