• Alexander Tsitsura
  • PRO
  • 2248 Points
  • Member since 2014
  • Salesforce Developer
  • Softheme


  • Chatter
    Feed
  • 56
    Best Answers
  • 0
    Likes Received
  • 3
    Likes Given
  • 2
    Questions
  • 322
    Replies

Hi everyone!

I'm trying to validate a Event field with a trigger. I'm using a trigger because it's dependent on values in the Account object. I want to show the user an error with sObject.addError() method. The test scenarios in the Salesforce GUI for 1 record at a time is working fine however the test class is failing. I'm creating 200 event records and inserting them at the same time. 

/*test class*/
try{
insert eventList;
 }
catch (Exception e) {
System.assert(e.getMessage().contains('The error message that should be shown'), e.getMessage());
 }

/*Event handler method*/
public void displayErrorMessage(List<Account> accountList){
      for (Account acc : accountList){
             if(acc.Type == 'Agency')
                eventMap.get(acc.Id).WhatID.addError('The error message that should be shown', false);
      }
}

/*Trigger*

trigger EventBefore on Event (before insert, before update) {
      if(Trigger.isInsert || Trigger.isUpdate){
          Event_TypeOfMeetingHandler handler = new Event_TypeOfMeetingHandler( trigger.new );
      }
}

THIS IS THE ERROR MESSAGE I'M GETTING:

 
Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, Too many retries of batch save in the presence of Apex triggers with failures: when triggers are present partial save requires that some subset of rows save without any errors in order to avoid inconsistent side effects from those triggers. Number of retries: 2: []

THE TEST WORKS FINE FOR THE FOLLOWING TRIGGER CODE. INSERT ONLY THOUGH.  
trigger EventBefore on Event (before insert) {
      if(Trigger.isInsert){
          Event_TypeOfMeetingHandler handler = new Event_TypeOfMeetingHandler( trigger.new );
      }
}

What am I doing wrong in the Trigger handler alternative what can I do in the test class to make this work for multiple insert and updates on  Event records? 

Thanks!

We have a visualforce 'edit' page for a custom object. The variable is stored in a String (eg: " a;b;c"). I want to be able to pull the saved values and preselect them on a multi selectList so users don't have to reselect the old values when editing. 

value = [select ....];

<apex:selectList value="{!value}" size="3" multiselect="true" label="blah" id="blah" >
                        <apex:selectOptions value="{!options}" />
                    </apex:selectList>

I've tried string format and String[] list format for 'value' and neither gets me any default selected values for this select list. 

Hi,

I have a dynamically created Opportunity where i assign values according to some formula:
 

Opportunity opp = new Opportunity(Name='SomeName', Amount=2000, Probability=20);
Whatever the values might be.

Then i convert it to a JSON String:

return JSON.serialize(opp);



My problem here is: The JSON String only contains the Values used/assigned by me. That would be Name, Probability, Amount.

Result: 

{"Name":"SomeName", "Probability":"20", "Amount":"2000"}

But I need it to also contain ExpectedRevenue, which is calculated by Probability*Amount. It is a read-only field, so i cannot set it in the code.

Desired Result:

{"Name":"SomeName", "Probability":"20", "Amount":"2000", "ExpectedRevenue":"400"}
How can i accomplish this?
I am writing an controller and VF component to email opportunitylineitemschedule details as an attachment. I am able to include schedule details to the attachment, but i am not able to include the opportunitylineitem's field in the same table. 

My requirement - for each line item schedule row, i would like to have one column populating the opportunitylineitem.Product_Name__c values. I am getting unknown property error 'String.Product_Name__c' if i try to add this field. 
my controller: 
public class emailtemplatev2{
    public emailtemplatev2() {    
    }
  List<OpportunityLineItemSchedule> revenue = new List<OpportunityLineItemSchedule>(); 
   public Id opportunityId {get;set;} 
   public List<OpportunityLineItemSchedule> getrevenue()
   { 
       revenue=[Select OpportunityLineItemId, CurrencyIsoCode, ScheduleDate,Revenue                           
                 from OpportunityLineItemSchedule where OpportunityLineItemId IN (Select ID from OpportunityLineItem 
                 where OpportunityId =:opportunityid )  ];
     return revenue;
        }  
}


VF Component: 
<apex:component controller="emailtemplatev2" access="global">
    
   
    <apex:attribute name="AcctId" type="Id" description="Id of the account" assignTo="{!opportunityId}"/>
    <table border = "2" cellspacing = "0" >
        <tr>
            <td>Product</td>
            <td>Forecast Period</td>
            <td>Currency</td>   
            <td>Amount</td> 
                         
        </tr>
        <apex:repeat value="{!revenue}" var="o">
        <tr>
            <td>{!o.OpportunityLineItemId.Product_Name__c}</td> //having issue in this line
            <td>   
            <apex:outputText value="{0,date,MMM, yyyy}">
            <apex:param value="{!o.ScheduleDate}" /> 
            </apex:outputText>
            </td>  
        
            <td>{!o.CurrencyIsoCode}</td>  
            <td>{!o.Revenue}</td> 
                        
        </tr>
        </apex:repeat>        
    </table>
</apex:component>


 
I have been looking at other posts for my questions on how Apex batch works when there is an Error. Somehow I am not able to clear my self. I have couple of questions. Can someone please clarify.

1. Assume a batch process has 3 iterations processing 200 records each. The batch process is doing an insert and I am using Database.Insert with AllorNone parameter set to False. Assume there was an error during the second iteration while processing 101 record.I understand that all the records in the first iteration will be committed and also the 100 records in the second iteration. My question is will the batch process continue to process other records in the second iteration and also the third iteration.

2. Assume all the 3 iterations (execute method) completed without any error but some error occured in the Finish method. Finish method just sends an email. How does this work, considering that I am using Database.Insert and AllorNone parameter set to False. My understanding is that all the records will be committed to the database but user will not be receiving email that the batch was successfull or not. I am confused how this scenario will work in the real time.
  • September 05, 2016
  • Like
  • 0
Hello there,

I have triggers on Contact and User objects. Contact trigger updates user record in future method. The user trigger on the other hand updates related contact in future method.

As future method is an asynchronous apex, I cannot track the execution using static variable. Is there any standard way that my scenario can be handled?

Thanks in advance.
I have an apex class that copies data from a custom field on the close case screen  into case comments when the case is closed, however it is creating the comments twice each time.  Can anyone tell me why it is doing this and how I can fix it?  Below is the apex class;

public without sharing class CaseManagement {
    
    //*****************************************************************************
  //Method called on after update of Case
  //****************************************************************************/
  public static void onAfterUpdate(List<Case> lstCase, Map<Id, Case> oldMap){ 
    checkCloseCase(lstCase, oldMap);   
  } 

  //*****************************************************************************
  //Method called to check the Close Case
  //****************************************************************************/
  public static void checkCloseCase(List<Case> lstCase, Map<Id, Case> oldMap) { 
    
    List<CaseComment> comments = new List<CaseComment>();
               
    for(Case caseUpdate : lstCase) {
            
      if( caseUpdate.Case_Close_Notes_To_Customer__c != null && caseUpdate.Case_Close_Notes_To_Customer__c != oldMap.get(caseUpdate.Id).Case_Close_Notes_To_Customer__c) {
        comments.add( new CaseComment(CommentBody = caseUpdate.Case_Close_Notes_To_Customer__c, IsPublished = false, ParentId = caseUpdate.Id));
      }
    }
    insert comments;
  }
}
I have following code:

