• Jim Jam
  • SMARTIE
  • 798 Points
  • Member since 2013

  • Chatter
    Feed
  • 25
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 0
    Questions
  • 136
    Replies
To preface, I have very little to no development skills, and unfortunately, the org I inherited as admin is very apex-heavy. I need to make an edit to an apex class (sandbox first of course), but am unable to due to it being part of a scheduled job. We have about a dozen scheduled jobs, all of which are vaguely named. Is there a way I can tell which apex class is running which scheduled job? Of the scheduled jobs, only two of them give me the "manage" option. (see below)
User-added image
I am trying to create a visualforce page that allows people to edit many child objects from the parent object.  In this instance, our org will have a Project (Project__c) as the parent and then many Work Orders (work_order__c) related to that Project.  Since most projects will have around 200 Work Orders, it would be cumbersome for somebody to edit them one by one.  

The error I keep getting is: Unkown property 'Project__cStandardController.Work_Orders'.  I am not a developer so any help would be much appreciated.  Thank you!

Here is my controller:
public class workorderController {
  
  // Constructor
 public workorderController(ApexPages.StandardController controller) {
  this.proj = (Project__c)controller.getSubject();
  
     this.delivers = [ SELECT 
      d.SystemModstamp, d.Name, 
      d.LastModifiedDate, d.LastModifiedById, d.LastActivityDate, 
      d.IsDeleted, d.Id,  d.CreatedDate, d.CreatedById, 
      d.AFE__c, d.Service__c, d.Project_Manager__c, d.work_order_status__c, 
      d.Service_provider__c 
      FROM 
      Work_order__c d 
      WHERE 
      d.AFE__c = :proj.id ];
 }
 
 // Action Method called from page button
 public pagereference saveChanges() { 
  upsert this.delivers;
  return null;
 }
 
 // Action Method called from page link
 public pagereference newDeliverable() { 
  work_order__c d = new work_order__c();
  d.AFE__c =this.proj.id; 
  delivers.add( d );
  return null;
 }
 
 // public Getter to provide table headers 
 public string[] getheaders() { return new string [] 
  {'Name','Service','Work Order Status','Project Manager', 'Service Provider',
   'AFE' } ; }
 
 // public Getter to list project deliverables
 public work_order__c[] getWorkOrders() { 
  return this.delivers; 
 } 
 
 // class variables
 Project__c proj;
 work_order__c[] delivers; 
}

My VF Page:

<apex:page standardController="Project__c" extensions="workorderController">
 <style>
.pbBody td {
 border-color: #E3DEB8;
 border-style: none none solid;
 border-width: medium medium 2px;
 padding-bottom: 4px;
 padding-top: 4px;
 width: 85px;
}
.pbBody input   { width: 105px;}
.pbBody .nameColumn { width: 125px;}
.hdr     {;}
</style>
<apex:form>
 <apex:messages />

 <apex:sectionHeader title="Work Orders for" subtitle="{!Project__c.name}" />
 <apex:pageBlock title="Edit Work Orders">
  <apex:pageBlockButtons>
   <apex:commandButton action="{!saveChanges}" value="Save"
    rerender="main" status="ajaxStatus" />
   <apex:commandButton action="{!cancel}" value="Cancel" />
  </apex:pageBlockButtons>
  <apex:actionStatus id="ajaxStatus" startText="Updating Work Orders...">
   <apex:facet name="stop">
   <apex:outputPanel id="main">
    <table>
    <tr>
     <apex:repeat value="{!headers}" var="h">
      <td class="hdr">{!h}</td>
     </apex:repeat>
    </tr>

    <apex:repeat value="{!Work_Orders}" var="a">
     <tr>
      <td ><apex:inputField value="{!a.name}" /></td>
      <td><apex:inputField value="{!a.Service__c}" /></td>
      <td><apex:inputField value="{!a.Work_Order_Status__c}" /></td>
      <td><apex:inputField value="{!a.Project_Manager__c}" /></td>
      <td><apex:inputField value="{!a.Service_Provider__c}" /></td>
      <td><apex:inputField value="{!a.AFE__c}" /></td>
     </tr>
    </apex:repeat>
    </table>
   </apex:outputPanel>
   </apex:facet>
  </apex:actionStatus>
 </apex:pageBlock>
</apex:form>
</apex:page>
Object1 has lookup to user.
 
<apex:outputText value="{!name.User1}"/>

output is a format like 00523000000g0E8UUT

How can i get the user name out of it ?
 

  • February 27, 2015
  • Like
  • 0
I'm starting to learn Apex and working on basic triggers so apologies in advance if the code is bad.

Architecture: Parent: Opportunity; relevant fields = Draw_4__c (checkbox), Project_Stage__c (text) Child: Referral__c; relevant fields = Send_Email__c (checkbox), Status__c (text)

Referral__c is a junction object between Opportunity records. The purpose is to link one opportunity to another and say that this opportunity referred that opportunity.

On update of Opportunity, the code needs to always set Status__c = Project_Stage__c and only set Send_Email__c = TRUE if Draw_4__c = TRUE.

Right now, Send_Email__c is getting appropriately set but Status__c is not. I can tell that the problem is how I am trying to refer to the parent field (opportunity.project_stage__c). If I set Status__c = some text, such as 'Active', the trigger works as needed but if I set status__c = opportunity.project_stage__c, the field remains blank. I'm wondering if this has something to do with the fact that Referral is junction between two opportunity records.

Trigger:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
trigger UpdateReferral on Opportunity(after update) {

If(Trigger.isUpdate){

     Set<ID> ids = Trigger.newMap.keySet();
     list<Opportunity> updatedParents = [SELECT Id, 
                 (SELECT Id, Referred_Opportunity__c, Send_Email__c, Status__c 
                  from Referred_By__r ) FROM Opportunity
                 WHERE Id in :ids];
         List<Referral__c> childrenToUpdate = new List<Referral__c>();

         //Then loop through each parent object in updated parent
         for (Opportunity p : updatedParents) 
         { 
        if(p.Draw_4__c = TRUE){

                //and loop thru each kid in the child set}
               for(Referral__c kid : p.Referred_By__r) 
               { 
                         ///update logic from above
                             kid.Send_Email__c = True;
                             kid.Status__c = 'Active';
               childrenToUpdate.add(kid);
                }
                }
                else  {
           for(Referral__c kid2 : p.Referred_By__r) 
           {
               kid2.Status__c = 'Active';
               childrenToUpdate.add(kid2);
           }
{
        }}
       if( !childrenToUpdate.isEmpty())
       {
            update childrenToUpdate;
       }
}}
}

Thanks in advance for your help!
Hi All,
We created a custom Object CalendarEV, we want a new record for CalendarEV is created automatically  when a new event is created in Public Calendar. We created below trigger but got error message, please help.

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

trigger CalendarEV on Event (after insert) {
    List<Event> Events = new List<Event>();
   for (Event e : Trigger.new) {
           if (Event.Subject != null ) {
               CalendarEV__c C = new CalendarEV__c();
               CalendarEV__c.Name = Event.Subject; 
               CalendarEV__c.Location__c = Event.Location;
               CalendarEV__c.Description__c = Event.Description;
                       
              insert C;
        }
    }
   }
I have a trigger that's calling from a class, and I'm getting a NullPointerException on the first line of the 3rd method (List<Contact> constoupdate = [select Id, FACheckbox__c from Contact where Id in :Trigger.newMap.keySet()];). Anyone know why this is happening?

