• Niket SF
  • 293 Points
  • Member since 2011
  • Salesforce Developer

  • Chatter
  • 9
    Best Answers
  • 0
    Likes Received
  • 3
    Likes Given
  • 1
  • 151
Hello, I'm trying to make a trigger that A) creates a Location Record (named Location 1) when a new Account Record is made, and B) automatically populates the new Location Record's address information using the new Account Record's shipping information. The problem that I seem to be having is that there's an error thrown when I try to compile complaining that the variables that I used for the Location object do not exist, when in fact they do. I think the problem is that there is some kind of difference between creating a location for the account and creating a location record, since the user is not asked their address when a location is added to the account. Thanks in advance!

trigger SetsLocationAddress on Account (after insert) {
    for(Account accountInLoop : Trigger.new )
        //tests if account is type Customer
        if( accountInLoop.salesReach__Account_Type__c == 'Customer - Partner' || accountInLoop.salesReach__Account_Type__c == 'Customer - Direct')
            //creates new location record based on shipping address on account record 
            Location newLocation = new Location();
            newLocation.salesReach__Location__c = 'Location 1';
            newLocation.salesReach__Street__c = accountInLoop.salesReach__Address__c;
            newLocation.salesReach__City__c = accountInLoop.salesReach__City__c;
            newLocation.salesReach__State__c = accountInLoop.salesReach__State__c;
            newLocation.salesReach__Zip_Code__c = accountInLoop.salesReach__ZIP__c;                        
Hey there,

I have a custom object Destiny products which is a child of accounts. I would like to send an email to all contacts associated with the account when the Destiny products stage field reaches level 4. i attempted to do this with a workflow rule but it would not let me. Is it possible to do with a apex trigger?

Any help would be appreciated.

hi I m using follwing c# coding.. In runtime i got error  "INVALID_SESSION_ID: Invalid Session ID found in SessionHeader: Illegal Session"...


getClassId.getClassIdService getClassIdObj = new getClassId.getClassIdService();
getClassIdObj.SessionHeaderValue = new getClassId.SessionHeader();
getClassIdObj.SessionHeaderValue.sessionId = sessionId;

if (ddlClassname.SelectedIndex != 0)
string name = ddlClassname.SelectedItem.Text.ToString();

getClassId.Class__c getClassIdResponse = getClassIdObj.getClassIdFromClassname(ddlClassname.SelectedItem.Text.ToString());
Session["ClassName"] = getClassIdResponse.Name;
Session["ClassId"] = getClassIdResponse.Id;
Session["ClassDay"] = getClassIdResponse.Day_of_Week__c;
lbError.Visible = true;
lbError.Text = "You must select class name!";

  • May 15, 2012
  • Like
  • 0



In my organisation, we have VF page to create a new record for an object. It has 2 different record types. We have overridden the New button to open the VF page. This all works fine.

Now there is a requirement to add "Save & New" button in the VF page. I have written code to save and redirect to the record type selection page (hard coded the URL).

Save works fine and redirect is also working normally. But now when i select a record type and click on create, after that an error occurs " Broken URL error".


My code:

public PageReference save_New(){
         try {
            PageReference pr = new PageReference(<URL given here>);
            return pr;  
       catch(Exception e) {   
            return null;        


What am i doing wrong here?

Alternatively, Is there a standard function for Save & New that I can use?

Any help would be appreciated.




Sorry, I a new people on Visualforce page development.


when I develop visualforce page, I am confusing by the session binding syntax.


in the "AJAX Tookit Developer's Guide" book, I find an example on page 6, it puts the following code on the VF page:

<script type="text/javascript">
var __sfdcSessionId = '{!GETSESSIONID()}';


I believe, the above code is used to do the session binding.


But on the other hand, I find some VF page are use the following code to do the session binding:

sforce.connection.sessionId = "{!$Api.Session_ID}";


what is the different between the first approach and the second one?  could someone help on this?  many thanks!

Hi all,

I am newbie to apex Batch classes. I need to understand how Apex batches execute(the process).

I know how to write apex classes and trigeers. but totally confused in following Apex batch code. Kindly give me some tips/knowledge/information on how easily I can write apex batches.


  1. global class Beautification's implements Database.Batchable<sObject>{
  2. global final String Query;
  3. global final String Entity;
  4. global final String Field;
  5. global final String Value;
  6. global UpdateAccountFields(String q, String e, String f, String v){
  7. Query=q; Entity=e; Field=f;Value=v;
  8. }
  9. global Database.QueryLocator start(Database.BatchableContext BC){
  10. return Database.getQueryLocator(query);
  11. }
  12. global void execute(Database.BatchableContext BC,
  13. List<sObject> scope){
  14. for(Sobject s : scope){s.put(Field,Value);
  15. } update scope;
  16. }
  17. global void finish(Database.BatchableContext BC){
  18. }
  19. }

The following code can be used to call the above class:


1. Id batchInstanceId = Database.executeBatch(new UpdateInvoiceFields(q,e,f,v), 5);


I am little confused of the following lines:


1. ""query","entity","field","value"" declared as variable and at 7th line why it is assigned to q,e,f,v.

2.  return Database.getQueryLocator(query)...?

3.  [List<sObject> scope)  {  for(Sobject s : scope){s.put(Field,Value);]..in line 13,14.

Can't we use directly Account,lead,contact or any custom object. Like this:[ List<account>scope { for(account a:scope...].

4. Id batchInstanceId = Database.executeBatch(new UpdateInvoiceFields(q,e,f,v), 5);


can please explain line by line.

thank you in advance.

any kind of explanation/suggestions/information is highly appriciated.


I know that the email template on mass email is related only to user and contact, but my question is: there is a way to do a mass email on a custom object?!


This is my apex class:


public with sharing class MassEmail
public List<Applicant_test__c> usr{get;set;} //
public List<String> usr_email{get;set;}
public Map<string,string> Map_usr{get;set;}
public string emailid{get;set;}
public string provaemail;
Contact con = new contact();

public void getprovaemail()
Contact con = new contact();
con = [Select Id from Contact where Id = :'a0D?fcf=00Bd0000003kLEZ'];
usr=new List<Applicant_test__c>();
usr_email=new List<String>();
usr=[select Email__c from Applicant_test__c where Keep_in_touch__c=true];
for(Applicant_test__c u : usr)
public void sendmail(List<String> str)
Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();

EmailTemplate EmailTemp = [SELECT id FROM EmailTemplate WHERE developerName = 'Standard_New_Interview'];


//email.setTargetObjectId(Applican_test id);

Messaging.sendEmail(New Messaging.SingleEmailMessage[]{email});




Thanks in advance

I'm new to salesforce and the IDE.  I installed the IDE sucessfully.  (Windows Installer (32-bit))   After I launch the IDE, I attempted to upgrade.  (Eclipse Platform and SDK 3.5.2,  Force.com IDE 24.0.0)


After the upgrade, I'm not able to launch.  .metadata\.log shows the following:

!SESSION 2012-04-18 11:40:47.652 -----------------------------------------------
java.vendor=Sun Microsystems Inc.
BootLoader constants: OS=win32, ARCH=x86, WS=win32, NL=en_US
Command-line arguments: -os win32 -ws win32 -arch x86

!ENTRY org.eclipse.osgi 4 0 2012-04-18 11:40:57.979
!MESSAGE Application error
java.lang.RuntimeException: Application "" could not be found in the registry. The applications available are: com.genuitec.pulse2.client.installer.ui.application, com.genuitec.pulse2.client.launcher.ui.application, org.eclipse.equinox.p2.artifact.optimizers.jardeltaoptimizer, org.eclipse.equinox.p2.artifact.optimizers.pack200optimizer, org.eclipse.equinox.p2.artifact.optimizers.jbdiffoptimizer, org.eclipse.equinox.p2.artifact.repository.mirrorApplication, org.eclipse.equinox.p2.garbagecollector.application, org.eclipse.equinox.p2.metadata.generator.EclipseGenerator, org.eclipse.equinox.p2.metadata.repository.mirrorApplication, org.eclipse.equinox.p2.publisher.InstallPublisher, org.eclipse.equinox.p2.publisher.ProductPublisher, org.eclipse.equinox.p2.publisher.FeaturesAndBundlesPublisher, org.eclipse.equinox.p2.reconciler.application, org.eclipse.equinox.p2.repository.repo2runnable, org.eclipse.equinox.p2.ui.admin.rcp.application, org.eclipse.equinox.p2.updatesite.UpdateSitePublisher, org.eclipse.equinox.p2.publisher.UpdateSitePublisher, org.eclipse.equinox.p2.publisher.CategoryPublisher, org.eclipse.update.core.standaloneUpdate, org.eclipse.update.core.siteOptimizer, org.eclipse.ant.core.antRunner, org.eclipse.ant.ui.antRunner, org.eclipse.equinox.app.error, org.eclipse.equinox.p2.director.app.application, org.eclipse.equinox.p2.director, org.eclipse.help.base.infocenterApplication, org.eclipse.help.base.helpApplication, org.eclipse.help.base.indexTool, org.eclipse.jdt.apt.core.aptBuild, org.eclipse.jdt.core.JavaCodeFormatter, org.eclipse.ui.ide.workbench.
at org.eclipse.equinox.internal.app.EclipseAppContainer.startDefaultApp(EclipseAppContainer.java:242)
at org.eclipse.equinox.internal.app.MainApplicationLauncher.run(MainApplicationLauncher.java:29)
at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:110)
at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:79)
at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:368)
at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:179)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:559)
at org.eclipse.equinox.launcher.Main.basicRun(Main.java:514)
at org.eclipse.equinox.launcher.Main.run(Main.java:1311)