List<user> TLSPuserlist=[Select id,Name,Email from User where UserRole.Name in:userRoles AND IsActive = true];
List<user> lst_TeamLead = new List<user>();       
 for(user u : TLSPuserlist)
{
  set<id> subord= new set<id>();            
  subord=RoleUtilsModified2.getRoleSubordinateUsers(u.Id);
  If(subord.size()>0 && subord!=NULL)
  {
       for(Id id1 : subord)
        {
             If(id1.Last_Edited_Object__c !=NULL && id1.Last_Edited_Object_Date__c > d || id1.Last_Activity_Type__c !=NULL &&    Last_Activity_Date__c > d) 
               {
                        unediteduseridlist.add(id1);
                }
       }
}


I am getting the following error:
Error: Compile Error: Variable does not exist: Last_Activity_Date__c at line 488 column 132

I have the field Last_Activity_Date__c  on User Object...
The subord for loop(  for(Id id1 : subord)  ) contains ids of all users...I need User usL subord kinda thing, so that i can do the logic and go ahead...How to achieve this..


Thanks in adv
Laxman Lax
Hi all,

I have page block table with apex:inputfield and JavaScript function that highlight selected row of that table. In Applex Safari it works perfect but in FireFox whenewer I click only first row of a table are highlighted and focus is set to the first row inputfield(Second Manager).

VF markup:
<apex:pageBlockTable id="tt"  value="{!selectedEmployees}" rules="rows" style="MbO_tab"
                          columnsWidth="24%,23%,23%,10%,20%" var="dd"   >

                      <apex:column onclick="highlight(this,'first'); " headerValue="Name"> 
                          <apex:outputField  value="{!dd.Employee.name}"/>
                      </apex:column>

                      <apex:column headerValue="Manager" onclick="highlight(this,'first'); "> 
                        <apex:outputField value="{!dd.Employee.ManagerId}"/> <!---->
                      </apex:column>

                      <apex:column headerValue="Second Manager(optional)"  >
                        <apex:inputField html-autocomplete="off" onclick="highlight(this,'second'); "  value="{!dd.secManager.Second_Manager__c}">
                           <apex:actionSupport action="{!checkSecondManagers}" event="onkeyup" reRender="employeeSelectionMessages"/>
                        </apex:inputField>          
                      </apex:column> 

                      <apex:column rendered="false" onclick="highlight(this,'first');" headerValue="Type" >
                        <apex:selectList label="Type" title="Type" value="{!dd.sType}" size="1" multiselect="false">
                          <apex:selectOptions value="{!dd.type}"/>
                              <apex:actionSupport event="onchange" action="{!dd.refresh}" reRender="Secondcolumn"/>
                        </apex:selectList>
                      </apex:column>
                      
                      <apex:column rendered="false" onclick="highlight(this,'first');" headerValue="Contract start" >
                        <apex:outputPanel id="Secondcolumn">
                        <apex:selectList rendered="{!dd.showPeriod}" label="Period" title="Period" value="{!dd.sPeriod}" size="1" multiselect="false">
                          <apex:selectOptions value="{!dd.period}"/>
                        </apex:selectList>
                        &nbsp;
                        <apex:selectList label="Year" title="Year" value="{!dd.sYear}" size="1" multiselect="false">
                          <apex:selectOptions value="{!dd.year}"/>
                        </apex:selectList>
                        </apex:outputPanel>
                      </apex:column>

                    </apex:pageBlockTable>

Script:
<script type="text/javascript">

var lastRow;
function highlight(elem,type){
    if(lastRow != undefined) {
        $('tr').removeClass('highlighted');
      }
    //if(lastRow == elem)
        //$('tr').removeClass('highlighted');
    //else {
      if(type=='second') {
        $(elem).parent().parent().parent().addClass('highlighted');  
      } else {
        $(elem).parent().addClass('highlighted');
      }
      lastRow = elem;
   // }
   
}

</script>

 
Hi All,

         Below is my Batch class. Is that always we require to pull complete records in databse in query field or can we filter using where condition. If we can filter can some one help me on this as I am getting errors

global class batchContactAccountNameUpdate implements Database.Batchable<sObject> {
    global Database.QueryLocator start(Database.BatchableContext BC) {
       String query = 'SELECT Id, AccountId,Type__C  FROM Contact where Type__c=:Asian Entities';
        return Database.getQueryLocator(query);
    }
   
    global void execute(Database.BatchableContext BC, List<Contact> scope) {
         for(Contact c : scope)
             
         {
             if(c.AccountId==null){
             
             c.AccountId = '0011900000BiZzn';            
         }
         }
         update scope;
    }   
    
    global void finish(Database.BatchableContext BC) {
    }
}
  • October 28, 2015
  • Like
  • 0
Hello,
I have to create a button which allow to delete a row in a visualforce table.

Here is the part of the visualforce code :
<apex:form>
 <apex:repeat value="{!listClient}" var="lc">
  <div class="tr">
   <span class="cell">
   <apex:outputLink value="{!supprClient(lc.Id)}" styleClass="delete">
   <apex:param name ="rowId" value="{!supprClient(lc.Id)}"/>
   </apex:outputLink>
   </span>
   <span class="cell">{!lc.LastName}</span>
   <span class="cell">{!lc.FirstName}</span>
  </div>
 </apex:repeat>
</apex:form>

And the part of my controller:
public List<Contact> listClient { get; set; }

public ExtranetV2_CampagnesController() {

		listClient = new List<Contact>();
}

public void supprClient(){
String myId = System.currentPageReference().getParameters().get('rowId');	

		for(Contact c : listClient){
			c = [SELECT Id FROM Contact WHERE Id = :myId];
			delete(c);
		}	
}

I have to retrieve the id of the row I have to delete (when the link is clicked) and apply the supprClient() method to that id ?
But I don't know how to do that, my code doesn't work, and I get an error when I want to save my visualforce page : supprClient unknown...

Thank you 
 
  • October 28, 2015
  • Like
  • 0
Hi,
I was trying to call an method of class 1 in class 2. but i am getting this error while saving class 2.
Error: Compile Error: Constructor is not visible: <IPgap>(constructor)
Ex:
Class 1:
public class IPgap 
{
   public Opportunity  opp{get; set;}
   public IPgap (ApexPages.StandardController controller)
      {
         //Some logic
      }
   private void Info(){
        intrest = new List<SelectOption>();
     }
}

Class 2:
global without sharing class ipHelper {
    //variable declarations
 public void method1() 
    {
        IPgap ipreq = new IPgap();
        string returnValue = ipreq.Info();
    }
}

Anyone can help me.

Thanks
Vivek
I'm writing an Apex class that reads a CSV spreadsheet and inserts object records accordingly. I can confirm my program can read all the fields and create insert new records with the respective fields, but I'm having a problem when I try SOQL query an Object__c record using a value from the CSV file. I recieve an error telling me "caused by: System.QueryException: List has no rows for assignment to SObject". 
String field = csvRow[4]);  
Object__c  obj = [Select Id, Name from Object__c where Name =: field];