(Also, I know I probably have a recursion problem here, which I'm hoping to solve with a static variable - but one issue at a time!)

Trigger:
trigger TestTrigger on Contact (before insert, before update, after insert, after update) {
	if(Trigger.isBefore) {
    TriggerClass.MethodBeforeT();	
    }
    else if(Trigger.isAfter) {
    TriggerClass.MethodAfterT();
    }

TriggerClass.MethodLast();
    
}

Class:
public with sharing class TriggerClass {

public static void MethodBeforeT (){
	List<RecordType> type1 = [select Id from RecordType where Name = 'Type 1' and SobjectType = 'Contact' limit 1];
	List <RecordType> type2 = [select Id from RecordType where Name = 'Type 2' and SobjectType = 'Contact' limit 1];
	
	for (Contact cons :(List <Contact>) Trigger.new){
	if(cons.Checkbox__c = true && cons.RecordTypeId == type1[0].Id){
			cons.RecordTypeId = type2[0].Id;}
	}
	}
	
public static void MethodAfterT (){
	List<CustomE__c> customes = new List <CustomE__c>();
	List<Contact> constoupdate = [select Id, FirstName, LastName, Email, Checkbox__c from Contact where Id in :Trigger.newMap.keySet()];
	List<Contact> constoupdate2 = new List <Contact>();

	for (Contact c :constoupdate){
	if(c.Checkbox__c = true){
	CustomE__c e = new CustomE__c();
		e.Contact__c = c.Id;
		e.First_Name__c = c.FirstName;
		e.Last_Name__c = c.LastName;
		e.Email__c = c.Email;
	customes.add(e);
	constoupdate2.add(c);
	}}
	insert customes;
}

public static void MethodLast (){
	List<Contact> constoupdate = [select Id, Checkbox__c from Contact where Id in :Trigger.newMap.keySet()];
	List<Contact> constoupdate2 = new List <Contact>();
	
	for(Contact c :constoupdate){
		c.Checkbox__c = false;
		constoupdate2.add(c);}
		update constoupdate2;
}
}


Hi folks
       Can anyone tell me why the popup is not working properly??

Code
<apex:page >
    <script>
        function showSimpleDialog(){   
           var sd = new SimpleDialog("Test"+Dialogs.getNextId(), false);   
           sd.setTitle("Test Pop up");  
           sd.createDialog();  
           window.parent.sd = sd;  
           sd.setContentInnerHTML("<p align='center'><img src='/img/msg_icons/warning32.png' style='margin:0 5px;'/></p><p align='center'>This is awesome!</p><p align='center'><br /><button class='btn' onclick='window.parent.sd.hide(); return false;'>cancel</button></p>");   
           sd.show();  
         } 
    

    </script>
   
    <apex:form >
        <apex:outputLink onclick="showSimpleDialog()">
            click to see popup
        </apex:outputLink>
    </apex:form>
</apex:page>


Problem is  the popup window is visble for 1 sec after clicking the link??

Please Help!
Based on the documentation seen here (http://www.salesforce.com/us/developer/docs/apexcode/Content/connectAPI_enums.htm#FeedSortOrder_enum), ConnectApi.FeedSortOrder is a valid Apex Enum.  However when I try to save this simple class with v28.0 through v31.0, I get the followin error "Compilation error: Invalid type: ConnectApi.​FeedSortOrder".  Here is the Apex class to reproduce the error

public with sharing class scratch
{
    private ConnectApi.​FeedSortOrder fso = ConnectApi.​FeedSortOrder.LastModifiedDateDesc;
}

Chatter is enabled in this org and other ConnectApi.ChatterFeeds related classes are working.

It would appear that the Apex compiler doesn't recognize ConnectApi.​FeedSortOrder enum as a valid Apex object.
Can anyone help with my trigger. Im trying to do a data load to the object but keep getting this error. I cant seem to see why my trigger is having the issue i thought i bulkified it..

trigger mainShipToAddessTrigger on ShipTo_Address__c (before insert, before update) {
   List<ShipTo_Address__c> slist = new List<ShipTo_Address__c>();
   for ( ShipTo_Address__c s : trigger.new ) { 
       if ( s.Primary_Billing_Address__c == true) {
           Contact c = New Contact(Id = s.Contact__c);
           system.debug('***** UPDATING:'+c.Id+' '+s.Address__c+' '+s.City__c);

           c.MailingStreet = s.Address__c;
           c.MailingCity = s.City__c;
           c.MailingState = s.State__c;
           c.MailingCountry = s.Country__c;
           c.MailingPostalCode = s.ZIP__c;

           update c;             
       }
       if ( s.Default_Shipping_Address__c == true) {
           Contact c = New Contact(Id = s.Contact__c);
           system.debug('***** UPDATING:'+c.Id+' '+s.Address__c+' '+s.City__c);

           c.OtherStreet = s.Address__c;
           c.OtherCity = s.City__c;
           c.OtherState = s.State__c;
           c.OtherCountry = s.Country__c;
           c.OtherPostalCode = s.ZIP__c;

           update c; 
       }
   }
}


Hi,

   I wanted something like this in my code

User-added image

I got this using single controller with few methods and and one visualforce page.

Now what I want is :

User-added image

But I want to use single controller which will operate on different lists.
So planning to have somethink like this

1) 1 Visual force 
2)  controller A has got different objects like multiselect1, multiselect2 and multiselect3   (These 3 objects are of type multiselect)
3) one generic controller/class 'multiselect' which will store information related to data in left panel, right panel, selected and unselected and some functions to move data from one panel to another. I can call these methods from controller A by calling methods using specific objects (like we do in Java).

How I can make this work?
So basically, what I want is visualforce page calls methods on particular object which will get pass to controller A and controller A will again call method from multiselect class on the same object passed by visualforcepage.

Current visualforcepage code :

<apex:panelGrid columns="3" id="abcd">
            <apex:selectList id="sel1" value="{!leftselected}" multiselect="true" style="width:100px" size="5">
                <apex:selectOptions value="{!unselectedvalues}" />
            </apex:selectList>
                <apex:panelGroup >
                    <br/>
                    <apex:image value="{!$Resource.moveRight}">
                        <apex:actionSupport event="onclick" action="{!selectclick}" reRender="abcd"/>
                    </apex:image>
                    <br/><br/>
                    <apex:image value="{!$Resource.moveLeft}">
                        <apex:actionSupport event="onclick" action="{!unselectclick}" reRender="abcd"/>
                    </apex:image>
                </apex:panelGroup>
            <apex:selectList id="sel2" value="{!rightselected}" multiselect="true" style="width:100px" size="5">
                <apex:selectOptions value="{!SelectedValues}" />
            </apex:selectList>
        </apex:panelGrid>



Please let me know if my question is confusing.



Best Regards,
Abhishek








Hi All,

I am looking to create a series of pages that allow for creation of multiple custom objects. The first step however before anything can be rendered or created is to check the 'v' parameter in the URL to ensure that the vendor exists.

i keep running into problems when i look to inslude the logic in the controller constructor. It is my understanding from the documentation that the controller constructor will be processed first, then getter, then actions etc...

The below logic either will not compile, because the contrstor cannot return a value, and thus not redirect the page. Or calling the PageReference method booter() does not do anything.

Below is the controller code i have currently:

public class ccController {
    public List<Vendor__c> vendor;

 //Redirects
    PageReference booted = new PageReference ('http://www.google.com');
    
    
    //controller constructor
    public ccController() {
        vendor = [SELECT id, name FROM Vendor__c WHERE id = :ApexPages.currentPage().getParameters().get('v') LIMIT 1];
        if (vendor.size() == 1){
            //vendor is valid do some stuff
            
        }else{
            //vendor is not valid, redirect to another page
            //booted.setRedirect(true);
            //return booted;
            booter();
        }
  
    public PageReference booter() {
        booted.SetRedirect(true);
        return booted;
        }
       
    public PageReference save() {
           return null;
    }
    
    public PageReference nextStep(){
        return null;
    }
    
}

Many thanks in advance for any feedback and nudges in the right direction.
Hi All,

We have a custom approval which is being carried by an Apex Class defening the logic behind it. The Apex Class gets the next approver based on certain Matrices in the system.

Now we would like to put in some validation when you click on the button. This button is a detail page button. Normally it just references a VF page. The VF page has an extension, calling the above class and firing a method.

The constructor of this Apex Class uses the ApexPages.StandardController method to get the current record from where the button was called. So without the need of creating separate query to get all the values of the fields referenced in the code.

So now we want to add the validation on the button using simple Javascript. The validation works, however, the Javascript will open up the location of the VF page. The VF page will call the method referenced in it's action. However, because of the Javascript, the ApexPages.StandardController references a null record.

Any ideas how we can get this done?

Following is the simple example of how the Javascript could look like:
{!REQUIRESCRIPT("/soap/ajax/24.0/connection.js")}

var result = sforce.connection.query("SELECT Id, StageName FROM Opportunity WHERE Id = '{!Contract_Approval__c.OpportunityId__c}' LIMIT 1");

records = result.getArray("records");

for(var i=0;i<records.length;i++) {
var record = records[i];

if(record.StageName == 'Not Won') {
window.location = '/apex/ApprovalButtonPage';
} else {
alert("Some Error Message.");
}
}

The VF page could look like this:

<apex:page standardController="Contract_Approval__c" extensions="ApprovalButtonController" action="{!submitApprovalProcess}">
    <apex:pageMessages />
</apex:page>
The Apex Class coud look like this:
public class ApprovalButtonController {
private final Contract_Approval__c conapp;

public ApprovalButtonController(ApexPages.StandardController controller) {
this.conapp = (Contract_Approval__c) controller.getRecord();
}

public PageReference submitApprovalProcess() {
// Logic
// Logic
}
}


How can I now make sure I can use the StandardController method via my Javascript validation?

Thanks!
Robin

Hey everyone,

I am currently working on a project that our organization is going to implement in our salesforce org, in order to increase user’s efficiency searching for specific contacts and leads. I proposed to create a visualforce page and an Apex controller that would allow users to search for contacts and leads in real time using javascript/jQuery/ajax. Everything seems to be working flawlessly, except for one of the two picklist fields, Revenue and Number of Employees. For both of these fields, I gave them both a list of ranged options, each representing a different tier for their respective values. After the user selects an option, the page’s Apex Controller would handle all values that were passed using conditional statements. Here are the two picklists:
<tr>
<td>
  <p>Revenue:</p>
</td>
<td>                         
  <select id="revenue_mL" onchange="runSearch();">
   <option value=""></option>
   <option value="tier1_mL">Less than $1 Million</option>
   <option value="tier2_mL">$1 million - $5 million</option>
   <option value="tier3_mL">$5 million - $10 million</option>
   <option value="tier4_mL">$10 million - under $25 million</option>
   <option value="tier5_mL">$25 million - under $50 million</option>
   <option value="tier6_mL">$50 million - under $100 million</option>
   <option value="tier7_mL">$100 million - under $250 million</option>
   <option value="tier8_mL">$250 million - under $500 million</option>
   <option value="tier9_mL">$500 million - under $2.5 billion</option>
   <option value="tier10_mL">Over $2.5 billion</option>
  </select>
</td>
</tr>
<tr>
<td>
  <p>Employees:</p>
</td>
<td>
  <select id="employNum_mL" onchange="runSearch();">
   <option value=""></option>
   <option value="tier1_mL">1-100 Employees</option>
   <option value="tier2_mL">101-500 Employees</option>
   <option value="tier3_mL">501-3,500 Employees</option>
   <option value="tier4_mL">3,500+ Employees</option>
  </select>
</td>
</tr>
Both picklists have the event, “onchange”, attributed to them. So, anytime the picklist is changed to a different value, the runSearch() function is executed. The function, runSearch(), is used to “scoop” all the data from the form using an <apex:actionFunction> tag. Here is the runSearch() javascript function:
function runSearch() {
	var e = document.getElementById("employNum_mL");
	var strUser = e.options[e.selectedIndex].value;
	var f = document.getElementById("revenue_mL");
	var strUser2 = f.options[f.selectedIndex].value;
	mainSearch(
		document.getElementById("title_mL").value,
		document.getElementById("industry_mL").value,
		document.getElementById("company_mL").value,
		strUser2,
		strUser,
		document.getElementById("zipInput").value
	);
}
Here is the actionFunction tag that sends the form parameters to the apex controller:
<apex:actionFunction name="mainSearch" action="{!runMarketingSearch}" rerender="results, resultsLead">
	  <apex:param name="title_mL" value="" />
	  <apex:param name="industry_mL" value="" />
	  <apex:param name="company_mL" value="" />
	  <apex:param name="revenue_mL" value="" />
	  <apex:param name="employNum_mL" value="" />
	  <apex:param name="zipInput" value="" />
  </apex:actionFunction>
Finally, all the data ends up in the Apex Controller. Here is the apex controller:
public with sharing class mLSearchController{
private String soqlCon {get;set;}
private String soqlLead {get;set;}
public List<Contact> contacts {get;set;}
public List<Lead> leadList {get;set;}

public mLSearchController() {
  runQuery();
}
 
public void runQuery() {
  try {
   contacts = Database.query(soqlCon + ' limit 20');
   leadList = Database.query(soqlLead + ' limit 20');
  } catch (Exception e) {
   ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 'Ooops!'));
  }
}