How do I fix this?  Any help is appreciated.


I have 2 VF pages which are similar and the controllers are similar too.

The only difference is that the first VF page accepts user to fill in the dates and queries the records within that date range.


The second VF is uses the dates from query string.


I get the same records in both the pages except that there is one field which comes as null for some records only.

I cant see what could cause this. Cant be a security issue as the same values are visible in one Vf page.


Here is the code for both pages


VFpage which is causing the Event__r.name not to display for some records only


 <apex:datatable value="{!LstOutgoingShipments}" columns="14"  var="inShip"  width="100%" cellpadding="2" cellspacing="2" columnsWidth="30px,50px,50px,50px,50px,50px,50px,50px,50px,50px,50px,50px,50px" rules="all" id="dtshiprec">
 <apex:column headerClass="columntext" styleClass="columntext">
 <apex:facet name="header">Departed</apex:facet>
 <apex:outputField value="{!inShip.Shipment_Departed__c}"/>
  <apex:column headerClass="columntext" styleClass="columntext">
 <apex:facet name="header">Equipment</apex:facet>
 <apex:outputText value="{!inShip.Equipment__r.name}"/>
 <apex:column headerClass="columntext" styleClass="columntext">
 <apex:facet name="header">Event</apex:facet>
  <apex:outputText value="{!inShip.Event__r.name}"/>
  <apex:column headerClass="columntext" styleClass="columntext">
 <apex:facet name="header">Ship from <br/>Location</apex:facet>
  <apex:outputText value="{!inShip.Ship_From_Location__r.name}"/>
   <apex:column headerClass="columntext" styleClass="columntext">
 <apex:facet name="header">Estimated<br/> Dep Time</apex:facet>
  <apex:outputField value="{!inShip.Est_Departure_Time__c}"/>
     <apex:column headerClass="columntext" styleClass="columntext">
 <apex:facet name="header">Ship To<br/> Location</apex:facet>
  <apex:outputText value="{!inShip.Ship_To_Location__r.name}"/>

       <apex:column headerClass="columntext" styleClass="columntext">
 <apex:facet name="header">Estimated <br/>Arrival Time</apex:facet>
  <apex:outputfield value="{!inShip.Estimated_Arrival_Time__c}"/>
        <apex:column headerClass="columntext" styleClass="columntext">
 <apex:facet name="header">Ship To <br/>Instructions</apex:facet>
  <apex:outputText value="{!inShip.Ship_To_Instructions__c}"/>
         <apex:column headerClass="columntext" styleClass="columntext">
 <apex:facet name="header">Carrier</apex:facet>
  <apex:outputText value="{!inShip.Shipping_Carrier__c}"/>
          <apex:column headerClass="columntext" styleClass="columntext">
 <apex:facet name="header">Driver</apex:facet>
  <apex:outputText value="{!inShip.Shipping_Driver__c}"/>
           <apex:column headerClass="columntext" styleClass="columntext">
 <apex:facet name="header">Driver Phone</apex:facet>
  <apex:outputText value="{!inShip.Shipping_Driver_Phone__c}"/>
            <apex:column headerClass="columntext" styleClass="columntext">
 <apex:facet name="header">Post Event Instructions</apex:facet>
  <apex:outputText value="{!inShip.Post_Event_Instructions__c}"/>
            <apex:column headerClass="columntext" styleClass="columntext">
 <apex:facet name="header">No Of <br/>Rolling Cases</apex:facet>
  <apex:outputText value="{!inShip.No_of_Rolling_Case__c}"/>
            <apex:column headerClass="columntext" styleClass="columntext">
 <apex:facet name="header">No Of <br/>HD Cases</apex:facet>
  <apex:outputText value="{!inShip.No_of_HD_Case__c}"/>


 Controller for the page which is not displaying one field for some records