So it's not finding the record when using the CSV value. However, when I hardcode the string into the SOQL query, it works.
Object__c  obj = [Select Id, Name from Object__c where Name = 'Test Object'];
Please note that Object__c obj is a pre-existing object/record that exists prior to the execution of the Class so its existence is not dependent on any processes within the Class. Any assistance would be appreciated.
Hello,

I want to get the list of record types for accounts available(accessible/alllowed) for the user logged in Apex.

Thanks for suggestion.
I want to upload change set to production but it is not showing option to upload to production.
it is showing another sandbox to upload.User-added image
i made a custom object to test some logic I am trying to learn.  i could have used the standard object account, but wanted to isolate my changes in a custom object.

the custom object is hpzaccount.
there is a field in this table called name.
I made a 2nd field in the table called name_unique.

name_unique is a read only-field that does not permit dups.

whenever a new record is added or updated to hpzaccount,  the trigger sets
   name_unique__c = name;

the non-bulk version of this trigger works fine. It is
trigger create_unique_name on hpzaccount__c (before insert, before update) {
for (hpzaccount__c    hpza : Trigger.new){
  hpza.name_unique__c = hpza.name;
}
}

but i want to bulk up the trigger so that it works with dataloader.
I am getting a syntax error that I cannot figure out. can you help?

  
trigger create_unique_name on hpzaccount__c ( before insert, before update) {
    List< hpzaccount__c >  hpzlist  = new List< hpzaccount__c >{};
     //Loop through all records in the Trigger.new collection
   for(hpzaccount__c   hpza  :  Trigger.new){
        
      //Concatenate fields to list
        hpzlist.name = hpza.name;
       hpzlist.name_unique__c = hpza.name;
                                                             }
Insert hpzlist;
  }      








 