public PageReference runMarketingSearch() {
  String title_mL = Apexpages.currentPage().getParameters().get('title_mL');
  String industry_mL = Apexpages.currentPage().getParameters().get('industry_mL');
  String company_mL = Apexpages.currentPage().getParameters().get('company_mL');
  String revenue_mL = Apexpages.currentPage().getParameters().get('revenue_mL');
  String employNum_mL = Apexpages.currentPage().getParameters().get('employNum_mL');
  String zipcode = Apexpages.currentPage().getParameters().get('zipInput');
  soqlCon = 'select firstname, lastname, Title, Email, Phone, account.Industry, MailingCity, MailingState, MailingPostalCode from Contact where account.name != null';
  soqlLead = 'select firstname, lastname, Title, Phone, Email, Industry, Company, NumberOfEmployees, AnnualRevenue, City, State, PostalCode from Lead where Company != null';
       if (!title_mL.equals('')) {
        soqlCon += ' and Title LIKE \'%' + String.escapeSingleQuotes(title_mL) + '%\'';
        soqlLead += ' and Title LIKE \'%' + String.escapeSingleQuotes(title_mL) + '%\'';
       }
       if (!industry_mL.equals('')) {
        soqlCon += ' and account.Industry LIKE \'%' + String.escapeSingleQuotes(industry_mL) + '%\'';
        soqlLead += ' and Industry LIKE \'%' + String.escapeSingleQuotes(industry_mL) + '%\'';
       }
       if (!zipcode.equals('')) {
        soqlCon += ' and MailingPostalCode LIKE \'' + String.escapeSingleQuotes(zipcode) + '%\'';
        soqlLead += ' and PostalCode LIKE \'' + String.escapeSingleQuotes(zipcode) + '%\'';
       }
       if (!company_mL.equals('')) {
        soqlLead += ' and Company LIKE \'%' + String.escapeSingleQuotes(company_mL) + '%\'';
       }
 
       // ===============================================================================================
  // THIS IS THE REVENUE CONDITIONAL STATEMENTS ALL SEEM TO WORK EXCEPT FOR tier9_mL AND tier10_mL
  // ===============================================================================================
       if (revenue_mL == 'tier1_mL') {
        soqlLead += ' and (AnnualRevenue < 1000000)';
       } else if (revenue_mL == 'tier2_mL') {
        soqlLead += ' and (AnnualRevenue >= 1000000 AND AnnualRevenue < 5000000)';
       } else if (revenue_mL == 'tier3_mL') {
        soqlLead += ' and (AnnualRevenue >= 5000000 AND AnnualRevenue < 10000000)';
       } else if (revenue_mL == 'tier4_mL') {
        soqlLead += ' and (AnnualRevenue >= 10000000 AND AnnualRevenue < 25000000)';
       } else if (revenue_mL == 'tier5_mL') {
        soqlLead += ' and (AnnualRevenue >= 25000000 AND AnnualRevenue < 50000000)';
       } else if (revenue_mL == 'tier6_mL') {
        soqlLead += ' and (AnnualRevenue >= 50000000 AND AnnualRevenue < 100000000)';
       } else if (revenue_mL == 'tier7_mL') {
        soqlLead += ' and (AnnualRevenue >= 100000000 AND AnnualRevenue < 250000000)';
       } else if (revenue_mL == 'tier8_mL') {
        soqlLead += ' and (AnnualRevenue >= 250000000 AND AnnualRevenue < 500000000)';
       } else if (revenue_mL == 'tier9_mL') {
        soqlLead += ' and (AnnualRevenue >= 500000000 AND AnnualRevenue < 2500000000)';
       } else if (revenue_mL == 'tier10_mL') {
        soqlLead += ' and (AnnualRevenue >= 2500000000)';
       } else {
       
       }
      
       if (employNum_mL == 'tier1_mL') {
        soqlLead += ' and (NumberOfEmployees >= 1 AND NumberOfEmployees <= 100)';
       } else if (employNum_mL == 'tier2_mL') {
        soqlLead += ' and (NumberOfEmployees >= 101 AND NumberOfEmployees <= 500)';
       } else if (employNum_mL == 'tier3_mL') {
        soqlLead += ' and (NumberOfEmployees >= 501 AND NumberOfEmployees <= 3500)';
       } else if (employNum_mL == 'tier4_mL') {
        soqlLead += ' and (NumberOfEmployees > 3500)';
       } else {
       
       }
       runQuery();
     return null;
}

}
   The problem that I am faced with is that the Revenue picklist is not functioning correctly, while the Number of Employees picklist is working fine. The apex seems to be appending the correct data from the revenue picklist, except for the last two values, tier9_mL and tier10_mL. Here are two lead use cases that are in my sandbox I do have two Lead cases. One lead has an annual revenue of $10,000,000, and another has $4,000,000,000. For some reason, the query is able to pull the $10 million lead, but not the $4 billion. I was hoping that any more experienced developers might be kind enough to look at my problem and help guide me to where the issue is. Any suggestions, ideas, etc. are greatly appreciated. Thanks so much for your time.
I've a requirement to do sorting . I did it with sort() but does only in ascending way. My client wants to have column sorting something like arrow sorting ,how can i attempt to do this with my code ? Please help. I'm really in a need to get this done.I'm referring to link : http://www.sundoginteractive.com/sunblog/posts/a-recipe-for-column-sorting-salesforce-visualforce-page which also doesnt work.

Stressed out with this.Thanks in advance,James.


    public class PagingTasksController{

    public List<Task> tasks;
    public Integer CountTotalRecords{get;set;}
    public String QueryString {get;set;}
    public Integer OffsetSize = 0;
    private Integer QueryLimit = 3;
    public List<Task> lstTasks;
    public String searchText {get;set;}
  
    public PagingTasksController (){
        //CountTotalRecords= [select count() from Task];
    }
  


    public List<Task> getTasks(){
        if(tasks == null){
            tasks = new List<Task>();
        }
        return tasks;
    }
  
    public void findTasks(){
        String qStr2 = 'Select count() from Task where Subject like \'%'+searchText+'%\' OR Status like \'%'+searchText+'%\'';
        CountTotalRecords = Database.countQuery(qStr2);
        queryTasks();
    }
  
    public void  queryTasks(){
        String qStr = 'Select OwnerId,Subject,Status,Priority from Task where Subject like \'%'+searchText+'%\' OR Status like \'%'+searchText+'%\' Order By Subject,Status limit ' + QueryLimit + ' offset ' + OffsetSize;
        tasks = Database.query(qStr);
        tasks.sort();

    }

    public Boolean getDisablePrevious(){
        if(OffsetSize>0){
            return false;
        }
        else return true;
    }

    public Boolean getDisableNext() {
        if (OffsetSize + QueryLimit < countTotalRecords){
            return false;
        }
        else return true;
    }

    public PageReference Next() {
        OffsetSize += QueryLimit;
        queryTasks();
        return null;
    }

    public PageReference Previous() {
        OffsetSize -= QueryLimit;
        queryTasks();
        return null;
    }

      public PageReference save() {
        update tasks;
        return ApexPages.CurrentPage();
     }
   
    }



     <apex:page controller="PagingTasksController">
    <apex:form >
        <apex:pageBlock title="Tasks" id="pgBlock">
           <apex:pageBlockButtons >
               <apex:commandButton action="{!save}" id="saveButton" value="Save"/>
               <apex:commandButton onclick="resetInlineEdit()" id="cancelButton" value="Cancel"/>
           </apex:pageBlockButtons>
   
        <apex:inlineEditSupport showOnEdit="saveButton, cancelButton"
                    hideOnEdit="editButton" event="ondblclick"
                    changedStyleClass="myBoldClass" resetFunction="resetInlineEdit"/>
   
         <apex:inputText id="searchBox" value="{!searchText}"/>
        <apex:commandButton value="Search" reRender="pgTable,pgBlock" action="{!findTasks}"/>
          <apex:pageBlockTable value="{!Tasks}" var="tsk" id="pgTable" >
           <apex:column >
            <apex:outputLink value="{!URLFOR($Action.Task.Delete, tsk.id,['retURL'='/apex/Task_Assignment_Features'])}" >Delete</apex:outputLink>