public with sharing class PrintShipDepartedController {
    public List<Event_Equipment__c> LstOutgoingShipments= new List<Event_Equipment__c>();
    public List<Event_Equipment__c> LstIncomingShipments=new List<Event_Equipment__c>();
    public List<user> LstCurrentUserAccount= new List<user>();
    Id userid;
    public date startdate1 {get; set;}
    public date enddate1 {get; set;}     
     public List <Event_Equipment__c> getLstOutgoingShipments() {
        return LstOutgoingShipments;
    public List <Event_Equipment__c> getLstIncomingShipments() {
        return LstIncomingShipments;
    string CurrentUserAccount='';
    public PrintShipDepartedController()
    public void LoadData()
        userid = UserInfo.getUserId();
        LstCurrentUserAccount=[select id,Related_Account__c from user where id=:userid];
        If (LstCurrentUserAccount.size()>0)
        LstOutgoingShipments=[select id,
                            Equipment__r.name,  // this field is one which is not displaying  for some records
                            Shipment_Received__c from Event_Equipment__c 
                            where Ship_From_Vendor__c=:CurrentUserAccount and DAY_ONLY(Est_Departure_Time__c)>=:startdate1 and DAY_ONLY(Est_Departure_Time__c)<=:enddate1 ];

         LstIncomingShipments=[select id,
                            Shipment_Received__c from Event_Equipment__c 
                            where Ship_To_Vendor__c=:CurrentUserAccount and DAY_ONLY(Estimated_Arrival_Time__c)>=:startdate1 and DAY_ONLY(Estimated_Arrival_Time__c)<=:enddate1 ];





Hello Team,

 I have writtent a salesforce custom webserviec. web service accepts the inner class which is global and having some class members which are marked as webService. 

 But when pass parameter from salesforce to .Net only string variables are coming . All integer variables coming as null.

 Any help appricated.

Hi All,

    First I'm reading the all the salesforce Accounts in a selectoption dropdownlist.
based on the account selection i'm displaying the related contacts in other dropdownlist.
From the multiple contacts i'm selecting one contact how can i read that particular contact from
all contacts.

problem : how to filter selected contact from contact dropdownlist.

This is apex class:

   public with sharing class Account_Contact_Picklist{
    public String selectedAccId{get;set;}
    public String selectedConId{get;set;}
    public String firstname;
    public String lastname;
    public String email;
    public String company;
    public String mailingcity;
    public String mailingstate;
    public String mailingcountry;
    public String mobileno;
    public LightiningEd__Webinar_Attendees_Status__c login1;
    public Account_Contact_Picklist(ApexPages.StandardController controller){
       this.login1= (LightiningEd__Webinar_Attendees_Status__c)controller.getRecord();

    public List<System.SelectOption> accOptions{get;set;}
    public List<System.SelectOption> getAccountNames() {
                  List<System.SelectOption> accOptions= new List<System.SelectOption>();
                  accOptions.add( new System.SelectOption('','--Select--'));
                  for( Account acc : [select Id,name from Account] ){
                          accOptions.add( new System.SelectOption(String.valueOf(acc.Id),acc.name));
                 return accOptions;

           public List<System.SelectOption> getContactNames(){
                  System.debug('Entered ContactNames account id...........'+selectedAccId );
                  List<System.SelectOption> conOptions= new List<System.SelectOption>();
                  List<System.SelectOption> options = new List<System.SelectOption>();
                    if(selectedConId != null){
                           System.debug('Entered ContactNames contact id1...........'+selectedConId );
                       for(contact con :  [select Id,name,accountid,FirstName,LastName,email,MobilePhone,MailingCity,MailingState,MailingCountry
                                           from contact where accountid=:selectedAccId ]){
                              conOptions.add(new System.SelectOption(String.valueOf(con.Id),con.name));
                              if(conOptions.size() > 0){
                                  for(Contact con1 : [select Id,name,Account.Name,accountid,FirstName,LastName,email,
                                                      MobilePhone,MailingCity,MailingState,MailingCountry from contact where id=:selectedConId]){                                  
                                      firstname = con1.FirstName;
                                      System.debug('Entered ContactNames contact id...........'+firstname);
                                      lastname= con1.LastName;
                                      email = con1.Email;
                                      System.debug('email:::'+email );                                                     
                                      company = con1.Account.Name;
                                      System.debug('company:::'+company );                                                     
                                      mailingcity = con1.MailingCity;
                                      System.debug('mailingcity:::'+mailingcity );
                                      mailingstate = con1.MailingState;
                                      System.debug('mailingstate:::'+mailingstate );
                                      mailingcountry = con1.MailingCountry;
                                      System.debug('mailingcountry:::'+mailingcountry );
                                      mobileno = con1.MobilePhone;
                                      System.debug('mobileno:::'+mobileno );
                        conOptions.add( new System.SelectOption('--None--','--None--'));
                   return conOptions;

Thanks In Advance
Hi All,

Can someone please let me know how can I seperate data received from a query into different tables in my vf page based on the value of a field being fetched?

latest__c is rollup summary field = max(opportunity).This trigger is mapping latest opportunity amount into account field (acc.opty_amount__c).
trigger latest on Account (after update)  {    
  {    set<id> acctid =new set<id>();    
  list<account> accnt=new list<account>();  
  for(account acc:trigger.new)  
  {       acctid.add(acc.id);           }          
  for(account acc : [select id,name,opty_amount__c,latest__c(select id,amount,CreatedDate from opportunities) from account where id  in:acctid])    {    list <opportunity> oppo = acc.opportunities;    
for(opportunity op:oppo)   
 {    if(acc.latest__c == op.CreatedDate)    
      {    acc.opty_amount__c=op.amount;  
 update accnt;  
private class UpdateAccount_Test
{  public static testMethod void TestUpdateAccount() 
  {        Account acc = new Account();           
         acc.Name = 'Test';              
         insert acc;         
         opportunity oppo = new opportunity();          
         oppo.accountid  =acc.id;     
         oppo.amount = 50000.00;                        
        update acc;    
Hello there,

I am creating 2 pablock section . which display data with checkbox's and select all check box for each section .
when I am selecting top section select all chekbox it is also selecting below check checkbox data and If  i am using mutilple object getting too many quiry error also.
below is the class and vf page. can any one please solve this issue. an

public class Checkbox_Class

    List<accountwrapper> accountList = new List<accountwrapper>();
    List<accountwrapper_Two> accountList2 = new List<accountwrapper_Two>();
    List<Account> selectedAccounts = new List<Account>();

    public List<accountwrapper> getAccounts()
        for(Account a : [select Id, Name, AccountNumber, Phone from Account ])
        accountList.add(new accountwrapper(a));
        return accountList;
     public List<accountwrapper_Two> getAccounts2()
        for(Account a : [select Id, Name, AccountNumber, Phone from Account ])
        accountList2.add(new accountwrapper_Two(a));
        return accountList2;

    public PageReference getSelected()
        for(accountwrapper accwrapper : accountList)
        if(accwrapper.selected == true)
        return null;
      public PageReference getSelected2()
        for(accountwrapper_Two accwrapper2 : accountList2)
        if(accwrapper2.selected == true)
        return null;

    public List<Account> GetSelectedAccounts()
        return selectedAccounts;
        return null;

    public class accountwrapper
        public Account acc{get; set;}
        public Boolean selected {get; set;}
        public accountwrapper(Account a)
            acc = a;
            selected = false;
     public class accountwrapper_Two
        public Account acc{get; set;}
        public Boolean selected {get; set;}
        public accountwrapper_Two(Account a)
            acc = a;
            selected = false;
vf page

<!-- http://tablesorter.com/docs/-->
<apex:page controller="Checkbox_Class" Tabstyle="Account">
    <apex:includeScript value="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js" />
    <apex:includeScript value="//cdnjs.cloudflare.com/ajax/libs/jquery.tablesorter/2.17.8/js/jquery.tablesorter.min.js" />
    <apex:stylesheet value="//cdnjs.cloudflare.com/ajax/libs/jquery.tablesorter/2.17.8/css/theme.blue.css" />

    <apex:form >
        <apex:pageBlock Title="Accounts with CheckBoxes">
            <apex:pageBlockSection Title="List of Available Accounts">
                <apex:dataTable value="{!accounts}" var="a" columnswidth="50px,50px" cellpadding="4" border="1" id="accsTable" styleclass="tablesorter">
                    <apex:column >
                        <apex:facet name="header"> <apex:inputCheckbox >
                            <apex:actionSupport event="onclick" action="{!GetSelected}" onsubmit="checkAll(this)" reRender="Selected_PBS"/>
                        <apex:inputCheckbox value="{!a.selected}" id="checkedone">
                        <apex:actionSupport event="onclick" action="{!GetSelected}" rerender="Selected_PBS"/></apex:inputCheckbox>
                    <apex:column headervalue="Account Name" value="{!a.acc.Name}" />
                    <apex:column headervalue="Account Number" value="{!a.acc.AccountNumber}" />
                    <apex:column headervalue="Phone" value="{!a.acc.Phone}" />
            <apex:pageBlockSection Title="List of Available Accounts">
                <apex:dataTable value="{!accounts2}" var="a" columnswidth="50px,50px" cellpadding="4" border="1" id="accsTable" styleclass="tablesorter">
                    <apex:column >
                        <apex:facet name="header"> <apex:inputCheckbox >
                            <apex:actionSupport event="onclick" action="{!GetSelected2}" onsubmit="checkAll2(this)" reRender="Selected_PBS"/>
                        <apex:inputCheckbox value="{!a.selected}" id="checkedone2">
                        <apex:actionSupport event="onclick" action="{!GetSelected2}" rerender="Selected_PBS"/></apex:inputCheckbox>
                    <apex:column headervalue="Account Name" value="{!a.acc.Name}" />
                    <apex:column headervalue="Account Number" value="{!a.acc.AccountNumber}" />
                    <apex:column headervalue="Phone" value="{!a.acc.Phone}" />

        function checkAll(cb)
            var inputElem = document.getElementsByTagName("input");
            for(var i=0; i<inputElem.length; i++)
                inputElem[i].checked = cb.checked;
         function checkAll2(cb)
            var inputElem = document.getElementsByTagName("input");
            for(var i=0; i<inputElem.length; i++)
                inputElem[i].checked = cb.checked;
        $("[id$='accsTable']").tablesorter({theme: 'none', dateFormat : "dd/mm/yyyy"});

  • February 02, 2018
  • Like
  • 0
I am not a developer but I am supposed to trouble shoot this apex trigger error. Can someone help let me know what I need to change in the code to fix it? 

Error:Apex trigger RHX_Turbine_Config caused an unexpected exception, contact your administrator: RHX_Turbine_Config: execution of AfterUpdate caused by: System.NullPointerException: Attempt to de-reference a null object: Class.rh2.AggregateFunctionWorker.handleMultipicklistValues: line 23, column 1


1 trigger RHX_Turbine_Config on Turbine_Config__c
2    (after delete, after insert, after undelete, after update, before delete) {
3     Type rollClass = System.Type.forName('rh2', 'ParentUtil');
4  if(rollClass != null) {
5   rh2.ParentUtil pu = (rh2.ParentUtil) rollClass.newInstance();
6   if (trigger.isAfter) {
7     pu.performTriggerRollups(trigger.oldMap, trigger.newMap, new String[]{'Turbine_Config__c'}, null);
8       }
9    }


I would to know the community opinion if there is any DML operation occurring within the for loop:

//Build the share for each project and each member
for(Id projectId :membersByProjectIds.keySet())
    if(Schema.Project__c.sObjectType != projectId.getSobjectType())

    //Get the list of members for this project
    Set<Id> memberIds = membersByProjectIds.get(projectId);

    if(memberIds != null && memberIds.size() > 0)
        //Iterate the list of members
        for(Id memberId :memberIds)
            //Test for ID injection
            if(Schema.User.sObjectType != memberId.getSobjectType() && Schema.Group.sObjectType != memberId.getSobjectType())

            //Create a share permission record using manager
            Sobject sob = SharePermissionManager.createShareRecord(ConstantHelper.PROJECT_SHARE_OBJECT_NAME, projectId, memberId, permissionAccess, ConstantHelper.PROJECT_SHARE_REASON);

            //Control the result
            if(sob != null)
                //Add the record to the result list
                projectShareList.put(i, sob);


public static SObject createShareRecord(String objectName, Id parentId, Id userId, String accessLevel, String rowCause)
    //Control parameter
    if(String.isBlank(objectName) || parentId == null || userId == null || String.isBlank(rowCause) || String.isBlank(accessLevel))
        return null;
    //Test the accesslevel
    if(!accesslevel.equals(ConstantHelper.SHARE_ACCESS_LEVEL_READ) && !accesslevel.equals(ConstantHelper.SHARE_ACCESS_LEVEL_EDIT))
        return null;

    Schema.SObjectType shareType = Schema.getGlobalDescribe().get(objectName);

    //Control the return type
    if(shareType == null)
        return null;

    //Instantiate the Share record
    SObject shareRecord = shareType.newSObject();

    //Set each field of the Share record
    shareRecord.put(ConstantHelper.SHARE_PARENTID_COLUMN, parentId);
    shareRecord.put(ConstantHelper.SHARE_USERORGROUPID, userId);

    //Set the accessLevel
    shareRecord.put(ConstantHelper.SHARE_ACCESSLEVEL_COLUMN, accessLevel);
    shareRecord.put(ConstantHelper.SHARE_ROWCAUSE_COLUMN, rowCause);
    //Return the record
    return shareRecord;

Thanks devs :)
  • August 22, 2017
  • Like
  • 0
Hi all,

I would need that if a user select a piclist field value, another text field can´t be blank.

Here is my code. Any help, please?

ISPICKVAL( Status  , "Unqualified"),
 NOT (ISBLANK( ReasonRejectedByCommercialPlanning__c ))

  • February 10, 2017
  • Like
  • 1
Hello all, I have the following code to roll-up summary products name to an opportunity text-long field, I need a summary of purchased products separated by commas.
Everything runs good with no errors, however I get no results, nothing happens, can you please take a look and help me?

trigger OppProductsTrigger on OpportunityLineItem (after delete, after insert, after update) {

    // fires after both insert and update
    if((Trigger.isInsert || Trigger.isUpdate) && Trigger.isAfter){

      // find the ids of all opps that were affected
      Set<Id> oppIds = new Set<Id>();
      for (OpportunityLineItem ar : [select Id, name, OpportunityId from OpportunityLineItem 
        where Id IN :Trigger.newMap.keySet()])

      // process the opps  

    // fires when records are deleted. may want to do undelete also?
    } else if(Trigger.isDelete && Trigger.isAfter){

      // find the ids of all opps that were affected
      Set<Id> oppIds = new Set<Id>();
      for (ID id : Trigger.oldMap.keySet())

      // process the opps



public with sharing class OppProductsTriggerHandler {

  public static void ProcessProductsAsync(Set<ID> oppIds){

    // holds a map of the opp id and comma separated products to build
    Map<Id, String> oppProductMap = new Map<Id, String>();

    // get ALL of the products for all affected opps so we can build
    List<OpportunityLineItem> oppProducts = [select id, name, OpportunityId 
      from OpportunityLineItem 
      where OpportunityId IN :oppIds order by Name];

    for (OpportunityLineItem ar : oppProducts) {
      if (!oppProductMap.containsKey(ar.OpportunityId)) {
        // if the key (opp) doesn't exist, add it with product name
      } else {
        // if the key (opp) already exist, add ", product-name"
        oppProductMap.put(ar.OpportunityId,oppProductMap.get(ar.OpportunityId) + 
          ', ' + ar.Name);

    // get the opps that were affected
    List<Opportunity> opps = [select id from Opportunity where Id IN :oppIds];

    // add the comma separated list of regions
    for (Opportunity a : opps)
      a.Products_Purchased__c = oppProductMap.get(a.id);

    // update the opps
    update opps;



Thank you!
Hi all,

I am trying to write a trigger that is 2-fold in purpose.  The context is we have 2 different types of opportunity record types (for existing business): Renewal and Retention.  Renewal is informal when we are proactively trying to extend a contract and Retention is more formal when the client has issued a Request for Proposal from multiple vendors.  It is possible that we have a renewal that will change to retention.  In that case, what I am trying to do is:
1 - Clone the record (when stage = '6 Going to Bid') but change the record type to Retention and set stage = '3 Analysis'
2 - Update the original record (the one whose stage = '6 Going to Bid') with a link to the new record (I have created a custom lookup field labeled 'Related Retention Opportunity').

I have written a trigger and can get the first part to work but am getting stuck on the second requirement.  I think it is because of the criteria when to run the trigger (before update, after insert, etc.).  I have copied my trigger below but commented out where it is not working at the end.  Any help would be greatly appreciated.  THANK YOU!!

trigger CloneOpportunity on Opportunity (before update, after insert) {

    for(Opportunity o : trigger.new){
        if(o.StageName == '6 Going to Bid'){
            Opportunity opp = [SELECT Id, Name, Related_Retention_Opportunity__c, AccountId, CloseDate, Type, No_of_Buses__c, Current_Contractor__c, NEC_Company__c, LeadSource, NEC_Contract__c, No_Bid_Decision_Made__c, OwnerId, CampaignId, Up_or_Out__c, Total_Routes_out_for_bid__c, Market_Cap__c, Description, Contract_Start_Date__c, Contract_End_Date__c, Contract_Extension_Date__c, Reason_Win_Loss_NoBid_Note__c, Account_Management__c, Priority__c, Business_Analysts__c, Bid_Coordinator__c, Comments_Update__c, Budgeted_Increase__c, Approved_Increase__c, Actual_Increase__c, Budgeted_Bus_Count__c, Approved_Bus_Count__c, Awarded_Bus_Count__c, Amount, X5_YR_OM__c, YR_1_Capex__c, New_Bus_CapEx_Yr1__c, District_Fleet_CapEx_Yr1__c, Cascade_Fleet_Value_Yr1__c, Other_Equip_CapEx_Yr1__c, ROCE__c, IRR__c, NPV__c, Final_Model_Detail__c, Op_Lease_Purchase__c, of_Op_Leases__c, Avg_Annual_Op_Lease_Cost__c, Winning_Contractor__c, No_Bid_Reason__c, Difference_from_low_bidder__c, Competitor_Pricing_Not_Available__c, Other_Bidding_Companies__c, Pricing__c, Reason_Win_Loss__c, STA_price_change_Yr_1__c, Difference_from_First_Student__c, Illinois_Central_s_price_change_Yr_1__c, Cook_IL_price_change_Yr_1__c, Regional_Co_price_change_Yr_1__c, Regional_Co_2_price_change_Yr_1__c
                               FROM Opportunity WHERE Id = :o.Id];
            Opportunity OClone = new Opportunity();
            OClone.Name = 'Going to Bid - ' + opp.Name;
            OClone.RecordTypeId = '012A0000000VkfM';
            OClone.AccountId = opp.AccountId;
            OClone.CloseDate = opp.CloseDate;
            OClone.StageName = '3 Analysis';
            OClone.Type = opp.Type;
            OClone.No_of_Buses__c = opp.No_of_Buses__c;
            OClone.Current_Contractor__c = opp.Current_Contractor__c;
            OClone.NEC_Company__c = opp.NEC_Company__c;
            OClone.LeadSource = opp.LeadSource;
            OClone.NEC_Contract__c = opp.NEC_Contract__c;
            OClone.No_Bid_Decision_Made__c = opp.No_Bid_Decision_Made__c;
            OClone.OwnerId = opp.OwnerId;
            OClone.CampaignId = opp.CampaignId;
            OClone.Up_or_Out__c = opp.Up_or_Out__c;
            OClone.Total_Routes_out_for_bid__c = opp.Total_Routes_out_for_bid__c;
            OClone.Market_Cap__c = opp.Market_Cap__c;
            OClone.Description = opp.Description;
            OClone.Contract_Start_Date__c = opp.Contract_Start_Date__c;
            OClone.Contract_End_Date__c = opp.Contract_End_Date__c;
            OClone.Contract_Extension_Date__c = opp.Contract_Extension_Date__c;
            OClone.Priority__c = opp.Priority__c;
            OClone.Business_Analysts__c = opp.Business_Analysts__c;
            OClone.Bid_Coordinator__c = opp.Bid_Coordinator__c;
            OClone.Comments_Update__c = opp.Comments_Update__c;
            OClone.Budgeted_Increase__c = opp.Budgeted_Increase__c;
            OClone.Approved_Increase__c = opp.Approved_Increase__c;
            OClone.Actual_Increase__c = opp.Actual_Increase__c;
            OClone.Budgeted_Bus_Count__c = opp.Budgeted_Bus_Count__c;
            OClone.Approved_Bus_Count__c = opp.Approved_Bus_Count__c;
            OClone.Awarded_Bus_Count__c = opp.Awarded_Bus_Count__c;
            OClone.Amount = opp.Amount;
            OClone.Reason_Win_Loss_NoBid_Note__c = opp.Reason_Win_Loss_NoBid_Note__c;
            OClone.X5_YR_OM__c = opp.X5_YR_OM__c;
            OClone.YR_1_Capex__c = opp.YR_1_Capex__c;
            OClone.New_Bus_CapEx_Yr1__c = opp.New_Bus_CapEx_Yr1__c;
            OClone.District_Fleet_CapEx_Yr1__c = opp.District_Fleet_CapEx_Yr1__c;
            OClone.Cascade_Fleet_Value_Yr1__c = opp.Cascade_Fleet_Value_Yr1__c;
            OClone.Other_Equip_CapEx_Yr1__c = opp.Other_Equip_CapEx_Yr1__c;
            OClone.ROCE__c = opp.ROCE__c;
            OClone.IRR__c = opp.IRR__c;
            OClone.NPV__c = opp.NPV__c;
            OClone.Final_Model_Detail__c = opp.Final_Model_Detail__c;
            OClone.Op_Lease_Purchase__c = opp.Op_Lease_Purchase__c;
            OClone.of_Op_Leases__c = opp.of_Op_Leases__c;
            OClone.Avg_Annual_Op_Lease_Cost__c = opp.Avg_Annual_Op_Lease_Cost__c;
            OClone.Winning_Contractor__c = opp.Winning_Contractor__c;
            OClone.Reason_Win_Loss__c = opp.Reason_Win_Loss__c;
            OClone.No_Bid_Reason__c = opp.No_Bid_Reason__c;
            OClone.Difference_from_low_bidder__c = opp.Difference_from_low_bidder__c;
            OClone.Competitor_Pricing_Not_Available__c = opp.Competitor_Pricing_Not_Available__c;
            OClone.Other_Bidding_Companies__c = opp.Other_Bidding_Companies__c;
            OClone.Pricing__c = opp.Pricing__c;
            OClone.Reason_Win_Loss__c = opp.Reason_Win_Loss__c;
            OClone.STA_price_change_Yr_1__c = opp.STA_price_change_Yr_1__c;
            OClone.Difference_from_First_Student__c = opp.Difference_from_First_Student__c;
            OClone.Illinois_Central_s_price_change_Yr_1__c = opp.Illinois_Central_s_price_change_Yr_1__c;
            OClone.Cook_IL_price_change_Yr_1__c = opp.Cook_IL_price_change_Yr_1__c;
            OClone.Regional_Co_price_change_Yr_1__c = opp.Regional_Co_price_change_Yr_1__c;
            OClone.Regional_Co_2_price_change_Yr_1__c = opp.Regional_Co_2_price_change_Yr_1__c;
            OClone.Account_Management__c = opp.Account_Management__c;
            insert OClone;
 /*         IF(trigger.isafter){
             opp.Related_Retention_Opportunity__c = OClone.Id;
             update opp;     

I was frustrated with the various answers I had found as to how to get a complete mapping of dependent picklist values, so I combined a few different posts into a solution that works, is efficient, and does not require a web service call. This only works for single level dependencies,

I created a class called Utilities that holds the method GetDependentOptions for getting dependent picklist values. There is also a method called GetPickListValues to retrieve values for a simple picklist. The method FirstControllingValueFor is used to do a reverse lookup given a child value to find the first controlling value that the child is valid for.

public class Utilities {
    public static List<String> GetPickListValues(String object_name, String field_name, String first_val) {
        SObjectType objectType = Schema.getGlobalDescribe().get(object_name);
        List<String> options = new List<String>(); //new list for holding all of the picklist options
        if (first_val != null) { //if there is a first value being provided
            options.add(first_val); //add the first option
        List<String> classes = new List<String>();
        List<Schema.DescribeSObjectResult> results = Schema.describeSObjects(classes);
        Schema.DescribeSObjectResult sobject_describe = results[0];
        Map<String, Schema.SObjectField> field_map = sobject_describe.fields.getMap(); //get a map of fields for the passed sobject
        if (null != field_map) {
            Schema.SObjectField fs = field_map.get(field_name);
            Schema.DescribeFieldResult dsr = fs.getDescribe();
            if (null != dsr) {
                List<Schema.PicklistEntry> pick_list_values = dsr.getPickListValues(); //grab the list of picklist values for the passed field on the sobject
                if (null != pick_list_values) {
                    for (Schema.PicklistEntry a : pick_list_values) { //for all values in the picklist list            
        return options; //return the List
    private static Map<String, Integer> base64Vals = null;
    private static List<Integer> ConvertB64ToInts(string b64Str) {
        if (base64Vals == null) {
            base64Vals = new Map<String, Integer> {
        List<Integer> ints = new List<Integer>();
        for (Integer idx = 0; idx< b64Str.length(); ++idx) {
            String c = String.fromCharArray(new List<Integer> { b64Str.charAt(idx)});
        return ints;

    private class TPicklistEntry{
        public string active {get;set;}
        public string defaultValue {get;set;}
        public string label {get;set;}
        public string value {get;set;}
        public string validFor {get;set;}
        public TPicklistEntry(){}

    public static Map<String,List<String>> GetDependentOptions(String pObjName, String pControllingFieldName, String pDependentFieldName) {
        Map<String,List<String>> mapResults = new Map<String,List<String>>();

        //verify/get object schema
        Schema.SObjectType pType = Schema.getGlobalDescribe().get(pObjName);
        if ( pType == null ) return mapResults;
        Map<String, Schema.SObjectField> objFieldMap = pType.getDescribe().fields.getMap();

        //verify field names
        if (!objFieldMap.containsKey(pControllingFieldName) || !objFieldMap.containsKey(pDependentFieldName)) return mapResults;

        //get the control & dependent values
        List<Schema.PicklistEntry> ctrl_ple = objFieldMap.get(pControllingFieldName).getDescribe().getPicklistValues();
        List<Schema.PicklistEntry> dep_ple = objFieldMap.get(pDependentFieldName).getDescribe().getPicklistValues();

        //initialize results mapping
        for(Integer pControllingIndex=0; pControllingIndex < ctrl_ple.size(); pControllingIndex++) {
            mapResults.put( ctrl_ple[pControllingIndex].getLabel(), new List<String>());

        //serialize dep entries
        List<TPicklistEntry> objDS_Entries = new List<TPicklistEntry>();
        objDS_Entries = (List<TPicklistEntry>)JSON.deserialize(JSON.serialize(dep_ple), List<TPicklistEntry>.class);

        for (TPicklistEntry objDepPLE : objDS_Entries){
            List<Integer> bitValues = ConvertB64ToInts(objDepPLE.validFor);

            Integer bitMask = 32; // Ignore highest 2 bits
            Integer intIndex = 0;
            Integer bitIdx = 0;
            for (Integer numBits = bitValues.size() * 6; numBits > 0; --numBits) {
                Integer bits = bitValues[intIndex];
                if ((bits & bitMask) == bitMask) {
                    mapResults.get( ctrl_ple[bitIdx].getLabel() ).add( objDepPLE.label );
                bitMask = bitMask >>> 1;

                if (bitMask == 0) {
                    bitMask = 32;
                    intIndex = intIndex + 1;
        return mapResults;
    public static String FirstControllingValueFor(String pObjName, String pControllingFieldName, String pDependentFieldName, String childValue) {
        Map<String,List<String>> mappedItems = GetDependentOptions(pObjName, pControllingFieldName, pDependentFieldName);
        for (String key : mappedItems.keySet()) {
            List<String> items = mappedItems.get(key);
            Set<String> itemSet = new Set<String>(items);
            if (itemSet.contains(childValue)) {
                return key;
        return null;

Hi All, 

I'm currently writing a test batch class and I'm scratching my head trying to figure out why my SOQL query is not returning the requested fields:

Here's the condensed version of the class:

@isTest static void testTaskUpdateActivityInfoBatchTest() {
		DateTime olderTime = system.now().addMinutes(-5);
		DateTime newestTime = system.now().addMinutes(-3);
		//Pull a random active sales guy
		User testUser = [SELECT Id FROM User WHERE ProfileId ='00e30000001Ghun' AND IsActive = true LIMIT 1];
		List<Task> tasks = new List<Task>();

		//Create test Leads
		Lead[] testLeads = new Lead[]{};
		for(Integer i = 0;  i < 10; i++) {
			testLeads.add(new Lead(LastName = 'kktest-'+i, Company='test', Date_Requested_Sales_Follow_Up__c = system.now()));
		insert testLeads;

		//Create 60 tasks associated to these leads
		for(Integer i = 0; i < 30; i++) {
			Integer j = math.mod(i, 10);
			tasks.add(new Task(OwnerId = testuser.Id, Subject = 'Apex Test '+i, ActivityDate = system.today(), Status = 'Completed', WhoId = testLeads[j].id, In_Queue_for_Processing__c = true, Date_Time_Processed__c = newestTime, Prospecting_call_affirmative__c = true, Prospecting_call_connected__c = true, Email_Connection__c = true));
			tasks.add(new Task(OwnerId = testuser.Id, Subject = 'Apex Test '+i, ActivityDate = system.today(), Status = 'Completed', WhoId = testLeads[j].id, In_Queue_for_Processing__c = true, Date_Time_Processed__c = olderTime, Prospecting_call_affirmative__c = true, Prospecting_call_connected__c = true, Email_Connection__c = true));
		system.assertEquals(60, tasks.size());

			Database.executeBatch(new TaskUpdateActivityInfoBatch());

		List<Lead> leadsToCheck = [SELECT Id, First_Activity_Id__c, First_Activity_Date_Time__c, First_Connection_Date_Time__c, Last_Connection_Date_Time__c, Second_to_Last_Activity_Date_Time__c, Last_Activity_Date_Time__c FROM Lead WHERE Id =:testLeads];
		system.debug('leadsToCheck: ' + leadsToCheck);
		for(Lead lead : leadsToCheck) {
			//Cannot assert Id with this set up
			system.assertEquals(olderTime, lead.First_Activity_Date_Time__c);
			system.assertEquals(olderTime, lead.First_Connection_Date_Time__c);
			system.assertEquals(newestTime, lead.Last_Connection_Date_Time__c);
			system.assertEquals(olderTime, lead.Second_to_Last_Activity_Date_Time__c);
			system.assertEquals(newestTime, lead.Last_Activity_Date_Time__c);

The last query

List<Lead> leadsToCheck = [SELECT Id, First_Activity_Id__c, First_Activity_Date_Time__c, First_Connection_Date_Time__c, Last_Connection_Date_Time__c, Second_to_Last_Activity_Date_Time__c, Last_Activity_Date_Time__c FROM Lead WHERE Id =:testLeads];

When I observe it in the debug logs is only returning the Ids:

16:22:42:080 USER_DEBUG [74]|DEBUG|leadsToCheck: (Lead:{Id=00Q8A000001HaZ6UAK}, Lead:{Id=00Q8A000001HaZ7UAK}, Lead:{Id=00Q8A000001HaZ8UAK}, Lead:{Id=00Q8A000001HaZ9UAK}, Lead:{Id=00Q8A000001HaZAUA0}, Lead:{Id=00Q8A000001HaZBUA0}, Lead:{Id=00Q8A000001HaZCUA0}, Lead:{Id=00Q8A000001HaZDUA0}, Lead:{Id=00Q8A000001HaZEUA0}, Lead:{Id=00Q8A000001HaZFUA0})

Why are the other fields not returning and how do I fix it? 


I'm experiencing  this into SandBox...if i understand well, this is not an issue but an expecting behavior:

This is expected behavior. "Text/Image" fields on quote templates are not supported in developer and developer-pro sandboxes. They are only supported in Production and Full-copy sandboxes.

Ok, but how can i reset this ?
even with Admin right i cannot edit the Template to remove the "Text/Image" fields...

Many thanks for your assistance
I am trying to change my date field from the default (MM)(DD)(YYYY) to (DD)(MMM)(YYYY). This is to assist in european clients in month designation so that the day is aparent(2) month(3) and year(4). 
Thanks for the help!
I have a customer requirement for mys users to have the ability to upload multiple products by way of an external text file to the quote line items. 
This would be part of the user experience each time they work on an opportunity and not an admin feature or use the data loader. I cannot think of a method of doing this. Any ideas ?

I have several opportunities, which all have a record field assigned to a specific project. The project, which they are assigned to is mapped through a look up field. My goal is to create a trigger, which sums every opportunity's CS_Capacity_Allocated__C field (this is the individual's capacity reservation) that is assigned to the same project and create a total capacity value to be mapped into a newly created CS_Reserved_Capacity__C field (this is all the individual's capacity reservations added together). One could then view the total project capacity on each opportunity.

A Roll Up Summary would be ideal for this situation; however I cannot establish a Master-Detail relationship on the opportunity with the project object, nor can I establish a Roll Up Summary on the project because the "Summarized Object" drop-down menu does not allow me to acces the opportunities option. 

This has left me, from what I believe, with the need to develop a trigger. I have authored the following code; however it has confronted me with several error messages, which I have been fixing along the way. It has just recently sent me the following error message 

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

I cannot seem to work this one out. The code is as follows:
Trigger addReservedCapacity on opportunity (before insert, before update) {

set <string> projectNames = new Set <string>(); 
List <decimal> projectAllocations = new List <decimal>( );
decimal reservedCapacity = 0;
integer i = 0;

// instantiate the variables.

    for (opportunity opportunity: trigger.new) {
        If (opportunity.assigned_cs_project__c != null) {
            projectNames.add (opportunity.assigned_cs_project__c);}

// if the opportunity has an assigned project add the name of the project to a set.

    if (projectNames.size( ) > 0 ) {
        map <string, decimal> mapNames = new map <string, decimal> ( );
        for (opportunity obj : [SELECT Id, name, assigned_cs_project__c, cs_capacity_allocated__c FROM opportunity WHERE assigned_cs_project__c IN : projectNames] ) {

// create a map and query the opportunity records looking for records that have matching project assignments to the created set. 
// return the found record’s id, name, project assignment and reserved capacity
// put the project assignment into the map as the key and the reserved capacity as the value.

    projectAllocations = mapNames.values();

// set the projectAllocations list to the reserved capacity values in the map.

    for(i = 0; i <= mapNames.size(); i++){

        reservedCapacity = reservedCapacity  + projectAllocations.get(i);


// sum the lines of the list

    opportunity.cs_reserved_capacity__c = reservedCapacity;

// set the CS Reserved Capacity field in the Projects object to the calculated reserved capacity.


If anybody could help I would really appreciate it. Regardless, thank you for your time in reading this.

All the best.


I have query that need to pull the Username from Users table but I am currently on Case object and the user ID is in opportunity.
This is working, but I want to show Approval name instead of user id (Opportunity__r.PR_Approval_level__c).  This should be the setup Master is Case Object.

Can you please help me?
SELECT Account_Owner__c, CaseNumber, 
FROM Case WHERE Id = '500M0000006Acvv'

Thanks in advance,
I have a visualforce page ,
1)Created a button on Contact Page Layout
onclick of new button i need to pull case feilds once they click save a case record should be created and attached to contact Record

Below is the Visualforce Page
<apex:page standardController="Contact" extensions="GlobalComplaintExt" tabStyle="Case" id="myPage" showHeader="False">
<apex:form id="myForm">
        <apex:pageBlock id="block1" title="Complaint" >
        <apex:outputPanel >
            <apex:pageBlockSection title="Complaint " collapsible="true" id="section1" >
                <apex:outputField value="{!contact.Name}"/>
                <apex:outputField value="{!contact.AccountId}" label="Account Name"/>
               <apex:inputfield value="{!com.Potential_Injury__c}" required="true"/>
               <apex:inputfield value="{!com.Date_Received__c}"/>
               <apex:inputfield value="{!com.Complaint_Source__c}" />
               <apex:inputfield value="{!com.Origin}" required="true"/>
<apex:commandbutton action="{!SaveItem}" value="Start " />

Whenever the user clicks SaveItem the cases records should be created.
global class GlobalComplaintExt
        private List<String> fieldErrors = new List<String>();
        public final Contact ContactName;
        private string contactID = '';
        private string complaintID = '';
        private string productID = '';
        private string prodseg = '';
        private string prodsubseg = '';
        public Integer icounter {get;set;}
        public Contact con {get;set;}
        public Account Acct {get;set;}
        public Case com {get;set;}
        public Product2 pro {get;set;}
        private Questions_and_Answers_Custom__c questions;
        private Questions_and_Answers_Custom__c answers;
        public List<Questions_and_Answers_Custom__c> questionslist;
        public List<Questions_and_Answers_Custom__c> answerslist;
        Case Caseinsert= new Case();
  public GlobalComplaintExt(ApexPages.StandardController controller)
     con = [select  Id, Name from Contact where id = :ApexPages.currentPage().getParameters().get('id')];         
     Caseinsert = new Case(ContactId = con.Id);
        Used to Save the values into the Case Object

  public pageReference SaveItem()
     CaseInsert.Associated_Product__c =com.Associated_Product__c;
     CaseInsert.Complaint_Lot2__c =com.Complaint_Lot__c;
     CaseInsert.Complaint_Lot3__c =com.Complaint_Lot3__c;
     insert CaseInsert;
     PageReference pageRef = new PageReference('/t');
     return pageRef;
       insert com;
       return null;

   public pageReference cancelAction()
         return null;


System.NullPointerException: Attempt to de-reference a null object
Error is in expression '{!SaveItem}' in component <apex:commandButton> in page globalcomplaint: Class.GlobalComplaintExt.SaveItem: line 77, column 1
Class.GlobalComplaintExt.SaveItem: line 77, column 1

Can you help me to fix this


I am trying to use a custom button w/ JavaScript to execute a record update for users who would otherwise not be able to edit the record, due to permissions and record sharing.  However, when I click the button as a user without the proper edit rights on the record, nothing happens (except the page reload).  It works just fine when logged in as SysAdmin.
Is it possible to get the javascript to execute without regard to the logged in user's edit rights on the record?  If so, what am I missing?  Code is below:

var newRecords = []; 
var c=new sforce.SObject("Contact"); 

Today we’re excited to announce the new Salesforce Developers Discussion Forums. We’ve listened to your feedback on how we can improve the forums.  With Chatter Answers, built on the Salesforce1 Platform, we were able to implement an entirely new experience, integrated with the rest of the Salesforce Developers site.  By the way, it’s also mobile-friendly.

We’ve migrated all the existing data, including user accounts. You can use the same Salesforce account you’ve always used to login right away.  You’ll also have a great new user profile page that will highlight your community activity.  Kudos have been replaced by “liking” a post instead and you’ll now be able to filter solved vs unsolved posts.

This is, of course, only the beginning  and because it’s built on the Salesforce1 Platform, we’re going to be able to bring you more features faster than ever before.  Be sure to share any feedback, ideas, or questions you have on this forum post.

Hats off to our development team who has been working tirelessly over the past few months to bring this new experience to our community. And thanks to each of you for helping to build one of the most vibrant and collaborative developer communities ever.

Hi All,


How can I create a __share for a custom object.


For Ex: I have created a custom object named  MyObject and how can I create a share object for it named MyObject__Share.


Note: I have the permission Manage Users as described in the docs.


Any help is appreciated.



  • November 27, 2013
  • Like
  • 1