Community portal user belongs to an account in Salesforce as a contact. how do I query the account name of the contact which is a user in the community portal?
how can i enforce uniqueness on a standard field in a standar object.  like the name field in the account object

i know how to define uniqueness on a custom object and custom field.  But how do i do it on a standard object and field?
 
Hi,

When i am run the test class i am getting this error

System.QueryException: expecting a colon, found 'sent'
Stack Trace    Class.WTPAA_sendReminderwagenoticestoemployees.start: line 8, column 1

Here is my test class


@isTest
 private class WTPAA_sendReminderwgntoemployees_Test{
  Static testmethod void WTPAA_sendReminderwgntoemployees_TestMethod(){
  
   Date td = system.Today();
   User u;
   User thisUser = [SELECT Id FROM User WHERE Id = :UserInfo.getUserId()];
    System.runAs (thisUser) {

            Profile p = [SELECT Id FROM Profile WHERE Name='System Administrator'];
            

            UserRole r = [SELECT Id FROM UserRole WHERE Name='WCT Admin'];

            u = new User(alias = 'sindu1', email='sandvarma1@deloitte.com',

                emailencodingkey='UTF-8', lastname='Smith',

                languagelocalekey='en_US',

                localesidkey='en_US', profileid = p.Id, userroleid = r.Id,

                timezonesidkey='America/Chicago',
                username='sandvarma1@deloitte.com.wct.prd.onebox');

            insert u;
      }      
    recordtype rt=[select id from recordtype where DeveloperName = 'WCT_Employee'];
        Contact con=WCT_UtilTestDataCreation.createEmployee(rt.id);
       // con.CreatedDate = td;
        insert con;
        
        WTPAA_Wage_Notice__c wgn = new WTPAA_Wage_Notice__c();
        wgn.WTPAA_Related_To__c = con.id;
        wgn.WTPAA_Status__c = 'Sent';
      // wgn.WTPAA_Reminder_for_2nd_week__c = ;
      //  wgn.WTPAA_Reminder_for_3rd_week__c= td.adddays(14) ;
       // wgn.WTPAA_Reminder_for_4nd_week__c = td.adddays(21)  ;
       insert wgn;
       EmailTemplate et = [SELECT id FROM EmailTemplate WHERE developerName = 'WTPAA_Reminder_for_2_weeks' limit 1];
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        mail.setTargetObjectId(wgn.WTPAA_Related_To__r.id);
        mail.setWhatid(wgn.id);
        mail.SetTemplateid(et.id);
        mail.setSaveAsActivity(false);
         for(OrgWideEmailAddress owa1 : [select id, Address from OrgWideEmailAddress]) {

           if(owa1.Address.contains('replicastatelabor@gmail.com')) {
            mail.setOrgWideEmailAddressId(owa1 .id);
           }
         }  
      //  OrgWideEmailAddress owa = [select Id, Address from OrgWideEmailAddress where DisplayName='Deloitte US Offers1' limit 1];
        
      Test.StartTest();
   WTPAA_sendReminderwagenoticestoemployees objBatch = new WTPAA_sendReminderwagenoticestoemployees ();
    ID batchprocessid = Database.executeBatch(objBatch);
   Test.StopTest();
  }
 
}

Here is the my Batch class