</apex:column>
         
          <apex:column headerValue="Subject">
            <apex:outputField value="{!tsk.Subject}"/>
           </apex:column>
           <apex:column headerValue="Status">
             <apex:outputField value="{!tsk.Status}"/>
         </apex:column>
         <apex:column headerValue="Priority">
            <apex:outputField value="{!tsk.Priority}"/>
        </apex:column>
        <apex:column headerValue="OwnerId">
            <apex:outputField value="{!tsk.OwnerId}"/>
        </apex:column>
     </apex:pageBlockTable>
       <apex:pageBlockButtons >
                <apex:commandButton value="Previous" action="{!Previous}" rerender="pgTable,pgBlock"
                                    status="status" disabled="{!DisablePrevious}" />
                <apex:commandButton value="Next" action="{!Next}" reRender="pgTable,pgBlock"
                                    status="status" disabled="{!DisableNext}" />
                <apex:actionStatus id="status" startText="Please Wait..."/>
            </apex:pageBlockButtons>
        </apex:pageBlock>
    </apex:form>
     <apex:enhancedlist type="Activity" height="800" rowsPerPage="50" customizable="False"/>
</apex:page>
trigger dubplicatewithoutgov on student__c (before insert)
{
   list<string> stlist=new list<string>();
   for(student__C st:trigger.old)
   {
    stlist.add(st.name);
   }
   for(student__C st:trigger.new)
   {
   for(integer i=0;i<stlist.size();i++)
   {
    if(st.name==stlist[i])
    {
     st.adderror('cant not add dupicate record');
     }
   }
}  
}
Hey all,

I am going absolutely mad trying to figure this out!  I have read tons and tons of articles online about how to pass a variable from Javascript to my Apex Controller...but NONE OF THEM ARE WORKING FOR ME!!  

Can someone take a look at my code here and let me know what the heck is going wrong?  I am only pasting the pertinent sections for now unless it is deemed that this code is accurate:

Visualforce Page:

<apex:page standardController="Case" recordSetVar="Cases" extensions="SIMSQuickCreate">
<head>
    <script> 
        
        function createCase(){
        
            var supplier = document.getElementById('{!$Component.form.block.section1.supplier}').value;
                
            createFunction();
        }
    </script>
    </head>
    <apex:form id="form" >
        <apex:actionFunction name="createFunction" action="{!createCase}" rerender=""/>
        <apex:pageBlock id="block" title="SIMS Quick Create" mode="edit">
            <apex:pageBlockSection id="section1" title="Contact Information" columns="2">
                <apex:inputField id="supplier" value="{!NewCase.Supplier__c}" required="true">
            </apex:pageBlockSection>
            <center><input type="button" value="Create" onclick="createCase();"/></center>
        </apex:pageBlock>
    </apex:form>
</apex:page>

Thus far, if I use JavaScript alert() to show me the value of the "supplier" var it shows perfectly.  However, it doesn't pass to the controller:

public with sharing class SIMSQuickCreate{

    ApexPages.StandardSetController setCon;
    
       
    public SIMSQuickCreate (Apexpages.StandardSetController controller) {

        setCon = controller;
    }
        
    public String supplier {get; set;}   
        
    public Case c;

    public Case getNewCase() {
    
        if(c == null){
            
            c = new Case();
        }
        
        return c;
    }
    
    
    public PageReference createCase() {  
    
        System.Debug('>>>>>>>>>>>>> HERE IS THE VALUE --> ' + supplier);

       return null;
    }
}

The result of the System.Debug is:

(116783031)|USER_DEBUG|[82]|DEBUG|>>>>>>>>>>>>> HERE IS THE VALUE --> null

Everything I have read online tells me that the {get;set;} should get the Javascript variable and set it for the controller.

Why isn't this working for me?!?!
Hi All,

I am trying to create a button that converts a case to an opportunity, but have ran into a bit of a brickwall

When I click the button I get the following error

 A problem with the OnClick JavaScript for this button or link was encountered:

{faultcode:,soapenv:Client',faultstring:"03/08/2014' is not a valid value for the type xsd:date',}


The status of the case changes but the opportunity is not created, here is the code I have but not sure if it works totally as can't get past the date issue.

{!REQUIRESCRIPT("/soap/ajax/25.0/connection.js")}
{!REQUIRESCRIPT("/soap/ajax/10.0/apex.js")}
var caseObj = new sforce.SObject("Case");
   caseObj.Id = '{!Case.Id}';
   caseObj.Status = 'Converted to Opportunity';
var result = sforce.connection.update([caseObj]);
var status = "{!Case.Status}}";
var newRecords = [];
{
   var o = new sforce.SObject("Opportunity");
   o.AccountId = '{!Case.AccountId}';
   o.Type = '{!Case.Type}';
   o.Name = '{!Case.CaseNumber},{!Case.Subject}';
   o.LeadSource = '{!'Converted from Case'}';
   o.Description = '{! Case.Description }';
   o.OwnerId = '{!Account.OwnerId}';
   o.StageName = '{!'Perception Analysis'}';
   o.CloseDate = '{! TODAY() +30}';
newRecords.push(o);
}
var result = sforce.connection.create(newRecords);

if (result[0].success == 'false') {
    alert(result[0].errors.message);
} else {
    parent.ID = '{!Case.ParentId}';
    window.parent.location = ('/00a/e?parent_id=retURL=/{!Case.Id}');}


I know the issue is from the o.CloseDate = '{! TODAY() +30}'; but just can't workout what it should be.

Thanks
 
Hi
Visualforce Code :
<apex:page controller="StringListEx" showheader="false" >
  <apex:form >
     <apex:pageblock >
        Name <apex:inputtext value="{!firVal}"/>
        code <apex:inputtext value="{!secVal}"/>
        Color <apex:inputtext value="{!thirdVal}"/>
        Class <apex:inputtext value="{!fourthVal}"/>
        <apex:commandButton value="Display" action="{!dislay}"/>
     </apex:pageblock>
  </apex:form>
</apex:page>
Apex/Controller Code :
public with sharing class StringListEx {

    public StringListEx (){
   
    } 
    
    public List<String> strLst;
    public String firVal { get; set; }
    public String secVal { get; set; }
    public String thirdVal { get; set; }
    public String fourthVal { get; set; }
    public PageReference dislay() {
        System.debug('First element value::::::::::::::'+firVal);
        System.debug('Second value::::::::::::::'+secVal);
        System.debug('Third value::::::::::::::::'+thirdVal);
        System.debug('Fourth value:::::::::::::::'+fourthVal); 
        strLst.add(firVal);   
        strLst.add(secVal);   
        strLst.add(thirdVal);   
        strLst.add(fourthVal);
        return null;
    }  
}

While Adding values to array,I'm getting this error System.NullPointerException: Attempt to de-reference a null object  at line 17.
In debugging I am getting the values whatever I entered
.Then why it is showing Nullpointer exception


Hi all,

I have the following custom lightning component, but it is coming up with the following error: Unknown controller action 'getOpps'.

component:
<aura:component controller="AcctOppsController" implements="flexipage:availableForRecordHome,force:hasRecordId">
    <aura:attribute name="mydata" type="OpportunityContactRole[]"/>
    <aura:attribute name="mycolumns" type="List"/>
    <aura:attribute name="recordId" type="Id" />
    <aura:attribute name="currentRecordId" type="Id" />
    <aura:handler name="init" value="{!this }" action="{! c.doInit }"/>
    <div style="height: 300px">
        <lightning:datatable
                keyField="id"
                data="{! v.mydata }"
                columns="{! v.mycolumns }"
                hideCheckboxColumn="true"/>
    </div>
</aura:component>
controller:
({
    doInit: function (cmp, event, helper) {
        cmp.set('v.mycolumns', [
            {label: 'Opportunity Name', fieldName: 'opportunityId', type: 'text'},
            {label: 'Contact Name', fieldName: 'contact', type: 'text'},
            {label: 'Role', fieldName: 'role', type: 'text'},
            {label: 'Amount', fieldName: 'amount', type: 'currency'}
        ]);
        
        var fetchData = {
            opportunityId: "opportunityId",
            contact : "Contact.Name",
            role : "Role",
            amount : "Opportunity.Amount"
        };

        helper.fetchData(cmp,fetchData);
    }
})
helper:
({
    fetchData : function(cmp) {
        var recordId =  cmp.get("v.recordId");
        var action = cmp.get("c.getOpps");
        action.setParams({ "currentRecordId" : recordId });
        action.setCallback(this, $A.getCallback(function (response) {
            var state = response.getState();
            if (state ==="SUCCESS") {
                cmp.set("v.mydata", response.getReturnValue());
            } else if (state === "ERROR") {
                var errors = response.getError();
                console.error(errors);
            }
        }
                                               ));
        $A.enqueueAction(action);
    }
})
apex controller:
public with sharing class AcctOppsController{
@AuraEnabled
public String currentRecordId {get;set;}

    public AcctOppsController(ApexPages.StandardController controller) {
        currentRecordId  = ApexPages.CurrentPage().getparameters().get('id');
    }
    
    @AuraEnabled    
    public List<OpportunityContactRole> getOpps() {
        List<OpportunityContactRole> oppresults = [SELECT Contact.name, Role, OpportunityId, Opportunity.Amount, Opportunity.StageName, Opportunity.Type FROM OpportunityContactRole WHERE contact.accountid=:currentRecordId];
        return oppresults;
        }
}

Any thoughts on what I am missing?


 

I'm fairly new to writing out apex code, so any input would be greatly appreciated. 

Here is the current setup and problem I'm running into:
I have a custom formula field with the OrderItem Object which generates a JSON string based on the product information (this JSON string is used to send lineItem order information to another system). This field is called QBO_Line_JSON__c. I'm trying to populate a custom field in the Order object (QBO_JSON__c) that combines all the QBO_Line_JSON__c fields from the related OrderItem records. The goal is to have one JSON string that can be queried from the external system that lives in the Order object.

Here is the code so far:
trigger qboJSONCreator on Order (after insert, after update, after delete, after undelete) {

List<Order> OrderList = (Trigger.isInsert|| Trigger.isUnDelete) ? Trigger.new : Trigger.old;

List<Id>OrderIds = new List<Id>();

for (Order OrderStr : OrderList) {
OrderIds.add(OrderStr.OrderItems);
}

List<OrderItem> OrderItemList = [select id, (select id, QBO_Line_JSON__c from OrderItems) from Order where id in :OrderIds];

for (OrderItem ordr :OrderItemList) {
  for(integer i=1;i < ordr.OrderItem.size();i++)
  {
    ordr.QBO_JSON__c = ordr.QBO_JSON__c + '; ' + string.valueOf(ordr.OrderItem[i].QBO_Line_JSON__c);
  }
}

update OrderItemList;

}
The above gives me an error "Incompatible element type List<OrderItem> for collection of Id"

I've looked but haven't been able to piece together an understanding of how to resolve it. 

Any input or pointing in the right direction would be great. 

Thanks in advance!

 
To preface, I have very little to no development skills, and unfortunately, the org I inherited as admin is very apex-heavy. I need to make an edit to an apex class (sandbox first of course), but am unable to due to it being part of a scheduled job. We have about a dozen scheduled jobs, all of which are vaguely named. Is there a way I can tell which apex class is running which scheduled job? Of the scheduled jobs, only two of them give me the "manage" option. (see below)
User-added image
I have a variable I am trying to pass to the controller, but it is not working. According to several posts I've seen it should work. Here's my code:

VF:
<apex:actionFunction action="{!clickedRow}" name="call_clickedRow">
     <apex:param value="" assignTo="{!selectedRow}"/>
</apex:actionFunction>

<apex:repeat value="{!object1}" var="var1">
     <tr onclick="call_clickedRow({!var1.Name}); alert({!selectedRow});">
          //.................................................
          //.................................................
     </tr>
<apex:repeat>

Controller:
public String selectedRow{ get; set; }

public PageReference clickedRow(){
        return null;
}

I am however, getting a XmlHTTPSynchronous error that when expanded says that it is related to the onclick event shown above. I've tried several different methods of sending variables to the controller, but none have worked so far. I have also tried putting async=true in many places, but maybe not the right one. Any and all help would be appreciated. Thanks in advance.
Hello,
I have this URL which generates JSON output:
https://maps.googleapis.com/maps/api/geocode/json?address= Nuselská 23, 140 00, Praha 4 key=AIzaSyC2Hu3fh2L7MIN_UaBqgBtM-QvI-SPcGYg
I get data in JSON format using above URL and what I need is to get geolocation data (latitude and longtitude) and place these in a variabĺe.
Could anyoune please share a code how to do that.
I just need to place the URL in a code and get required geolocoation details without any "in between" step of copying/pasting JSON output format.
Appreciate your help,
Milan
Hi all,

I need some help with a validation rule please. 

I have the picklist "Network" with 30 Values. For 20 of them it is necessary to enter another information in the picklist field "Payment". 

I tried different ways, but I was only able to relate one value to the the  2nd picklist. But this I also can not reproduce anymore. Can you help me? I played with  AND and OR ...but it won't work :(
Last try is: 
AND(
ISPICKVAL(network__c,"AD"),
ISPICKVAL (network__c,"AX"),
(ISBLANK(Payment_Type__c)))

In this case I got the Error "Error: Field Affiliate_Payment_Type__c is a picklist field. Picklist fields are only supported in certain functions. " But before it worked with the field. i have no idea..

 
Hello,

I am trying to create a map of child objects as they relate to the parent object for a trigger.

I have the standard Contract object, and a custom Time Entry Object. When a Time Entry is created, udpated, or deleted my trigger kicks off and grabs all Time Entries associated with the Contract. It will then calculate the Total Time Entered and the Total Value and update this on the Contract. My current  method works, however I'm running into governor limit exceptions. Best practices states I should use a map instead of multipl SQL calls in a for loop. I've followed some examples online using this method however I am getting the error.

sObject type 'ContractwithTime' is not supported. If you are attempting to use a custom object, be sure to append the '__c' after the entity name. Please reference your WSDL or the describe call for the appropriate names.

Code:
trigger trg_TimeEntryRollupToContract on Time_Entry__c (after delete, after insert, after update) 
{
    double dblTotalHours = 0.0;
    double curTotalValue = 0.00;


    if(Trigger.isInsert||Trigger.isUpdate||Trigger.isDelete)
    { 
        //***********************************************
        //New Record
        //***********************************************
           
        if(Trigger.isInsert)
        { 


           List<Contract> ContractwithTime = [SELECT Id, Total_Time_Entry_Value__c, Total_Time_Entry_Hours__c,
                                                    (SELECT Id, Total_Time__c, Total_Entry_Value__c FROM TimeEntry__r)
                                                    FROM ContractwithTime WHERE Id IN :Trigger.newMap.KeySet()];
            
            for(Contract con : ContractwithTime){
                for(TimeEntry__c ti : ContractwithTime.Time_Entry__r){
                    	if (ti.Total_Time__c == null) ti.Total_Time__c = 0;
                        dblTotalHours += ti.Total_Time__c;
                        if(ti.Time_Entry_Value__c!=null) curTotalValue += ti.Time_Entry_Value__c;
                        if(dblTotalHours > 0) contractwithTime.Total_Time_Entry_Hours__c = dblTotalHours;
;
                        contractwithTime.Total_Time_Entry_Value__c = curTotalValue;
                }
            }
}



 
Hello,
I am using below api call in my project "https://ap2.salesforce.com/services/data/v20.0/query?q=select+FirstName,LastName,Phone,Email+from Contact where+FirstName+LIKE+'%a%' "
but i am get  400 bad request error can you please any one help me to resolve that 
i have created a Connected app in my sandbox account 

Note: its working for one of my old account, earlier i created one new sandbox account with that i am getting bad request error
Hello,

I'm trying to find out how to add custom content in the Community Builder. I was under the impression I have to build a component within Developer Console, but then I can't see how I get that component to appear within Community Builder? I've followed several different guides and none seem to make it appear anywhere to be selectable. I thought it'd be possible to make it appear within the lightning components list under the page editor section?

Thanks,

Tom
Hi SFDC, I'm new in the Apex world :)
I have some trouble with picklist value, i will explain.
I have a picklist that show me the StartDate from the Period Objects.
I have also a List of ForecastingQuota by User.
The problem is that when I select a value in the picklist, the controller doesn't get it, so my query wich show the user can't change.
Controller :
public List<SelectOption> optionspl {get;set;}
public List<User> resultsusers{get;set;}
public Date dateinput{get;set;}
public Date dateinput2 {get;set;}


public List<SelectOption> getPeriodList(){
 		List<SelectOption> optionspl = new List<SelectOption>();
 		List<SObject> resultspl = [SELECT FullyQualifiedLabel, StartDate FROM Period WHERE StartDate > TODAY AND Type = 'Quarter'];
 		for(SObject pl : resultspl){
 			optionspl.add(new SelectOption(String.valueOf(pl.get('StartDate')),String.valueOf(pl.get('StartDate'))));
 		}
 		return optionspl;
 	}

public  List<ForecastingQuota> getAllQuotas(){
		dateinput = Date.today();
		date mydate2 = mydate.addDays(90);

		List<ForecastingQuota> resultsquotas = new List<ForecastingQuota>();
	    resultsquotas = [SELECT Id,QuotaAmount,QuotaOwnerId, StartDate FROM ForecastingQuota WHERE StartDate >:dateinput AND StartDate <:mydate2 ORDER BY QuotaOwnerId, StartDate ASC];
	    
	    List<User> resultsusers = new List<User>();
		resultsusers = [SELECT Id FROM User WHERE IsActive = TRUE AND ForecastEnabled = TRUE LIMIT 999];

		Map<Id, ForecastingQuota> fqsByOwnerId = new Map<Id, ForecastingQuota>();
			for (ForecastingQuota fq : resultsquotas)
			{
			    fqsByOwnerId.put(fq.QuotaOwnerId, fq);
			}
		
			// new map of quotas keyed by all user ids
		Map<Id, ForecastingQuota> allUserFqsByOwnerId = new Map<Id, ForecastingQuota>();
			for (User u : resultsusers)
			{
			     allUserFqsByOwnerId.put(u.id, fqsByOwnerId.containsKey(u.id) ? fqsByOwnerId.get(u.id) : new ForecastingQuota(QuotaOwnerId = u.id, QuotaAmount = null));
			    	
			}
			List<ForecastingQuota> allthequotas = new List<ForecastingQuota>();
			allthequotas = allUserFqsByOwnerId.values();
			allthequotas.sort();
			return allthequotas;
	}

And the VFP code :
<apex:pageBlockSection columns="4">
<apex:selectList value="{!dateinput2}" id="dateinput2" size="1">
    <apex:selectOptions value="{!periodlist}" />
     <apex:actionSupport event="onchange" rerender="allquotas"/>
</apex:selectList>
			<apex:pageBlockTable value="{!allquotas}" var="key">
				<apex:column>
				<input type="checkbox" name="pouet"/>
				</apex:column>
				<apex:column headerValue="Name">
				    <apex:outputField  value="{!key.QuotaOwnerId}"/>
				</apex:column>
    			<apex:column headerValue="Quota">
			    	<apex:inputField value="{!key.QuotaAmount}"/>
			    </apex:column>
			    <apex:column headerValue="Date">
			    	<apex:outputField value="{!key.StartDate}"/>
			    </apex:column>
			</apex:pageBlockTable>
</apex:pageBlockSection>
</apex:pageBlock>

Thank's for the help :)
 
Hello,

I have a picklist field that contains values A-Z. I need to write a validation rule that says if the Picklist is set to A, B or C then the same Picklist can't be changed to the value X but can be changed to other values. 

OR(
AND(
ISPICKVAL(PRIORVALUE( VPM_Field__c ),"A"), NOT(ISPICKVAL(VPM_Field__c,"X))
),
AND(
ISPICKVAL(PRIORVALUE(VPM_Field__c),"B"), NOT(ISPICKVAL(VPM_Field__c,"X")))
),
AND(
ISPICKVAL(PRIORVALUE(VPM_Field__c),"C"), NOT(ISPICKVAL(VPM_Field__c,"X")))
)


The above is what i have but it doesnt work 

Thanks 

 
  • November 08, 2016
  • Like
  • 0
I have the following Batch job :

global class AdvisorGroupsBatch implements Database.Batchable<sObject>{
    
    public String query;
    
    global database.querylocator start(Database.BatchableContext BC)
  {
      String query = 'Select Id, Name, YTD_Gross_Adv_Group__c, SV_Assets_for_Team__c, (select Id, Name, YTD_Gross_Sales__c, Assets_with_WB__c from Contacts__r) from Advisor_group__c';
      return Database.getQueryLocator(query);
  }
   global void execute(Database.BatchableContext BC, List<sObject> scope)
  {
      decimal total_YTD;
      decimal total_SV;
      for (sObject obj: scope){
          total_YTD = 0;
          total_SV = 0;
          Advisor_group__c advgrp = (Advisor_group__c)obj;
          for (Contact c: advgrp.Contacts__r){
              total_YTD = total_YTD + c.YTD_Gross_Sales__c;
              total_SV = total_SV + c.Assets_with_WB__c;
          }
          advgrp.YTD_Gross_Adv_Group__c = total_YTD;
          advgrp.SV_Assets_for_Team__c = total_SV;
          update advgrp;
        
      }
  } 
  
  global void finish(Database.BatchableContext BC)
  {
    System.debug('Advisor Groups Batch finished.');
  }
    
}


I am trying to write a test class, following is the test class :
@isTest
private class AdvisorGroupsBatchTest {
    public static testMethod void test(){
       
       String query = 'Select Id, Name, YTD_Gross_Adv_Group__c, SV_Assets_for_Team__c, (select Id, Name, YTD_Gross_Sales__c, Assets_with_WB__c from Contacts__r) from Advisor_group__c LIMIT 2';
    
     Advisor_Group__c[] adv = new List<Advisor_Group__c>();
     
           Advisor_Group__c a1 = new Advisor_Group__c(
               Name='Adv Group',
               Id='000',
               YTD_Gross_Adv_Group__c=100,
               SV_Assets_for_Team__c=200);
 
           adv.add(a1);
     
     insert adv;
     
     Test.startTest();
     AdvisorGroupsBatch a = new AdvisorGroupsBatch(query);
      Database.executeBatch(a);
     //ID batchprocessid = Database.executeBatch(a);
     Test.stopTest();
  } 
                      
}

I am unable to reach a code coverage of 75%. it is not increasing more than 24%. Please suggest

 
Hi All,

I have written a batch class with the below scenario.
if (ObjectName==Account)
{ need to query account  records
}
else if (ObjectName =Contact )
{ Query Contact records)
}
So i will get either account or contact records in scope and in execute method i will create records for other custom object means if it is account it will insert with account Id in the new custom object and if Contact contact Id in the new object .Right now it is captuirng the Id into another custom Object but the problem is whenever i am executing it is capturing the same .

So here i want to eliminate the creation of duplicates means if the Record Id(Acc or con Id already in the new custom object then it should not create new record if the record is not existing then create new record with the Acc or Con Id

My Code:
  global void execute(Database.BatchableContext BC, List<SObject> scope)
    { 
        Map<id, Custom Object> CustomMap= new Map<id,Custom Map>();
         for(Sobject obj: scope)
         {      
                Custom Object cm= new Custom Object();
                 
                 cm.Recordt_ID__c =obj.Id;
                 
                  CustomMap.put(Cm.Object_ID__c, cm);
             
          }
          if(!CustomMap.isEmpty())
        {
            Database.SaveResult[] InsertResult = Database.insert(CustomMap.values(),false);
            
        }
        
    }

So here how i will check if there is already a record with same Object Id is there then it should not insert if it is not there it should create new custom object Record.Any one please guide how to do this

Thanks in advance
My apex class is working as desired, but when I convert it to an extension (as my visualforce page has already a custom controller), it is not working.
I have a RemoteAction written in a Apex class which performs auto complete lookup fields. DId I miss anything in save_custom button of custom controller, or the syntax of Controller Extension for custom controller? Why the same code working good as controller, but not as extension? 
public class ExtensionAutocomplete {
    public General_Ledge_Account__c wildCardForGeneralLedgerAccount {get; set;}
    public General_Ledge_Account__c selected {get; set;}
    public Tax_Code__c wildCardForTaxCode {get; set;}
    public Tax_Code__c selectedTC {get; set;}
    public Journal__c wildCardForJournal {get; set;}
    public Journal__c selectedJ {get; set;}    
    public Dimension__c wildCardForDimension {get; set;}
    public Dimension__c selectedD {get; set;}  
    
	// Constructor for extension of custom controller 
	// 
    public ExtensionAutocomplete(JournalDetail_Controller_2T ctrlParam) {    // JournalDetail_Controller_2T is the controller for the VF page 
    }
    // JavaScript Remoting Action call 
    @RemoteAction
    public static List<General_Ledge_Account__c> lookupSearch(String wildCardForGeneralLedgerAccount) {
        System.debug('lookup: '+wildCardForGeneralLedgerAccount );
        List<General_Ledge_Account__c> master = Database.query('Select Id, Name from General_Ledge_Account__c where Name like \'%' + String.escapeSingleQuotes(wildCardForGeneralLedgerAccount) + '%\'');
        return master;
    }

Custom Controller: 
public with sharing class JournalDetail_Controller_2T  {
    // MVC concept to data binding in VF page & controller
    public Journal__c objectJournal{get; set;}
    public Line_Item__c objectLineItem{get; set;}
        
    //define the constructor 
      public JournalDetail_Controller_2T(ApexPages.StandardController stdController) {}

    public JournalDetail_Controller_2T(){
        // Initiate objects 
        objectJournal = new Journal__c();
        objectLineItem = new Line_Item__c();
    }
    public void save_custom()
    {
        try
        {
            insert objectJournal;
            insert objectLineItem;
        }   
        catch(Exception ex)
        {
            System.debug('\n\nException ='+ex.getMessage()+'\n\n');
        }    
    }
    public void cancel(){}  
    
       }

VF
 
<apex:page id="page" Controller="JournalDetailController_T"  sidebar="false" showHeader="false" standardStylesheets="false" >
    <apex:form id="form" >
        <html id="html">
            <head id="head">
                
                <style>
                    *{
                    <!-- font-size: 1.2vw;           viewport sized typography -->
                    }
                    html{
                    background-color: #E7EDF3;
                    }
                    body{ 
                    margin: 1rem; background-color: white;
                    }    
                    h3{
                    clear:both; background-color: #5B5DFE; width: 95%; padding-left: 1rem; color: white; margin: 2% 2.5% 1% 2.5%;
                    }
                    #div-table-1, #journal-status-left{
                    float: left; width: 45%; margin-left: 5%;
                    }
                    #div-table-2{
                    
                    }
                    #journal-detail-table-1{
                    
                    }
                    #journal-detail-table-2{
                    
                    }
                    #line-item-table{
                    margin-left: 5%;
                    }
                    #accordion3{
                    padding-bottom: 3%;
                    }
                    .lookupInput
                    {
                    display: inline;
                    vertical-align: middle;
                    white-space: nowrap;
                    }
                    .lookupInput img
                    {
                    background-repeat: no-repeat;
                    margin-right: .25em;
                    vertical-align: middle;
                    }
                    .lookupInput .disabled
                    {
                    background-color: #ccc;
                    }
                    .lookupInput .emptyDependentLookup
                    {
                    font-style: italic;
                    }
                    .lookupInput input[readonly]
                    {
                    background-color: #e6e6e6;
                    border: 2px solid #e6e6e6;
                    color: #333;
                    cursor: default;
                    }
                    .lookupInput a.readOnly
                    {
                    float: right;
                    }
                    .lookupInput span.readOnly
                    {
                    display: block;
                    white-space: normal;
                    }
                    .lookupInput span.totalSummary
                    {
                    font-weight: bold;
                    }
                    .inlineEditRequiredDiv .lookupInput img,.inlineEditDiv .lookupInput img
                    {
                    vertical-align: middle;
                    }
                    .quickCreateModule .lookupInput input {
                    max-width: 155px
                    }
                    .lookupIcon {
                    background-image: url(/img/func_icons/util/lookup20.gif);
                    background-position: 0 0;
                    width: 20px;
                    height: 20px;
                    background-position: top left
                    }
                    .lookupIconOn {
                    background-image: url(/img/func_icons/util/lookup20.gif);
                    background-position: 0 0;
                    width: 20px;
                    height: 20px;
                    background-position: top right
                    }
                </style>    
                <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
                <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.21/jquery-ui.min.js"></script>
                <apex:includeScript value="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.10/angular.min.js"/>
                <script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
                <script>
                $(function() { $("#accordion1").accordion({ header: "h3", collapsible: true }); });
                $(function() { $("#accordion2").accordion({ header: "h3", collapsible: true }); });
                $(function() { $("#accordion3").accordion({ header: "h3", collapsible: true }); });
                </script>
            </head>
            
            
            <body id="body" >
                <div>
                    <b> <span style="margin: 0 5% 0 5%; font-size:1.5rem">Journal Detail </span> </b>
                    
                    <apex:commandButton action="{!save_custom}" value="Post" style="background-color:#5B5DFE; color:white;font-weight: bold;  padding: .5rem 2rem .5rem 2rem; margin: 3rem 1rem 1rem 0; " />
                    <apex:commandButton action="{!cancel}" value="Cancel" style="background-color:#5B5DFE; color:white;font-weight: bold;  padding: .5rem 2rem .5rem 2rem; margin: 3rem 1rem 1rem 0; " />
                </div>
                <div class="journal-detail" id="accordion1" >
                    <h3>
                        Journal Detail
                    </h3>
                    <div>
                        <div id="div-table-1">
                            <table id="journal-detail-table-1" border="1" >
                                <apex:pageBlock >
                                    <apex:pageBlockSection >
                                        <tr>  
                                            <apex:inputField value="{!objectJournal.Type__c}"  /> </tr> <tr>
                                        <apex:inputField value="{!objectJournal.Journal_Date__c}" /> </tr><tr>
                                        <apex:inputField value="{!objectJournal.Journal_Currency__c}" /> </tr> <tr>
                                        <apex:inputField value="{!objectJournal.Reference__c}" /> </tr> <tr>
                                        <apex:inputField value="{!objectJournal.Journal_Description__c}"  /> </tr><tr>
                                        <apex:inputField value="{!objectJournal.Transaction__c}"  /> </tr> <tr>
                                        </tr>
                                    </apex:pageBlockSection>
                                </apex:pageBlock>
                            </table>
                        </div>
                        <div id="div-table-2">
                            <table  id="journal-detail-table-2" >
                                <apex:pageBlock >
                                    <apex:pageBlockSection >
                                        <tr><apex:outputField value="{!objectJournal.Name}" /> </tr> <tr> 
                                        <apex:inputField value="{!objectJournal.Period__c}"  /> </tr> <tr>
                                        <apex:inputField value="{!objectJournal.Debits__c}" /> </tr><tr>
                                        <apex:inputField value="{!objectJournal.Credits__c}"  />  </tr> <tr>
                                        <apex:inputField value="{!objectJournal.Invoice_Number__c}" /></tr><tr>
                                        <apex:inputField value="{!objectJournal.Total__c}" /> </tr>
                                    </apex:pageBlockSection>
                                </apex:pageBlock>
                            </table>
                        </div>
                    </div>
                </div>
                
                <div id="accordion2">
                    <h3 >
                        Journal Line Item
                    </h3>    
                   
				<div id="room-and-adding-room">
                	    <div id="field_wrapper_header_id" class="field_wrapper_header">
                                Line Type   	Line Description 		Journal			General Ledger Account	 	Amount 
                                Tax Code		Tax Amount 				Total Amount 	Dimension 

                    </div>
                    <div class="field_wrapper" style="border: dotted;" >
                        <div>      <apex:inputField value="{!objectLineItem.Line_Type__c}" style="width:3rem; float:left;"/> </div><div>
                        <apex:inputField value="{!objectLineItem.Line_Description__c}" style="width:5rem; float:left;"/> </div><div>
                        <apex:inputField value="{!objectLineItem.Journal__c}" style="width:3rem; float:left;"/> </div><div>
                        <apex:inputField value="{!objectLineItem.General_Ledge_Account__c}" style="width:4rem; float:left;"/> </div><div>
                        <apex:inputField value="{!objectLineItem.Amount__c}" style="width:5rem;  float:left;"/> </div><div>
                        <apex:inputField value="{!objectLineItem.Tax_Code__c}" style="width:5rem; float:left;"/> </div><div>
                        <apex:outputText value="{!objectLineItem.Tax_Amount__c}" style="width:3rem; float:left;"/> </div><div>
                        <apex:outputText value="{!objectLineItem.Total_Amount__c}" style="width:3rem; float:left;"/> </div><div>
                        <apex:inputField value="{!objectLineItem.Dimension_1__c}" style="width:6rem; float:left;"/> </div> <br/>
                </div> 
                    
                </div> <!-- End of room-and-adding-room div -->
                    <a href="javascript:void(0);" class="add_button"  title="Add field" style="background-color: red; display:inline-block;" > Add Room </a>
                    
                <div id="accordion3">
                    <h3 >
                        Journal Status
                    </h3>    
                    <div>
                    <div id="journal-status-left">
                        Journal Status <apex:inputField value="{!objectJournal.Journal_Status__c}" />
                    </div>
                    <div>
                        Discard Reason <apex:inputField value="{!objectJournal.Discard_Reason__c}" />
                    </div>
                    </div>
                </div>
                <!-- Script to enable autocomplete functionality -->

                    <apex:pageBlock id="searchBlock" >
                 <apex:outputLabel value="Search General Ledger Account" for="Box" />
                 <apex:outputPanel >
                     <apex:inputText id="TextBox" value="{!wildCardForGeneralLedgerAccount}" styleClass="General Ledger Account"/>
                     <apex:inputHidden id="searchId" value="{!selected}" /> <br/>
                 </apex:outputPanel>
                    
            <apex:outputLabel value="Search Tax Code" for="BoxTC" />
            <apex:outputPanel >
                     <apex:inputText id="TextBoxTC" value="{!wildCardForTaxCode}" styleClass="Tax code"/>
                <apex:inputHidden id="searchIdTC" value="{!selectedTC}" /> <br/>
            </apex:outputPanel>
           <apex:outputLabel value="Search Journal" for="BoxJ" />
            <apex:outputPanel >
                     <apex:inputText id="TextBoxJ" value="{!wildCardForJournal}" styleClass="wild card for Journal"/>
                <apex:inputHidden id="searchIdJ" value="{!selectedJ}" />  <br/>
                </apex:outputPanel>                                       
              <apex:outputLabel value="Search Dimension" for="BoxD" />
            <apex:outputPanel >
                     <apex:inputText id="TextBoxD" value="{!wildCardForDimension}" styleClass="wild card for Dimension"/>
                     <apex:inputHidden id="searchIdD" value="{!selectedD}" />    
                    </apex:outputPanel>
        </apex:pageBlock>
                </div>

    
                   	<!-- Script to add room -->
           <script type="text/javascript">