global class  WTPAA_sendReminderwagenoticestoemployees Implements Database.Batchable <sObject> {
    global Database.queryLocator start(Database.BatchableContext bc) {
        
        Date d = Date.today();
       String SOQL = 'SELECT Id, WTPAA_Employee_Email__c,WTPAA_Related_To__r.id,WTPAA_Status__c,WTPAA_Reminder_for_2nd_week__c,WTPAA_Reminder_for_3rd_week__c,WTPAA_Reminder_for_4nd_week__c FROM WTPAA_Wage_Notice__c WHERE (WTPAA_Reminder_for_2nd_week__c = :d OR WTPAA_Reminder_for_3rd_week__c = :d OR WTPAA_Reminder_for_4nd_week__c = :d) AND WTPAA_Status__c =  sent ';
        //String SOQL = 'SELECT Id,WTPAA_Company_Name__c, WTPAA_Employee_Email__c,WTPAA_Related_To__r.id,WTPAA_Is_same_Employer_Mailing_Address__c FROM WTPAA_Wage_Notice__c WHERE WTPAA_Is_same_Employer_Mailing_Address__c = false';
            
        return Database.getQueryLocator(SOQL);
    }

    global void execute(Database.BatchableContext bc, List<WTPAA_Wage_Notice__c> wagenotice) {
        List<Messaging.SingleEmailMessage> mailList = new List<Messaging.SingleEmailMessage>();
       Emailtemplate et = [select id, developername , IsActive from Emailtemplate where developername = 'WTPAA_Reminder_for_2_weeks' AND IsActive = true];
      
        for(WTPAA_Wage_Notice__c w: wagenotice) {
           system.debug('size of the list' +wagenotice.size());
           system.debug('ID**********' +w.id);
          //  List<String> toAddresses = new List<String>{w.WTPAA_Employee_Email__c};           
            Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
          //  mail.setToAddresses(toAddresses);
          
            mail.SetTemplateid(et.id);
            mail.setSaveAsActivity(false);
          
           mail.setTargetObjectId(w.WTPAA_Related_To__r.id);
           system.debug('ID of Contact' +w.WTPAA_Related_To__r.id);
           mail.setWhatid(w.id);
        for(OrgWideEmailAddress owa : [select id, Address from OrgWideEmailAddress]) {

           if(owa.Address.contains('replicastatelabor@gmail.com')) {
            mail.setOrgWideEmailAddressId(owa .id);
           }
          } 
           
            system.debug('IDDDDDDDDDDD*******' +et.id);
            mailList.add(mail);   
               
        } 
        Messaging.sendEmail(mailList);        
    }

    global void finish(Database.BatchableContext bc) {
    }
}

While execute the batch class i didn't get the error ..............Only when i am run the test class i am getting above error


 
  • October 12, 2015
  • Like
  • 0
Hi Community,

I have a strange issue while using the lightning:recordEditForm and the lightning:inputField components. When I put, for example, "1................" to the number field, it's cleared after losing the focus. It can be painful for a user which by error put for example, second "."

Here I captured the demo:
https://www.screencast.com/t/BfGA142yf7dV

Here is the code that I used:
<lightning:recordEditForm recordId="0061U000009UEze" objectApiName="Opportunity">
	<lightning:inputField fieldName="Amount" aura:id="field" />
	<div class="slds-m-top_medium">
		<lightning:button type="submit" label="Save" />
	</div>
</lightning:recordEditForm>

Does anybody know how to fix that to keep the incorrect value?  I want to give a chance to the user to fix an incorrect value.

Thanks,
Alex
Hi all

I am unable to complete this challenge because whenever I am clicking check button, I receive the error message.
User-added image
"Challenge Not yet complete... here's what's wrong: 
It doesn't appear that you've added protection against CSRF. Make sure you re-write 
the outputlink to a commandlink that is not vulnerable to CSRF, that the action is no longer in the on-load method and the correct method is referenced by the command link"

I don't understand what is wrong. I removed the action handler from the apex:page tag and below the comment "<!-- complete challenge here -->" added command link. 
 
<apex:page controller="CSRF_Challenge" sidebar="false" tabStyle="CSRF_Challenge__tab" > <!-- action="{!approveReq}" -->
<apex:sectionHeader title="CSRF Challenge" />
<apex:form >
    <apex:pageBlock >
        <apex:pageMessages />      
        <apex:pageBlockSection title="Demo" columns="1" id="tableBlock">

            <apex:pageBlockTable value="{!Requisitions }" var="req">
                
                <!-- skipped -->    
                                             
                <apex:column headervalue="Approval Action">
                    <apex:outputLink target="_new" value="/apex/CSRF_Challenge?approve={!req.id}">Approve This Requisition</apex:outputLink>
                </apex:column>
                <apex:column headervalue="Approval Action (NO CSRF)">
                    TBD
                    <!-- complete challenge here -->
                    <apex:commandLink value="Approve This Requisition" action="{!approveReqNOCSRF}"> 
                        <apex:param name="reqId" value="{!req.id}" assignTo="{!approve}"/> 
                    </apex:commandLink>
                </apex:column>                                                                                               
            </apex:pageBlockTable>
       
        </apex:pageBlockSection>
        
        <!-- skipped -->
         
</apex:form>              
</apex:page>



Any advice?

Thanks,
Alex
Can someone give me detailed references/articles of how triggers work in asynchronous apex. in normal synchronous apex trigeers inserts records in the batch count of 200s each for every iteration. mean 1000 rows go in 5 batches. what happens in asynchronous processing. If i have a queueable inserting 1000 rows how they are processed.
Can someone give me detailed references/articles of how triggers work in asynchronous apex. 
  • December 10, 2017
  • Like
  • 1

Hi everyone!

I'm trying to validate a Event field with a trigger. I'm using a trigger because it's dependent on values in the Account object. I want to show the user an error with sObject.addError() method. The test scenarios in the Salesforce GUI for 1 record at a time is working fine however the test class is failing. I'm creating 200 event records and inserting them at the same time. 

/*test class*/
try{
insert eventList;
 }
catch (Exception e) {
System.assert(e.getMessage().contains('The error message that should be shown'), e.getMessage());
 }

/*Event handler method*/
public void displayErrorMessage(List<Account> accountList){
      for (Account acc : accountList){
             if(acc.Type == 'Agency')
                eventMap.get(acc.Id).WhatID.addError('The error message that should be shown', false);
      }
}

/*Trigger*

trigger EventBefore on Event (before insert, before update) {
      if(Trigger.isInsert || Trigger.isUpdate){
          Event_TypeOfMeetingHandler handler = new Event_TypeOfMeetingHandler( trigger.new );
      }
}

THIS IS THE ERROR MESSAGE I'M GETTING:

 
Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, Too many retries of batch save in the presence of Apex triggers with failures: when triggers are present partial save requires that some subset of rows save without any errors in order to avoid inconsistent side effects from those triggers. Number of retries: 2: []

THE TEST WORKS FINE FOR THE FOLLOWING TRIGGER CODE. INSERT ONLY THOUGH.  
trigger EventBefore on Event (before insert) {
      if(Trigger.isInsert){
          Event_TypeOfMeetingHandler handler = new Event_TypeOfMeetingHandler( trigger.new );
      }
}

What am I doing wrong in the Trigger handler alternative what can I do in the test class to make this work for multiple insert and updates on  Event records? 

Thanks!

public class accountprioritysort {
    public list<Company_Priorities__c> acts {set;get;}
    public accountprioritysort (){
        acts = [select Field1__c,Account_Priorities__c from Company_Priorities__c];
    }    
}

The Field1__c (has priority number) so i want to have the SOQL with where condition, that i want to display all the first 5 records which have Field1__c with numbers. Please see the below screen shot. Your help is really appreciated.

 

Priority

Hi ,
 i have uplaoded the java script  file in staticresoure.  iam getting the pop up correctly. but  ih ave written the function in that file which will return multiplication of 2 numbres . Please suggest me how to display the value returned form the java script.

my ststic resource code is,

function popup() { alert("Hello World") }
function myFunction(a, b) {
    return a * b;


 And the vf code is,

<apex:page >

<html>

<head>
<apex:includeScript value="{!$Resource.jsss}"/>

</head>
</html>

<script type="text/javascript" >
popup()

 myFunction(4,5);
 
 
 

</script>

<apex:pageBlock>


</apex:pageBlock>
</apex:page>
   
Any body suggest me aboutthis.


Regards,
Siva.

 
We have a visualforce 'edit' page for a custom object. The variable is stored in a String (eg: " a;b;c"). I want to be able to pull the saved values and preselect them on a multi selectList so users don't have to reselect the old values when editing. 

value = [select ....];

<apex:selectList value="{!value}" size="3" multiselect="true" label="blah" id="blah" >
                        <apex:selectOptions value="{!options}" />
                    </apex:selectList>

I've tried string format and String[] list format for 'value' and neither gets me any default selected values for this select list. 

Hi,

I have a dynamically created Opportunity where i assign values according to some formula:
 

Opportunity opp = new Opportunity(Name='SomeName', Amount=2000, Probability=20);
Whatever the values might be.

Then i convert it to a JSON String:

return JSON.serialize(opp);



My problem here is: The JSON String only contains the Values used/assigned by me. That would be Name, Probability, Amount.

Result: 

{"Name":"SomeName", "Probability":"20", "Amount":"2000"}

But I need it to also contain ExpectedRevenue, which is calculated by Probability*Amount. It is a read-only field, so i cannot set it in the code.

Desired Result:

{"Name":"SomeName", "Probability":"20", "Amount":"2000", "ExpectedRevenue":"400"}
How can i accomplish this?
I am writing an controller and VF component to email opportunitylineitemschedule details as an attachment. I am able to include schedule details to the attachment, but i am not able to include the opportunitylineitem's field in the same table. 

My requirement - for each line item schedule row, i would like to have one column populating the opportunitylineitem.Product_Name__c values. I am getting unknown property error 'String.Product_Name__c' if i try to add this field. 
my controller: 
public class emailtemplatev2{
    public emailtemplatev2() {    
    }
  List<OpportunityLineItemSchedule> revenue = new List<OpportunityLineItemSchedule>(); 
   public Id opportunityId {get;set;} 
   public List<OpportunityLineItemSchedule> getrevenue()
   { 
       revenue=[Select OpportunityLineItemId, CurrencyIsoCode, ScheduleDate,Revenue                           
                 from OpportunityLineItemSchedule where OpportunityLineItemId IN (Select ID from OpportunityLineItem 
                 where OpportunityId =:opportunityid )  ];
     return revenue;
        }  
}


VF Component: 
<apex:component controller="emailtemplatev2" access="global">
    
   
    <apex:attribute name="AcctId" type="Id" description="Id of the account" assignTo="{!opportunityId}"/>
    <table border = "2" cellspacing = "0" >
        <tr>
            <td>Product</td>
            <td>Forecast Period</td>
            <td>Currency</td>   
            <td>Amount</td> 
                         
        </tr>
        <apex:repeat value="{!revenue}" var="o">
        <tr>
            <td>{!o.OpportunityLineItemId.Product_Name__c}</td> //having issue in this line
            <td>   
            <apex:outputText value="{0,date,MMM, yyyy}">
            <apex:param value="{!o.ScheduleDate}" /> 
            </apex:outputText>
            </td>  
        
            <td>{!o.CurrencyIsoCode}</td>  
            <td>{!o.Revenue}</td> 
                        
        </tr>
        </apex:repeat>        
    </table>
</apex:component>


 
I have been looking at other posts for my questions on how Apex batch works when there is an Error. Somehow I am not able to clear my self. I have couple of questions. Can someone please clarify.

1. Assume a batch process has 3 iterations processing 200 records each. The batch process is doing an insert and I am using Database.Insert with AllorNone parameter set to False. Assume there was an error during the second iteration while processing 101 record.I understand that all the records in the first iteration will be committed and also the 100 records in the second iteration. My question is will the batch process continue to process other records in the second iteration and also the third iteration.

2. Assume all the 3 iterations (execute method) completed without any error but some error occured in the Finish method. Finish method just sends an email. How does this work, considering that I am using Database.Insert and AllorNone parameter set to False. My understanding is that all the records will be committed to the database but user will not be receiving email that the batch was successfull or not. I am confused how this scenario will work in the real time.
  • September 05, 2016
  • Like
  • 0
Hi,
I have trigger calling an external Api once an account is updated, I don't have any DML in the trigger and
I'm calling a handler and assigning @future(callout = true) for the method calling the external Api
but having this issue:
System.CalloutException: You have uncommitted work pending. Please commit or rollback before calling out*
I have deactivated the workflow assigned to account but still having this issue
and don't see how to debug it even after looking to the developer logs
any thoughts please how to debug this issue ?
Hello there,

I have triggers on Contact and User objects. Contact trigger updates user record in future method. The user trigger on the other hand updates related contact in future method.

As future method is an asynchronous apex, I cannot track the execution using static variable. Is there any standard way that my scenario can be handled?

Thanks in advance.
Hi,

Where can I get all img icon of salesforce?
I am using the following site.
http://blogforce9dev-developer-edition.ap1.force.com/salesforceicons
But I need such as chalkboard icon that used when custom tab created.
Is there other site?

Regards,
LinThaw

by the way I want to use icon something like this...
<apex:pageblock id="ContactRecord" >
   
    <apex:facet name="header">
        <apex:panelGrid columns="1" width="100%" columnClasses="colstyleLeft,colstyleRight">
            <div class="pbTitle" style="width:100%;padding-left:0px;padding-top:0px;">
                <img src="/img/icon/computer24.png" class="relatedListIcon" style="width:24px;display:block;" />
                <h3 class="mainTitle">&nbsp;Title1</h3>
            </div> 
    </apex:facet>  

    ...

 </apex:pageblock>
Thanks.




 
I have a query inside a trigger and one of the conditions is that a reference field (lookup) is not null. My query is:
List<Contract> contratti=[Select Id,Opportunitl__c from Contract 
        where Id IN: Trigger.new AND Opportunitl__c !=null ];

where Opportunitl__c is the reference field, but it's not working. The list "contratti" contains Contracts with an empty Opportunitl__c. What is wrong in this query?
Hi All,

I need to return the values from apex class to batch class. The below code throws constructor not defined. Can any one let me know how to pass list of inserted accounts to batch class.
 
public with sharing class CalloutBatchApex implements Database.Batchable<Integer>, Database.AllowCallouts {
    public Iterable<String> start(Database.BatchableContext BC) {
        return new List<Integer> { 1, 2, 3 };
    }
 
    public void execute(Database.BatchableContext info, List<integer> iteration) {
        // Make the callout to the web service and import the records to Salesforce for the iteration.
       String responseStrng = response.getBody();
        insertAccountMethod.methodone(responseStrng);
    }
 
    public void finish(Database.BatchableContext info) {}
}

//Calling Apex class here

public class insertAccountMethod{
   List<Account> accList = new List<Account>();
         public methodone(String responseStrng){
         //my code here
         I need to return the above accList to batch class.I have tried with the below line
          
         CalloutBatchApex c = new CalloutBatchApex();
         DataBase.execute(c,1);

        }
}

Thanks
​Arjun
Hi All,

I need to return the values from apex class to batch class. The below code throws constructor not defined. Can any one let me know how to pass list of inserted accounts to batch class.
 
public with sharing class CalloutBatchApex implements Database.Batchable<Integer>, Database.AllowCallouts {
    public Iterable<String> start(Database.BatchableContext BC) {
        return new List<Integer> { 1, 2, 3 };
    }
 
    public void execute(Database.BatchableContext info, List<integer> iteration) {
        // Make the callout to the web service and import the records to Salesforce for the iteration.
       String responseStrng = response.getBody();
        insertAccountMethod.methodone(responseStrng);
    }
 
    public void finish(Database.BatchableContext info) {}
}

//Calling Apex class here

public class insertAccountMethod{
   List<Account> accList = new List<Account>();
         public methodone(String responseStrng){
         //my code here
         I need to return the above accList to batch class.I have tried with the below line
          
         CalloutBatchApex c = new CalloutBatchApex();
         DataBase.execute(c,1);

        }
}

 
I have an apex class that copies data from a custom field on the close case screen  into case comments when the case is closed, however it is creating the comments twice each time.  Can anyone tell me why it is doing this and how I can fix it?  Below is the apex class;

public without sharing class CaseManagement {
    
    //*****************************************************************************
  //Method called on after update of Case
  //****************************************************************************/
  public static void onAfterUpdate(List<Case> lstCase, Map<Id, Case> oldMap){ 
    checkCloseCase(lstCase, oldMap);   
  } 

  //*****************************************************************************
  //Method called to check the Close Case
  //****************************************************************************/
  public static void checkCloseCase(List<Case> lstCase, Map<Id, Case> oldMap) { 
    
    List<CaseComment> comments = new List<CaseComment>();
               
    for(Case caseUpdate : lstCase) {
            
      if( caseUpdate.Case_Close_Notes_To_Customer__c != null && caseUpdate.Case_Close_Notes_To_Customer__c != oldMap.get(caseUpdate.Id).Case_Close_Notes_To_Customer__c) {
        comments.add( new CaseComment(CommentBody = caseUpdate.Case_Close_Notes_To_Customer__c, IsPublished = false, ParentId = caseUpdate.Id));
      }
    }
    insert comments;
  }
}
Hi all,