$(document).ready(function(){
    var maxField = 10; //Input fields increment limitation
    var addButton = $('.add_button'); //Add button selector
    var wrapper = $('.field_wrapper'); //Input field wrapper
    var fieldHTML = '<div><apex:inputField value="{!objectLineItem.Line_Type__c}" style="width:3rem; float:left;"/><apex:inputField value="{!objectLineItem.Line_Description__c}" style="width:5rem; float:left;"/><apex:inputField value="{!objectLineItem.Journal__c}" style="width:3rem; float:left;"/><apex:inputField value="{!objectLineItem.General_Ledge_Account__c}" style="width:4rem; float:left;"/><apex:inputField value="{!objectLineItem.Amount__c}" style="width:5rem;  float:left;"/><apex:inputField value="{!objectLineItem.Tax_Code__c}" style="width:5rem; float:left;"/><apex:outputText value="{!objectLineItem.Tax_Amount__c}" style="width:3rem; float:left;"/><apex:outputText value="{!objectLineItem.Total_Amount__c}" style="width:3rem; float:left;"/><apex:inputField value="{!objectLineItem.Dimension_1__c}" style="width:6rem; float:left;"/><a href="javascript:void(0);" class="remove_button" title="Remove field">Remove</a></div>';
    var x = 1; //Initial field counter is 1
    $(addButton).click(function(){ //Once add button is clicked
        if(x < maxField){ //Check maximum number of input fields
            x++; //Increment field counter
            $(wrapper).append(fieldHTML); // Add field html
        }
    });
    $(wrapper).on('click', '.remove_button', function(e){ //Once remove button is clicked
        e.preventDefault();
        $(this).parent('div').remove(); //Remove field html
        x--; //Decrement field counter
    });
});
</script>
    
    <script type="text/javascript">
    // A FOR LOOP will be added soon to optimize the length of the code
    // for id = [TextBox, TextBoxTC, TextBoxJ, TextBoxD]   searchID  $('[id$=id]')
    //------------------------------------GLA--------------------------
        var PLACEHOLDER = ''; 
        var masterObjects;
        var queryTerm;
        
        $('[id$=TextBox]').autocomplete({
            minLength: 0,
            source: function(request, response) {
                        queryTerm = request.term;
                        AutoCompleteLookupField.lookupSearch(request.term, function(result, event)  {
                            if(event.type == 'exception') {
                                  alert(event.message);
                            } else {
                                 masterObjects = result;
                                 response(masterObjects);
                            }
                        });
                   },
            focus: function( event, ui ) {
                    $('[id$=TextBox]').val( ui.item.Name );
                    return false;
                    },
            select: function( event, ui ) {
                        $('[id$=TextBox]').val( ui.item.Name );
                        $('[id$=searchId]').val( ui.item.Id );
                        return false;
                    },
         })
         .data( "autocomplete" )._renderItem = function( ul, item ) {
            var entry = "<a>" + item.Name;
           
            entry = entry + "</a>";
            entry = entry.replace(queryTerm, "<b>" + queryTerm + "</b>");
            return $( "<li></li>" )
                .data( "item.autocomplete", item )
                .append( entry )
                .appendTo( ul );
        };
            
        // Add or remove placeholder values
        $('[id$=TextBox]').val(PLACEHOLDER);
        $('[id$=TextBox]').on("focus",  function(event){
            $tgt = $(event.target);
            if($tgt.val() === PLACEHOLDER ){
                $tgt.val('');
                $tgt.removeClass('placeHolder');
            }
        });
        $('[id$=TextBox]').on( "blur",  function(event){
            $tgt = $(event.target);
            if($tgt.val() === '' ){
                $tgt.val(PLACEHOLDER);
                $tgt.addClass('placeHolder');
            }
        });

    // ----------------------------------TC-----------------------
            var PLACEHOLDER = ''; 
        var masterObjectsTC;
        var queryTerm;
        $('[id$=TextBoxTC]').autocomplete({
            minLength: 0,
            source: function(request, response) {
                        queryTerm = request.term;
                        AutoCompleteLookupField.lookupSearchTC(request.term, function(result, event)  {
                            if(event.type == 'exception') {
                                  alert(event.message);
                            } else {
                                 masterObjectsTC = result;
                                 response(masterObjectsTC);
                            }
                        });
                   },
            focus: function( event, ui ) {
                    $('[id$=TextBoxTC]').val( ui.item.Name );
                    return false;
                    },
            select: function( event, ui ) {
                        $('[id$=TextBoxTC]').val( ui.item.Name );
                        $('[id$=searchIdTC]').val( ui.item.Id );
                        return false;
                    },
         })
         .data( "autocomplete" )._renderItem = function( ul, item ) {
            var entry = "<a>" + item.Name;
           
            entry = entry + "</a>";
            entry = entry.replace(queryTerm, "<b>" + queryTerm + "</b>");
            return $( "<li></li>" )
                .data( "item.autocomplete", item )
                .append( entry )
                .appendTo( ul );
        };
            
        // Add or remove placeholder values
        $('[id$=TextBoxTC]').val(PLACEHOLDER);
        $('[id$=TextBoxTC]').on("focus",  function(event){
            $tgt = $(event.target);
            if($tgt.val() === PLACEHOLDER ){
                $tgt.val('');
                $tgt.removeClass('placeHolder');
            }
        });
        $('[id$=TextBoxTC]').on( "blur",  function(event){
            $tgt = $(event.target);
            if($tgt.val() === '' ){
                $tgt.val(PLACEHOLDER);
                $tgt.addClass('placeHolder');
            }
        });

    // -----------------------------------------------------====================Journal
       var PLACEHOLDER = ''; 
        var masterObjectsJ;
        var queryTerm;
        $('[id$=TextBoxJ]').autocomplete({
            minLength: 0,
            source: function(request, response) {
                        queryTerm = request.term;
                        AutoCompleteLookupField.lookupSearchJ(request.term, function(result, event)  {
                            if(event.type == 'exception') {
                                  alert(event.message);
                            } else {
                                 masterObjectsJ = result;
                                 response(masterObjectsJ);
                            }
                        });
                   },
            focus: function( event, ui ) {
                    $('[id$=TextBoxJ]').val( ui.item.Name );
                    return false;
                    },
            select: function( event, ui ) {
                        $('[id$=TextBoxJ]').val( ui.item.Name );
                        $('[id$=searchIdJ]').val( ui.item.Id );
                        return false;
                    },
         })
         .data( "autocomplete" )._renderItem = function( ul, item ) {
            var entry = "<a>" + item.Name;
           
            entry = entry + "</a>";
            entry = entry.replace(queryTerm, "<b>" + queryTerm + "</b>");
            return $( "<li></li>" )
                .data( "item.autocomplete", item )
                .append( entry )
                .appendTo( ul );
        };
            
        // Add or remove placeholder values
        $('[id$=TextBoxJ]').val(PLACEHOLDER);
        $('[id$=TextBoxJ]').on("focus",  function(event){
            $tgt = $(event.target);
            if($tgt.val() === PLACEHOLDER ){
                $tgt.val('');
                $tgt.removeClass('placeHolder');
            }
        });
        $('[id$=TextBoxJ]').on( "blur",  function(event){
            $tgt = $(event.target);
            if($tgt.val() === '' ){
                $tgt.val(PLACEHOLDER);
                $tgt.addClass('placeHolder');
            }
        });

    // -----------------=============================---------------________________ Dimension
       var PLACEHOLDER = ''; 
        var masterObjectsD;
        var queryTerm;
        $('[id$=TextBoxD]').autocomplete({
            minLength: 0,
            source: function(request, response) {
                        queryTerm = request.term;
                        AutoCompleteLookupField.lookupSearchD(request.term, function(result, event)  {
                            if(event.type == 'exception') {
                                  alert(event.message);
                            } else {
                                 masterObjectsD = result;
                                 response(masterObjectsD);
                            }
                        });
                   },
            focus: function( event, ui ) {
                    $('[id$=TextBoxD]').val( ui.item.Name );
                    return false;
                    },
            select: function( event, ui ) {
                        $('[id$=TextBoxD]').val( ui.item.Name );
                        $('[id$=searchIdD]').val( ui.item.Id );
                        return false;
                    },
         })
         .data( "autocomplete" )._renderItem = function( ul, item ) {
            var entry = "<a>" + item.Name;
           
            entry = entry + "</a>";
            entry = entry.replace(queryTerm, "<b>" + queryTerm + "</b>");
            return $( "<li></li>" )
                .data( "item.autocomplete", item )
                .append( entry )
                .appendTo( ul );
        };
            
        // Add or remove placeholder values
        $('[id$=TextBoxD]').val(PLACEHOLDER);
        $('[id$=TextBoxD]').on("focus",  function(event){
            $tgt = $(event.target);
            if($tgt.val() === PLACEHOLDER ){
                $tgt.val('');
                $tgt.removeClass('placeHolder');
            }
        });
        $('[id$=TextBoxD]').on( "blur",  function(event){
            $tgt = $(event.target);
            if($tgt.val() === '' ){
                $tgt.val(PLACEHOLDER);
                $tgt.addClass('placeHolder');
            }
        });

    </script>
                            </body>
        </html>
    </apex:form>
</apex:page>

 
  • November 05, 2016
  • Like
  • 0