global class batchprocessdesc implements Database.Batchable<sObject>
{

    global Database.QueryLocator start(Database.BatchableContext BC)
    {
        String query = 'select id from Account';
        return Database.getQueryLocator(query);
    }

    global void execute(Database.BatchableContext BC, List<Account> accounts)
    {
        list<Entitlement> ents = [select AccountId, id, Product_Family__c, EndDate from Entitlement where AccountId IN :accounts ORDER BY AccountId,Product_Family__c,EndDate DESC];
        //Map<Id, Entitlement> pfmap= new Map<Id, Entitlement>(ents);
       
        map<Product_Family__c,EndDate> PFMAP = new map<Product_Family__c,EndDate>(ents); // Error: Compile Error: Invalid type: EndDate at line 15 column 74

        for (Entitlement objent: ents)
        {
          
           pfmap.put('Product_Family__c','EndDate');

        }
        
    } 
    global void finish(Database.BatchableContext BC)
    {
    }
}
I am new and I just need a basic video showing me how this works.  Each video I find shows a different home page.  It looks nothing like my home page in salesforce.  Where do I find a basic video??!!???  I am very fustrated, I have called Salesforce TWICE to ask this question.
Hello,

I have written a test class, for code coverage.
the code coverage is not proper for a fucntion.
it accepts no paramenters.
but it stop inside for loop.
i am making query inside for loop and it doesnt not enter this loop,whe i execute the query it is passing

User-added image

Any suggestion
 
Can anyone tell me how to search for a '%' inserted as text at the end of a Text string?

    LIKE '%[%]'  

This works fine in SQL. How would this work in SOQL?
Hi ALL,

I am creating an inline vf page on parent object which shows all child records with custom button.
Now I have done this by using command button ,so that it will redirect to another vf page ,i am able to do that by Page refernce ,now the question is how can i can pass the selected child record id into the page reference.

Apperciate if any body could help me out.

Thanks in advance
Hi, 
Most of the procedural languages like SQL have locking,blocking and deadlocking issues,wondering if apex has blocking issues,coz i have seen posts about locking and deadlocking but not blocking relating to apex, could some one eloborate each of those with an example if possible and any statements that helps to troublshoot, like FOR UPDATE statement for locking records
  • September 30, 2015
  • Like
  • 2