• Roy Luo
  • SMARTIE
  • 639 Points
  • Member since 2014
  • LiquidFrameworks

  • Chatter
    Feed
  • 17
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 2
    Questions
  • 90
    Replies
Hi All,

I need your help wiht a SOQL query. In a visualforce page, I need to show in a Visualforce page all the Approval Process Item that is assigned to a logged in user. I am trying to build a SOQL query for this, but finding it much more challenging than regular SOQL queries. Challenge is that I want to provide a link to the Record that is part of the Approval Process.

Could someone help me with a SOQL query that pulls all Approval items peding for the logged in user. Or even help me with the right direction.

Thanks,
Raghu
Hi,
i have a requirement in which i need to get  javascript variables in apex class.If anyone can help with a code example, I'd appreciate it.
Hi All,

I have a VF template with Apex Class on our Production. I update the Apex Class on our sandbox to add a filter criteria to limit the result. unfortunately when I try to deploy it, I receive an error that says "DerekUpdateSource.updateUpdateSource(), Details: System.LimitException: AVTRRT:Too many SOQL queries: 101 (AVTRRT)".

The tricky part is DerekUpdateSource test class is not what I am deploying its a different one and that "DerekUpdateSource" is already deployed on our Production.

What I did was, I run a test on DerekUpdateSource on our Production and it gave the error "Too many SOQL queries: 101 " but on our Sandbox when I run the test it passed.

The only changes that happened on our Org recently was Target Recruit (third party app) deployed a patch update on our production to resolve a bug. After that I can no longer deploy any class that uses queries record. 

Target Recruit on our Sandbox is not yet update to the lastest patch of Target Recruit.

Is the DerekUpdateSource test class that has a problem or the recent patch of target recruit?

If its DerekUpdateSource test class, I really do not have any other ideas how to shorten this.

DerekUpdateSource Test Class:

@IsTest
public class DerekUpdateSource {

    static testmethod void updateUpdateSource(){

        AVTRRT__Config_Settings__c mycs = AVTRRT__Config_Settings__c.getValues('Default');
    if(mycs == null) 
    {
        mycs = new AVTRRT__Config_Settings__c(Name= 'Default');
        mycs.Trigger_Disable_UpdateAccountName__c = true;
        insert mycs;
    }
        Contact c = new contact();
            c.LastName = 'Test';
            c.RecordtypeID = '012A0000000v0La';
            c.AVTRRT__Source__c = null;
        insert c;
        
        AVTRRT__ETCObject__c a = new AVTRRT__ETCObject__c();
            a.AVTRRT__Name__c = 'jobsDB';
            a.AVTRRT__Candidate__c = c.id;
        insert a;        
        AVTRRT__ETCObject__c b = [Select id from AVTRRT__ETCObject__c where AVTRRT__Name__c = 'jobsDB' and AVTRRT__Candidate__c = :c.Id limit 1];
        update b;
        
        Contact c1 = new contact();
            c1.LastName = 'Test1';
            c1.RecordtypeID = '012A0000000v0La';
            c1.AVTRRT__Source__c = null;
        insert c1;
        
        AVTRRT__ETCObject__c e = new AVTRRT__ETCObject__c();
            e.AVTRRT__Name__c = 'Clyde Marine Recruitment';
            e.AVTRRT__Candidate__c = c1.id;
        insert e;
        AVTRRT__ETCObject__c f = [Select id from AVTRRT__ETCObject__c where AVTRRT__Name__c = 'Clyde Marine Recruitment' and AVTRRT__Candidate__c = :c1.Id limit 1];
        update f;
        
        Contact c2 = new contact();
            c2.LastName = 'Test2';
            c2.RecordtypeID = '012A0000000v0La';
            c2.AVTRRT__Source__c = null;
        insert c2;
        
        AVTRRT__ETCObject__c h = new AVTRRT__ETCObject__c();
            h.AVTRRT__Name__c = 'Corporate Event';
            h.AVTRRT__Candidate__c = c2.id;
        insert h;
        AVTRRT__ETCObject__c f1 = [Select id from AVTRRT__ETCObject__c where AVTRRT__Name__c = 'Corporate Event' and AVTRRT__Candidate__c = :c2.Id limit 1];
        update f1;
        
        Contact c3 = new contact();
            c3.LastName = 'Test3';
            c3.RecordtypeID = '012A0000000v0La';
            c3.AVTRRT__Source__c = null;
        insert c3;
        
        AVTRRT__ETCObject__c k = new AVTRRT__ETCObject__c();
            k.AVTRRT__Name__c = 'e Financial Careers';
            k.AVTRRT__Candidate__c = c3.id;
        insert k;
        AVTRRT__ETCObject__c f3 = [Select id from AVTRRT__ETCObject__c where AVTRRT__Name__c = 'e Financial Careers' and AVTRRT__Candidate__c = :c3.Id limit 1];
        update f3; 
        
        Contact c4 = new contact();
            c4.LastName = 'Test4';
            c4.RecordtypeID = '012A0000000v0La';
            c4.AVTRRT__Source__c = null;
        insert c4;
        
        AVTRRT__ETCObject__c n = new AVTRRT__ETCObject__c();
            n.AVTRRT__Name__c = 'Email/Mailer Application';
            n.AVTRRT__Candidate__c = c4.id;
        insert n;
        AVTRRT__ETCObject__c f4 = [Select id from AVTRRT__ETCObject__c where AVTRRT__Name__c = 'Email/Mailer Application' and AVTRRT__Candidate__c = :c4.Id limit 1];
        update f4;
        
        Contact c5 = new contact();
            c5.LastName = 'Test5';
            c5.RecordtypeID = '012A0000000v0La';
            c5.AVTRRT__Source__c = null;
        insert c5;
        
        AVTRRT__ETCObject__c q = new AVTRRT__ETCObject__c();
            q.AVTRRT__Name__c = 'Indeed';
            q.AVTRRT__Candidate__c = c5.id;
        insert q;
        AVTRRT__ETCObject__c f5 = [Select id from AVTRRT__ETCObject__c where AVTRRT__Name__c = 'Indeed' and AVTRRT__Candidate__c = :c5.Id limit 1];
        update f5;      
        
        Contact c6 = new contact();
            c6.LastName = 'Test6';
            c6.RecordtypeID = '012A0000000v0La';
            c6.AVTRRT__Source__c = null;
        insert c6;
        
        AVTRRT__ETCObject__c t = new AVTRRT__ETCObject__c();
            t.AVTRRT__Name__c = 'Jobstreet';
            t.AVTRRT__Candidate__c = c6.id;
        insert t;
        AVTRRT__ETCObject__c f6 = [Select id from AVTRRT__ETCObject__c where AVTRRT__Name__c = 'Jobstreet' and AVTRRT__Candidate__c = :c6.Id limit 1];
        update f6;
        
        Contact c7 = new contact();
            c7.LastName = 'Test7';
            c7.RecordtypeID = '012A0000000v0La';
            c7.AVTRRT__Source__c = null;
        insert c7;
        
        AVTRRT__ETCObject__c w = new AVTRRT__ETCObject__c();
            w.AVTRRT__Name__c = 'LinkedIn - Resourcer';
            w.AVTRRT__Candidate__c = c7.id;
        insert w;
        AVTRRT__ETCObject__c f7 = [Select id from AVTRRT__ETCObject__c where AVTRRT__Name__c = 'LinkedIn - Resourcer' and AVTRRT__Candidate__c = :c7.Id limit 1];
        update f7;
        
        Contact c8 = new contact();
            c8.LastName = 'Test8';
            c8.RecordtypeID = '012A0000000v0La';
            c8.AVTRRT__Source__c = null;
        insert c8;
        
        AVTRRT__ETCObject__c a1 = new AVTRRT__ETCObject__c();
            a1.AVTRRT__Name__c = 'Linkedin Advert';
            a1.AVTRRT__Candidate__c = c8.id;
        insert a1;
        AVTRRT__ETCObject__c f8 = [Select id from AVTRRT__ETCObject__c where AVTRRT__Name__c = 'Linkedin Advert' and AVTRRT__Candidate__c = :c8.Id limit 1];
        update f8;  
        
        Contact c9 = new contact();
            c9.LastName = 'Test8';
            c9.RecordtypeID = '012A0000000v0La';
            c9.AVTRRT__Source__c = null;
        insert c9;
        
        AVTRRT__ETCObject__c a9 = new AVTRRT__ETCObject__c();
            a9.AVTRRT__Name__c = 'Reed';
            a9.AVTRRT__Candidate__c = c9.id;
        insert a9;
        AVTRRT__ETCObject__c f9 = [Select id from AVTRRT__ETCObject__c where AVTRRT__Name__c = 'Reed' and AVTRRT__Candidate__c = :c9.Id limit 1];
        update f9;
        
        Contact c10 = new contact();
            c10.LastName = 'Test10';
            c10.RecordtypeID = '012A0000000v0La';
            c10.AVTRRT__Source__c = null;
        insert c10;
        
        AVTRRT__ETCObject__c a10 = new AVTRRT__ETCObject__c();
            a10.AVTRRT__Name__c = 'Red Website';
            a10.AVTRRT__Candidate__c = c10.id;
        insert a10;
        AVTRRT__ETCObject__c f10 = [Select id from AVTRRT__ETCObject__c where AVTRRT__Name__c = 'Red Website' and AVTRRT__Candidate__c = :c10.Id limit 1];
        update f10;
        
        Contact c11 = new contact();
            c11.LastName = 'Test11';
            c11.RecordtypeID = '012A0000000v0La';
            c11.AVTRRT__Source__c = null;
        insert c11;
        
        AVTRRT__ETCObject__c a11 = new AVTRRT__ETCObject__c();
            a11.AVTRRT__Name__c = 'Trade Winds';
            a11.AVTRRT__Candidate__c = c11.id;
        insert a11;
        AVTRRT__ETCObject__c f11 = [Select id from AVTRRT__ETCObject__c where AVTRRT__Name__c = 'Trade Winds' and AVTRRT__Candidate__c = :c11.Id limit 1];
        update f11;
}
}
I have the following test class and its erroring with a list has no rows for assignment to SObject and it gives this line number
CW_alertUpdate controller = new CW_alertUpdate(sc); //This is to initialize your class

Not sure what I'm missing, I'm a newbie to test classes
 
@isTest
private class CW_alertUpdateTest {

static testMethod void CW_alertUpdateTest() {
//creates new alert
Alerts__c a1 = new Alerts__c();
a1.Account_Name__c = '00119000003QPkD';
a1.Subject__c = 'This is an Alert';
a1.Alert_Status__c = 'Initial';
a1.Product__c = 'Fleet';
a1.Customer_Impact__c = 'This is a huge impact to site';
a1.Completed_Actions__c = 'This is what I have done';
a1.Next_Actions__c = 'This is what I will do next';
a1.Incident_Ticket_Number__c='50019000000zkD4';
//a1.Incident_Reported__c==Date.today();
a1.Incident_Start__c=Date.today();
a1.Incident_Manager__c='005a00000086FDq';
a1.Team_List__c='Matt Mansfield';
a1.CGM_P1_APD_MANNED__c=true;
a1.CGM_P1_Command__c=false;
a1.CGM_P1_EAME_MANNED__c=false;
a1.CGM_P1_AMERICAS_MANNED__c=false;
a1.CGM_P1_SOUTH_AMERICAS_MANNED__c=false;
//a1.Master_AlertText__c='';
insert a1;

//creates new alert
Alerts__c a2 = new Alerts__c();
a2.Account_Name__c = a1.Account_Name__c;
a2.Subject__c = a1.Subject__c;
a2.Alert_Status__c = 'Update';
a2.Product__c = a1.Product__c;
a2.Customer_Impact__c = a1.Customer_Impact__c;
a2.Completed_Actions__c = a1.Completed_Actions__c;
a2.Next_Actions__c = a1.Next_Actions__c;
a2.Incident_Ticket_Number__c=a1.Incident_Ticket_Number__c;
//a2.Incident_Reported__c==Date.today();
a2.Incident_Start__c=a1.Incident_Start__c;
a2.Incident_Manager__c=a1.Incident_Manager__c;
a2.Team_List__c=a1.Team_List__c;
a2.CGM_P1_APD_MANNED__c=a1.CGM_P1_APD_MANNED__c;
a2.CGM_P1_Command__c=a1.CGM_P1_Command__c;
a2.CGM_P1_EAME_MANNED__c=a1.CGM_P1_EAME_MANNED__c;
a2.CGM_P1_AMERICAS_MANNED__c=a1.CGM_P1_AMERICAS_MANNED__c;
a2.CGM_P1_SOUTH_AMERICAS_MANNED__c=a1.CGM_P1_SOUTH_AMERICAS_MANNED__c;
a2.Master_AlertText__c=a1.Name;
insert a2;



//test.startTest();
           ApexPages.StandardController sc = new ApexPages.StandardController(a1);
           CW_alertUpdate controller = new CW_alertUpdate(sc); //This is to initialize your class
      
pageReference retPage = Page.CW_AlertUpdate; 

ID alertID = retPage.getParameters().put('newid',a2.ID); 
ID alertID1 = retPage.getParameters().put('alertID',a1.ID); 



Test.setCurrentPage(retPage);
retPage = controller.autoRun();

//test.stopTest();

}}
 
public class CW_alertUpdate{

public final Alerts__c alertID;
public Alerts__c newAlert{get;set;}
   
    public CW_alertUpdate(ApexPages.StandardController controller) {
        //gets fields from previous case
        alertID = [SELECT Id, Master_AlertText__c, Incident_Ticket_Number__c FROM Alerts__c WHERE Id = :ApexPages.currentPage().getParameters().get('alertID')];
      }
     public pageReference autorun(){
         //create a new Alert
         Alerts__c newAlert = new Alerts__c(Id = ApexPages.currentPage().getParameters().get('newid'));
          
          // Fill in the values for the new record from previous case
        if(alertID.Master_AlertText__c == NULL)
        {
         newAlert.Master_AlertText__c = alertID.Id;
         }
         //Update the new Alert record
        update newAlert;
        system.debug(newAlert);
     
        
        //create a new Case Alert Association - Junction Object
        Case_Alert_Association__c newCAA = new Case_Alert_Association__c();
         // Fill in the values for the new record
         newCAA.Alerts__c = newAlert.id;
         newCAA.Case__c = alertID.Incident_Ticket_Number__c;
                
        //Insert the new Case Alert Association record
        Database.insert (newCAA);
        system.debug(newCAA);
                    
        
        system.debug(newAlert);
        PageReference retPage = new PageReference('/' + newAlert.id);
        return retPage; 
        
        
       }


    }




 
  • November 12, 2014
  • Like
  • 0
Hi all,
In first VF page I am getting basic Lead information and I want to pass that information to another VF page which will have detailed information about the Lead. Now after click on Save button I need to pass that record information and then add more info and save that Lead.

Here is my first VF page:
<apex:page controller="myLeadController">
    <apex:sectionHeader title="New Lead Page" />
    <apex:form >
        <apex:pageBlock title="Create a New Lead">
            <apex:pageBlockButtons >
                <apex:commandButton action="{!save}" value="Save"/>
            </apex:pageBlockButtons>        
            <apex:pageBlockSection title="Lead Information">
                <apex:inputField id="firstName" value="{!Lead.FirstName}"/>
                <apex:inputField id="lastName" value="{!Lead.LastName}"/>
                <apex:inputField id="companyName" value="{!Lead.Company}"/>
            </apex:pageBlockSection>
        </apex:pageBlock>
    </apex:form>
</apex:page>

public class myLeadController {
    
    Lead lead;

    public Lead getLead() {
        if(lead == null) lead = new Lead();
        return lead;
    }
    
    public PageReference save() {
        // Add the lead to the database. 
        insert lead;
        // Send the user to the detail page for the new lead.
       // need to pass the record id to Thankyou Page
        PageReference leadPage = new ApexPages.Thankyou
        leadPage.setRedirect(true);
        return leadPage;
    }

}
Can't get any coverage on this, and can't figure out why. Both this class and the test cases were written by another developer (who is not available anymore to ask questions of). But I can't get any coverage on this no matter what I try. Any help is greatly appreciated.

Going to have to put this code up in parts as it is too large.
public without sharing class MyProfileController {
    public String fname{set;get;}
    public String lname{set;get;}
    public String fullmiddelname{set;get;}
    public String pemail{set;get;}
    public String semail{set;get;}
    public String mobile{set;get;}
    public String home{set;get;}
    public String work{set;get;}
    public String street{set;get;}
    public String city{set;get;}
    public String state{set;get;}
    public String zip{set;get;}
    public String country{set;get;}
    public String facebook{set;get;}
    public String twitter{set;get;}
    public String linkedin{set;get;}
    public String birthdate{set;get;}
    public String gender{set;get;}
    public String race{set;get;}
    public String profession{set;get;}
    public String pinterest{set;get;}
    public String ainterest{set;get;}    
    public String ointerest{set;get;}    
    public String corpregion{set;get;}
    public String alumniregion{set;get;}
    public String corpregionView{set;get;}
    public String alumniregionView{set;get;}
    public String corpYear{set;get;}
    public boolean HasOptedOutOfEmail{get;set;}
    public boolean DoNotCall{get;set;}
    public boolean memberoptout{set;get;}
    public List<SelectOption> corpRegions{get;set;}
    public List<SelectOption> advocacyInterests{get;set;}
    public List<SelectOption> policyInterests{get;set;}
    public List<SelectOption> organizingInterests{get;set;}
    public List<SelectOption> ethnicityOntions{get;set;}
    public blob imagebody{set;get;}
    public string imageName{set;get;}
    public string imagesrc{set;get;}
    public string imagesrc1{set;get;}
    public boolean isEditable{set;get;}
    public boolean registered{set;get;}
    public String leadership{set;get;}
    public List<SelectOption> leaderships{get;set;}
    public List<SelectOption> volunteerInterests{get;set;}
    public String volunteerInterest{set;get;}
    List<Region__c> corpRegionsList;
    List<Region__c> alumniRegionsList;
    Map<String,Region__c> regionsMap;
    String oldZip;
    String contactId;
    List<Attachment> att;
    public Contact con{set;get;}
    Attachment img;
    Contact_Picture__c contactImage;
    public LEE_Campaign__c leecamp{set;get;}
    public boolean showErr{set;get;}
    List<Region_ZipCode__c> zipcodes;
    List<Region_Membership__c> regionMembers;
    Decimal filesize;
    public boolean isError{set;get;}
    public String errorMsg{set;get;}
    public string title{set;get;}
    public string employer{set;get;}
    public MyProfileController(){
        isError = false;
        regionsMap = new Map<String,Region__c>();
        leecamp = new LEE_Campaign__c();
        showErr = false;
        User loggedUser = [SELECT id,ContactID from User WHERE Id=: userInfo.getUserId()];
        //contactId = ApexPages.currentPage().getParameters().get('id');
        contactId = loggedUser.ContactId;
       // contactId = '003M000000Dp9z9';
        isEditable = false;
        policyInterests =  new List<SelectOption>();
        advocacyInterests = new List<SelectOption>();
        organizingInterests = new List<SelectOption>();
        ethnicityOntions = new List<SelectOption>();
        leaderships = new List<SelectOption>();
        volunteerInterests  = new List<SelectOption>();
        //Populate Advocacy Interest Picklist
        Schema.DescribeFieldResult fieldResult = Contact.Advocacy_Interest__c.getDescribe();
        List<Schema.PicklistEntry> ple = fieldResult.getPicklistValues();
        for(Schema.PicklistEntry f : ple){
            advocacyInterests.add(new SelectOption(f.getLabel(), f.getValue()));
        }
        //Populate Policy Interest Picklist
        fieldResult =  Contact.Policy_Interest__c.getDescribe();
        ple = fieldResult.getPicklistValues();
        for(Schema.PicklistEntry f : ple){
            policyInterests.add(new SelectOption(f.getLabel(), f.getValue()));
        }
        
        //Populate Organizing Interest Picklist
        fieldResult =  Contact.Organizing_Interest__c.getDescribe();
        ple = fieldResult.getPicklistValues();
        for(Schema.PicklistEntry f : ple){
            organizingInterests.add(new SelectOption(f.getLabel(), f.getValue()));
        }
        //Populate Ethnicity Picklist
        fieldResult =  Contact.Ethnicity__c.getDescribe();
        ple = fieldResult.getPicklistValues();
        for(Schema.PicklistEntry f : ple){
            ethnicityOntions.add(new SelectOption(f.getLabel(), f.getValue()));
        }
        
        //Populate Public Leadership Aspirations Picklist
        fieldResult =  Contact.Public_Leadership_Aspirations__c.getDescribe();
        ple = fieldResult.getPicklistValues();
        for(Schema.PicklistEntry f : ple){
            leaderships.add(new SelectOption(f.getLabel(), f.getValue()));
        }
        //Populate Volunteer Interests Picklist
        fieldResult =  Contact.Volunteer_Interests__c.getDescribe();
        ple = fieldResult.getPicklistValues();
        for(Schema.PicklistEntry f : ple){
            volunteerInterests.add(new SelectOption(f.getLabel(), f.getValue()));
        }
        
        //contactId = ApexPages.currentPage().getParameters().get('contactId');
        corpRegions = new List<SelectOption>();
        corpRegionsList = [SELECT id,Name from Region__c];
        //Populate Corp Region and Amumni Region Picklist
        if(corpRegionsList != null && corpRegionsList.size() > 0){
            for(Region__c r: corpRegionsList){
                corpRegions.add(new SelectOption(r.Id,r.Name));
                regionsMap.put(r.Name,r);
            }
        }else{
            corpRegions.add(new SelectOption('',''));
        }
        
        if(contactId != null && contactId.trim().length() > 0){
            con = [Select c.Twitter__c,  c.Secondary_Email__c,
                        c.Ethnicity__c, c.Profession__c, c.Policy_Interest__c, Volunteer_Interests__c,
                        c.Phone,  c.Organizing_Interest__c, c.Name, c.MobilePhone, c.Member_Stage__c,
                        c.MailingStreet, c.MailingState, c.MailingPostalCode, c.MailingCountry, c.MailingCity, c.DoNotCall,
                        c.Linked_In__c, c.LeadSource, c.LastName,  c.Id, c.HomePhone, Registered_to_Vote__c,
                        c.Gender__c, c.Full_Middle_Name__c, c.FirstName, c.Fax, c.Facebook__c, Public_Leadership_Aspirations__c,
                        c.Email,c.Corps_Year__c, c.Corp_Region__c, c.Birthdate, c.Alumni_Region__c, c.Advocacy_Interest__c, c.HasOptedOutOfEmail,
                        c.Employee_Title__c,c.Employment_Organization__c
                    From Contact c
                    WHERE Id=: contactId];
                    
            if(con != null){
                fname = con.FirstName;
                lname = con.LastName;
                fullmiddelName = con.Full_Middle_Name__c;
                home = con.HomePhone;
                mobile = con.MobilePhone;
                work = con.Phone;
                pemail = con.Email;
                semail = con.Secondary_Email__c;
                facebook = con.Facebook__c;
                twitter = con.Twitter__c;
                linkedin = con.Linked_In__c;
                street = con.MailingStreet;
                city = con.MailingCity;
                state = con.MailingState;
                zip = con.MailingPostalCode;
                oldZip = zip;
                country = con.MailingCountry;
                title = con.Employee_Title__c;
                employer = con.Employment_Organization__c;
                //birthdate = String.valueOf(con.BirthDate);
                race = con.Ethnicity__c;
                profession = con.Profession__c;
                gender = con.Gender__c;
                pinterest = con.Policy_Interest__c;
                ainterest = con.Advocacy_Interest__c;
                ointerest = con.Organizing_Interest__c;
                corpregion = con.Corp_Region__c;
                alumniregion = con.Alumni_Region__c;
                if(con.HasOptedOutOfEmail != null)
                    HasOptedOutOfEmail = con.HasOptedOutOfEmail;
                else
                    HasOptedOutOfEmail = false;
                if(con.DoNotCall != null)
                    DoNotCall = con.DoNotCall;
                else
                    DoNotCall = false;
                for(SelectOption so:corpRegions){
                    if(so.getValue() == corpregion){
                        corpregionView = so.getLabel();
                    }
                }
                
                for(SelectOption so:corpRegions){
                    if(so.getValue() == alumniregion){
                        alumniregionView = so.getLabel();
                    }
                }
                corpYear = con.Corps_Year__c;
                if(con.Member_Stage__c == 'Deactivated'){
                    memberoptout = true;
                }else{
                    memberoptout = false;
                }
                registered = con.Registered_to_Vote__c;
                String str = con.Public_Leadership_Aspirations__c;
                
                /*str = str.replaceAll(';',',');
                str ='['+str + ']';*/
                leadership = str;
                System.Debug('@@@@@@@@Value'+leadership);
                volunteerInterest = con.Volunteer_Interests__c;
                
                List<Contact_Picture__c> contactImages = [SELECT id,Contact__c from Contact_Picture__c WHERE Contact__c =: con.id];
                if(contactImages != null && contactImages.size() >0){
                    contactImage = contactImages[0];
                    att = [SELECT id,Name from Attachment WHERE parentId =: contactImage.Id Order By CreatedDate Desc LIMIT 1];
                    if(att != null && att.size() > 0){
                        System.Debug('######Attachment ID'+att[0].id);
                        //imagebody = att[0].body;
                       /* imagesrc1 = String.valueOf(imagebody);
                        System.Debug('######Image Body'+imagesrc1);*/
                        //imageName = att[0].Name;
                        imagesrc = '/servlet/servlet.FileDownload?file='+att[0].id;
                    }
                }
                
            }else{
                con = new Contact();
            }
        }
    }
    public void upload(){       
        if(imageName != null && imageBody != null){
            filesize = imageBody.size();
            filesize = filesize /(1024*1024);
            if(filesize <= 1){
                if(con != null && con.id != null){
                    if( contactImage != null && contactImage.Contact__c != null){
                        img = new Attachment(Name = imageName,Body=imageBody,ParentId = contactImage.id);
                        insert img;
                    }else{
                        contactImage = new  Contact_Picture__c(Contact__c = con.Id);
                        insert contactImage;
                        img = new Attachment(Name = imageName,Body=imageBody,ParentId = contactImage.id);
                        insert img;
                    }
                    imagesrc = '/servlet/servlet.FileDownload?file='+img.id;
                    imageBody = null;
                    img = null;
                    isError = false;
                }
            }else{
                isError = true;
                errorMsg = 'File Size can not be more than 1 MB';
                //ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR, 'File Size can not be more than 1 MB'));
                imageBody = null;
                return;
            }
        }
    }

 
I have a picklist field called  'Policy__c.policyTerm__c'  that contains the following values; 1month, 2months,3months, other. If 'other' is selected I would like to render a field called; 'Policy__c.policyOtherTerm__c' just below it. 

I have several of these types of fields where 'other' is a picklist value scattered thru a visualforce page. What is the best way to use the <apex:actionSupport> component to accomplish this ?

Have seen several post on rendering output panels,... but its not clear how to best accomplish this.



 

So I have a strange error. I have a bit of code that is updating leads and adding them as members to campaigns when a field is updated from an external tool with a campign ID. It works fine in my testing, but in the last day have been getting the following error when the external tool is touching the record. From what I can see, the field in quesiton is not being accessed:

 

LeadCreateCampaignMember: execution of AfterUpdate
caused by: System.StringException: Invalid id: undefined
Trigger.LeadCreateCampaignMember: line 24, column 1

I will bold line 24 in this case:


/* 
Author: John Athitakis
Synopsis: When a new or existing Lead has a special string field populated, an event is created with that string as its subject line
*/

trigger LeadCreateCampaignMember on Lead (after insert, after update) {
   //  Logic: On insert if the Event Activity Field is Populated, Create an Event.
 if(Trigger.IsInsert) {
 for (Lead UpdatedLead: Trigger.new) {
     if(UpdatedLead.campaign_id__c!=null){ 
            CampaignMember cml = new CampaignMember();
            cml.campaignid = UpdatedLead.campaign_id__c;
            cml.leadid = UpdatedLead.id;
            Database.upsert(cml, false) ;
     }
 }
 }
   // Logic: On update, if there is a change in the Event Activity Field & it is not Null, Create an Event 
 if(Trigger.IsUpdate){
     for (Lead UpdatedLead2: Trigger.new) {
      Lead PriorLead = Trigger.oldMap.get(UpdatedLead2.ID);
         if (UpdatedLead2.campaign_id__c != PriorLead.campaign_id__c && UpdatedLead2.campaign_id__c!=null){
          CampaignMember cml2 = new CampaignMember();
          cml2.campaignid = UpdatedLead2.campaign_id__c;
          cml2.leadid = UpdatedLead2.id;
          Database.upsert(cml2, false);
}
     }}}
 Obviously

Hi All,

I am new to slesforce. i have created a stadard object and creating the Visual force page for he same. I have 2 checkboxes., on clicking the first one, second should become disable/Hide.

i m using the change jquery event when first check box is selected nd trying to toggle the second checkbox. But my change event is not getting called. 

I m not ble to find the exact reson. Please hve a look on the code.


<apex:page standardController="Batch__c" >
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <script> $(document).ready(function(){
alert('testfirst');
$("#studentnoptification").change(function(){  ===> control not reaching here
alert('test');
$("#isprof").toggle();
});
});
</script>
<apex:form >
<apex:pageBlock>
<apex:pageBlockSection id="pbSection1" columns="1">
<apex:inputfield value="{!Batch__c.Name}" id="Bus" required="true"/>
<apex:inputfield value="{!Batch__c.isstudent__c}" id="studentnoptification"/>
<apex:inputfield value="{!Batch__c.Lab_Timing__c}" required="true"/>
<apex:inputfield value="{!Batch__c.isproffessional__c}" id="isprof"/>
</apex:pageBlockSection>
<apex:pageBlockButtons > <apex:commandbutton value="Save" action="{!save}"></apex:commandbutton> <apex:commandbutton value="Save & new" action="{!quicksave}"></apex:commandbutton> <apex:commandbutton value="Cancel" action="{!cancel}"></apex:commandbutton>
</apex:pageBlockButtons>
</apex:pageBlock>
</apex:form>
</apex:page>


Thanks in Advance
 
Doing Trailhead exercise here: https://developer.salesforce.com/en/trailhead/force_com_programmatic_beginner/apex_database/apex_database_intro

This is my code:
 
public class StringArrayTest {
    public static generateStringArray(Integer x) {
        List<String> stringList = new List<String>();
        for (integer n=0; n<x; n++) {
            stringList.add('Test '+n);
        }
        return stringList;
    }
}
I get the error message "Constructors cannot be static" on line 2, but I can not find anywhere an example of a public static method that returns a value.  How can I fix this?

Thank you,
Brian
 

Okay... So I'm very new to Salesforce. And I'm trying to deploy 1 package that has 86 percent coverage in the Sandbox.

But when I go to deploy it in the live system, it is telling me
" Details: Average test coverage across all Apex Classes and Triggers is 55%, at least 75% test coverage is required."

However... when I go to the Develop section and look at the Manage Your Apex Classes., I do the Estimate Code Coverage... and it is listing as 81 percent.

What on earth is the problem? And how do I go about fixing it? 

I've cleared all the data, and re-run all the tests... but no go... and I'm seriously stumped. I can't find anything online that could help me.

So attached is the code i have in place that im looking to have uncheck a checkbox on a record if its in a list after a record has been updated or added. The class is also there to stop the infinate loop. But its still allowing for me to have multiple checked address records. Can anyone see what im missing...
Apex Code:

trigger PrimaryAddressValidation on ShipTo_Address__c (after insert, after update) {
	
   if (SingleExecution.hasAlreadyDone()) {
  		return;
	}
		SingleExecution.setAlreadyDone();
	
  Contact c=[select id from contact where id in(select Contact__c from ShipTo_Address__c where id in:trigger.new)];
  
  list<ShipTo_Address__c> addList=new list<ShipTo_Address__c>([select id from ShipTo_Address__c where Contact__c in:Trigger.newMap.keySet()]);
  
  Id selectedAddressId;
  
  list<ShipTo_Address__c> updateList=new list<ShipTo_Address__c>(); 
  
  for(ShipTo_Address__c add:Trigger.new)
   {
     if(add.Default_Shipping_Address__c==true)
     {
        c.OtherStreet = add.Address__c; 
        c.OtherCity = add.City__c; 
        c.OtherState = add.State__c; 
        c.OtherCountry = add.Country__c; 
        c.OtherPostalCode = add.ZIP__c; 
     }
   }
   
   for(ShipTo_Address__c aa:addList)
    {
      if(aa.Id!= selectedAddressId)
      {
           aa.Default_Shipping_Address__c=false;
           updateList.add(aa);
      }
    }
 
 update updateList;
 
 update c;
}
Class:

public with sharing class SingleExecution {

private static boolean blnAlreadyDone = false;

public static boolean hasAlreadyDone() {
    return blnAlreadyDone;
}

public static void setAlreadyDone() {
    blnAlreadyDone = true;
}

public static void forceResetAlreadyDone() {
    blnAlreadyDone = false;
}

}

Hopefully someone has dealt with this before. Also i have a primary billing checkbox as well. Can i add that into this same trigger or should i create a new one for that.
 
Hello Everyone,
I am trying send out the email and create a case when the email has been sentout from the system

I am able to send the Email,but when i try to create a records for the case its not happening.
Here is the code 

##################Visual forcePage#########################################<apex:page standardController="Contact" tabStyle="contact" showHeader="true" showChat="false" extensions="sendEmail,SubmitCaseController">
<apex:form >
  <apex:pageBlock title="Termination Form">
  <apex:pageblockSection columns="2" >
  <apex:outputField value="{!contact.LastName}"/>
  <apex:outputField value="{!contact.FirstName}"/>
  <apex:outputField value="{!contact.Phone}"/>
  </apex:pageblockSection>
  <apex:pageblockButtons >  
  <apex:commandButton value="Save" action="{!Save}"/>
  <apex:commandButton value="Send Email" action="{!send}" /> 
  </apex:pageblockButtons>
  </apex:pageBlock>
</apex:form>
  </apex:page>

First Extention that trigger email   -----By using this extension i am trying to sendout email
public class sendEmail {

    public sendEmail(ApexPages.StandardController controller) {
    contact = [ select Id,LastName,FirstName,Phone,Email from contact where id = :ApexPages.currentPage().getParameters().get('id')];

    }

    public String subject { get; set; }
    public String body { get; set; }

    private final Contact contact;
    public contact getcontact() {
        return contact;
    }
    public PageReference send() {
      
       /* Messaging.SingleEmailMessage message = new Messaging.SingleEmailMessage();
        String[] toAddresses = new String[] {'}; 
        String[] ccAddresses = new String[] {'}; 
        message.setTemplateId('00Xo0000000YyL2');
        message.setTargetObjectId('005o0000000kUqP');
        message.setToAddresses(toAddresses);
        system.debug('ToAddress@@@@@@@'+ toAddresses );
        system.debug('CCC@@@Address@@@@@@@'+ ccAddresses );
        message.setccAddresses(ccAddresses );
        message.setBccSender(false);
        message.saveAsActivity=false;
        Messaging.sendEmail(new Messaging.SingleEmailMessage[]{ message });
        system.debug('MessageSent@@@@@@@@@@@@@@@@@@@@@@@'+message );
        //return controller.view();
        */
       return null;
    }
}

Second Extension that creates a case   -----By using this extension i am trying to create a case ,but the case has not been created
public class SubmitCaseController {
   public Case c { get; set; }
     public final Contact cnt ;
    public SubmitCaseController(ApexPages.StandardController controller) {
        c = new Case();
        cnt = [ select Id,LastName,FirstName,Phone,Email from contact where id = :ApexPages.currentPage().getParameters().get('id')];
        system.debug('cntlist@@@@'+cnt);
    }
    public contact getcontact() {
        return cnt ;
    }
    public PageReference send() {
    try{
    if(cnt!=null)
    {
          c.ContactId = cnt.Id;
          c.Status='New';
          c.Origin='Email';
          c.Reason='Other';
          system.debug('Caselist@@@@@@@@@@@@@@@@@@'+c);
          insert c;
    }      

     }catch(DMLException e){
         ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR,'Error creating new case.'));
     }
     
    
   
     return new PageReference('/thanks');
    }
    

}


Thanks a lot

Regards,
Jyo


 

Error: Compile Error: Invalid bind expression type of Schema.SObjectField for column of type Decimal at line 13 column 75@isTest
public class Testcreatedeal{
 
static testMethod void deal()
 {
 Test_1__c a = new Test_1__c();
 a.Number__c=34;
 
 insert a;
 
 ApexPages.standardController controller = new ApexPages.standardController(a);

 list<Test_2__c>  b=[select id,Number__c from Test_2__c where Number__c=: Test_1__c.Number__c];//line 13
 System.assertEquals(1, Test_2__c.size());  
 }


vf page:
<apex:page standardController="Test_1__c"   extensions="CreateDeal"  action="{!deal}">
</apex:page>

controller*************
public class CreateDeal
 {
  
 
    private id accountId{get;set;} 
     public Test_1__c b{get;set;}

    
    public CreateDeal(ApexPages.StandardController controller) 
    {
    accountId= ApexPages.currentPage().getParameters().get('id');
    system.debug('+++'+accountId);
    }
    
    public  pageReference  deal()
    {
     Test_1__c  b = [Select id,Name__c,Number__c,Phone__c from Test_1__c  where id =:accountId];
     Test_2__c a = new Test_2__c();
     {
     
      a.Name__c=b.Name__c;
      a.Number__c=b.Number__c;
      a.Phone__c=b.Phone__c;
      }
      insert a;
      
    //Schema.DescribeSObjectResult result = Test_2__c.SObjectType.getDescribe();

    PageReference pageRef = new PageReference('/'+a.id);
    pageRef.setRedirect(true);
    return pageRef;
    }
}
any help ??  and is my test class correct  basically on one object there are field ,when i click button( custom button on which m calling this vf page) it populates fields into other object just.
I am new to Apex development, and am trying to figure out how to get past the !lead.isConverted part of my Trigger in the Test case.  The test case is only making it to the IF Statement of the Trigger.

Thank you in advance for your help.
trigger LeadConvertVerified on Lead (after Update) {
string convertStatus = 'Closed - Converted';
List<Database.LeadConvert> leadConverts = new List<Database.LeadConvert>();
for (Lead lead: Trigger.new) {
   if (!lead.isConverted && lead.Verified__c == True){
    Database.LeadConvert lc = new Database.LeadConvert();
    lc.setLeadId(lead.Id);
    lc.setAccountId(lead.Organization__c);
    lc.setDoNotCreateOpportunity(TRUE);
    lc.ConvertedStatus= convertStatus;
    leadConverts.add(lc);
        }
    }
if (!leadConverts.isEmpty()) {
List<Database.LeadConvertResult> lcr = Database.convertLead(leadConverts);
}
}

@istest
private class LeadConversionTriggerTestClass {

Static testMethod void LeadConvertTriggerTestClass() {
//Test Against Verified Lead
  Lead l1 = New Lead();
   l1.IsConverted = False;
   l1.FirstName = 'TestOne';
  l1.LastName = 'Testing';
  l1.Organization__c = '001L000000TSsoD';
  l1.Email = 'testone@testing.com';
  l1.Company = 'Individual';
  l1.Verified__C = True;
  insert l1;
    Database.LeadConvert lc = new database.LeadConvert();
         lc.setLeadId(l1.Id);
         LeadStatus convertStatus = [SELECT Id, MasterLabel FROM LeadStatus WHERE IsConverted=true LIMIT 1];
         lc.setConvertedStatus(convertStatus.MasterLabel);
         Database.LeadConvertResult lcr = Database.convertLead(lc);
    
//Test Against Un Verified Lead
Lead l2 = New Lead();
    l2.IsConverted = False;
  l2.FirstName = 'TestOne';
  l2.LastName = 'Testing';
  l2.Organization__c = '001L000000TSsoD';
  l2.Email = 'testone@testing.com';
  l2.Company = 'Individual';
  l2.Verified__C = False;
  insert l2;    
    Database.LeadConvert lc2 = new database.LeadConvert();
         lc.setLeadId(l2.Id);
         LeadStatus convertStatus2 = [SELECT Id, MasterLabel FROM LeadStatus WHERE IsConverted=true LIMIT 1];
         lc.setConvertedStatus(convertStatus2.MasterLabel);
         Database.LeadConvertResult lcr2 = Database.convertLead(lc);
  }
  }
[SELECT Contact.FirstName, Contact.Account.Name from Contact order by Contact.Account.Name  limit 1000]

Why is this query not working
I am trying to find the duplicate emails under same account.
I have limited soql abilities so I didn't use "group" in my query at the time.
i wrote a batch apex class to process all the contacts to find the duplicate pairs but I got error "Batch Apex Error: Batchable Instance Is Too Big"
I tried the following:
1. Change the batch size to be 150 or 180.  
2. Searched this error in this forum, people encountered this when they were importing csv files or when they mistakenly added "Database.Stateful" keyword.

I don't quite understand the heap limit here, for each batch, what is the limit?  How can I know which part of my code comsumes most of the heap so I can try to fix my code?
Thank you!

 
global class ContactsCleaning implements Database.Batchable<sObject>,Database.Stateful{
    //query: select id,Accountid,email from Contact where email !=null and email!='\'\'' and accountid!=null and accountid!='\'\''
    public Map<AccountEmail,List<Contact>> duplicatePairs=new Map<AccountEmail,List<Contact>>();
    public integer totalemail=0;
    public integer totalcontact=0;
    global final String query;
    global ContactsCleaning(String q){
        query=q;
    }    
    global Database.QueryLocator start(Database.BatchableContext BC){
        return Database.getQueryLocator(query);
    }
    global void execute(Database.BatchableContext BC, List<Contact> scope)
    {
        for(Contact c : scope)
        {                        
                //check if email&account pair exists
                AccountEmail ae=new AccountEmail(c.AccountId,c.Email);
                if(duplicatePairs.containsKey(ae))
                {
                    duplicatePairs.get(ae).add(c);                  
                }
                else
                {                    
                    List<Contact> cl=new List<Contact>();
                    cl.add(c);
                    duplicatePairs.put(ae, cl);                    
                }            
        }                
    }    
    global void finish(Database.BatchableContext BC)
    {
        Document d=new Document();
        d.Name='Duplicate Emails';
        d.folderid = UserInfo.getUserId();
        String content='';
        for(AccountEmail ae : duplicatePairs.keySet())
        {
            if(duplicatePairs.get(ae).size()<=1)
            {
                duplicatePairs.remove(ae);
            }
            else
            {
                List<Contact> ls=duplicatePairs.get(ae);
                content=content+'Account: '+ae.AccountID+'   '+'Email:   '+ae.Email+'   ';
                Integer i=1;
                for(Contact c : ls)
                {
                    content=content+i+'   '+'ContactId:  '+c.Id+'   ';
                    i++;
                }
                content+='\n';
            }
        }
        d.Body=Blob.valueOf(content);
        d.ContentType='text/plain';
        d.Type='txt';
        insert d;
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        String[] toAddresses = new String[] {'jack.wang@accelerationretirement.com'};
        mail.setToAddresses(toAddresses);
        mail.setSubject('Duplicate Email Stats');
        mail.setPlainTextBody('Total Contacts:   '+totalcontact+'\n'+'Total Emails:   '+totalemail+'\n'+'Deplicate Pairs:   '+duplicatePairs.size());
        mail.setHtmlBody('<div>Total Contacts:   '+totalcontact+'</div>'+'Total Emails:   '+totalemail+'</div><div>Deplicate Pairs:   '+duplicatePairs.size()+'</div>');
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });                                
    }    
}
//This class is the key to dedup email of Contact
public class AccountEmail {
    public String AccountID;
    public String Email;
    public AccountEmail()
    {
    }
    public AccountEmail(String acctid,String e)
    {
        AccountID=acctid;
        Email=e;
    }
    public Boolean equals(Object obj) {
        if (obj instanceof AccountEmail) {
            AccountEmail p = (AccountEmail)obj;
            return ((AccountID==p.AccountID) && (Email==p.Email));
        }
        return false;
    }

    public Integer hashCode() {
        return (31 * AccountID.hashCode()) ^ (Email.hashCode());
    }

}






 
In unit tests, System.scheduleBatch only schdules the job and the batchable won't execute. You should see the scheduled job with this query:
SELECT Count() FROM CronTrigger WHERE CronJobDetail.Name='...'
But that is very much it. System.assert on your expected results from the batchable will always fail. 

A picture Code is worth a thousand words, here are the batchable and unit tests I have:
 
public class MyBatchable implements Database.Batchable<SObject>
{
    String soqlQuery {get;set;}
    String AccountNumber {get;set;}
    
    public MyBatchable(String acctNumber)
    {
        soqlQuery = 'SELECT Id, Name, AccountNumber FROM Account';
        AccountNumber = acctNumber;
    }
    
    public Database.QueryLocator start(Database.BatchableContext BC)
    {          
        return Database.getQueryLocator(soqlQuery);
    }
 
    public  void execute(Database.BatchableContext BC, List<SObject> scope)
    {        
        List<Account> accounts = (List<Account>)scope;
        for(Account a: accounts)
        {
            a.AccountNumber = AccountNumber ;
        }
        update accounts;
    }
 
    public void finish(Database.BatchableContext BC)
    {   
    }
}
 
@isTest
private class MyBatchableTest
{
    static testmethod void DatabaseExcuteBatch_Test()
    {
        Test.startTest();
        SetupTestData(100);
        String acctNumber = '987654321';
        
        Database.executeBatch(new MyBatchable(acctNumber));
        
        Test.stopTest();
        Integer count = [SELECT COUNT() FROM Account WHERE AccountNumber=:acctNumber];
        System.assertEquals(100, count);
    }
    
    static testmethod void ScheduleBatch_Test()
    {
        Test.startTest();
        SetupTestData(100);
        String acctNumber = '987654321';  
              
        System.scheduleBatch(new MyBatchable(acctNumber), 'MyBatchable', 1);
        
        Test.stopTest();
        Integer count = [SELECT COUNT() FROM Account WHERE AccountNumber=:acctNumber];
        System.assertEquals(100, count);
    }   
    
    static void SetupTestData(Integer acctCount)
    {       
        List<Account> accts = new List<Account>();
        for(Integer i=0; i<acctCount; i++)
        {
            accts.add(new Account(Name=getGuid()));
        }
        insert accts;
    }
    
    static String getGuid()
    {
        String v = EncodingUtil.convertToHex(Crypto.generateDigest('SHA1', Blob.valueOf(EncodingUtil.ConvertTohex(Crypto.GenerateAESKey(128))))).toUpperCase(); 
        return (v.subString(0,8) + '-' + v.subString(8,12) + '-' + v.subString(12,16) + '-' + v.subString(16,20) + '-' + v.subString(20,32)).ToUpperCase();
    }
}


DatabaseExcuteBatch_Test calling Database.executeBatch will pass while ScheduleBatch_Test (with System.scheduleBatch) fails.

So unit testing codes with System.scheduleBatch would require two pieces, one to test the job is scheduled and another one to test data results from your batchable. 

 
I have a dev org working fine with the new Queueable interface. Then I need to setup a new org for QA and that org won't compile class implementing Queueable. Some dude suggested changing it to 'queueable' and that seems to fool the compiler, but codes never get run and workbench apex execute tells me this 'COMPILE ERROR: Method does not exist or incorrect signature: System.enqueue(new QTest())'. Is there any config setting I need to turn on in order to use Queueable? Class and codes are on api version 32.0.

Here  is my superduper class:

public class QTest implements Queueable
{
      public void execute(QueueableContext context) 
      {
          System.debug('get here QTest.execute');
      }
}
With 'Queueable' instead of 'queueable', the comipler erros out with this:
"Error: Compile Error: Invalid Interface name provided at line 1 column 14"

Codes at workbench:

QTest q = new QTest();
System.enqueueJob(q);

The error from workbench results:
COMPILE ERROR: Method does not exist or incorrect signature: System.enqueue(QTest)
LINE: 3 COLUMN: 1
I have created an rollup field, and added some Filter Criteria under its Roll-Up Summary Options tab. But I can't find the Filter Criteria in the Custom Field's metadata object through the Tooling API. Would you please let me know how to get it?
CustomField: https://developer.salesforce.com/docs/atlas.en-us.api_tooling.meta/api_tooling/tooling_api_objects_customfield.htm
In unit tests, System.scheduleBatch only schdules the job and the batchable won't execute. You should see the scheduled job with this query:
SELECT Count() FROM CronTrigger WHERE CronJobDetail.Name='...'
But that is very much it. System.assert on your expected results from the batchable will always fail. 

A picture Code is worth a thousand words, here are the batchable and unit tests I have:
 
public class MyBatchable implements Database.Batchable<SObject>
{
    String soqlQuery {get;set;}
    String AccountNumber {get;set;}
    
    public MyBatchable(String acctNumber)
    {
        soqlQuery = 'SELECT Id, Name, AccountNumber FROM Account';
        AccountNumber = acctNumber;
    }
    
    public Database.QueryLocator start(Database.BatchableContext BC)
    {          
        return Database.getQueryLocator(soqlQuery);
    }
 
    public  void execute(Database.BatchableContext BC, List<SObject> scope)
    {        
        List<Account> accounts = (List<Account>)scope;
        for(Account a: accounts)
        {
            a.AccountNumber = AccountNumber ;
        }
        update accounts;
    }
 
    public void finish(Database.BatchableContext BC)
    {   
    }
}
 
@isTest
private class MyBatchableTest
{
    static testmethod void DatabaseExcuteBatch_Test()
    {
        Test.startTest();
        SetupTestData(100);
        String acctNumber = '987654321';
        
        Database.executeBatch(new MyBatchable(acctNumber));
        
        Test.stopTest();
        Integer count = [SELECT COUNT() FROM Account WHERE AccountNumber=:acctNumber];
        System.assertEquals(100, count);
    }
    
    static testmethod void ScheduleBatch_Test()
    {
        Test.startTest();
        SetupTestData(100);
        String acctNumber = '987654321';  
              
        System.scheduleBatch(new MyBatchable(acctNumber), 'MyBatchable', 1);
        
        Test.stopTest();
        Integer count = [SELECT COUNT() FROM Account WHERE AccountNumber=:acctNumber];
        System.assertEquals(100, count);
    }   
    
    static void SetupTestData(Integer acctCount)
    {       
        List<Account> accts = new List<Account>();
        for(Integer i=0; i<acctCount; i++)
        {
            accts.add(new Account(Name=getGuid()));
        }
        insert accts;
    }
    
    static String getGuid()
    {
        String v = EncodingUtil.convertToHex(Crypto.generateDigest('SHA1', Blob.valueOf(EncodingUtil.ConvertTohex(Crypto.GenerateAESKey(128))))).toUpperCase(); 
        return (v.subString(0,8) + '-' + v.subString(8,12) + '-' + v.subString(12,16) + '-' + v.subString(16,20) + '-' + v.subString(20,32)).ToUpperCase();
    }
}


DatabaseExcuteBatch_Test calling Database.executeBatch will pass while ScheduleBatch_Test (with System.scheduleBatch) fails.

So unit testing codes with System.scheduleBatch would require two pieces, one to test the job is scheduled and another one to test data results from your batchable. 

 
Hi All,

I need your help wiht a SOQL query. In a visualforce page, I need to show in a Visualforce page all the Approval Process Item that is assigned to a logged in user. I am trying to build a SOQL query for this, but finding it much more challenging than regular SOQL queries. Challenge is that I want to provide a link to the Record that is part of the Approval Process.

Could someone help me with a SOQL query that pulls all Approval items peding for the logged in user. Or even help me with the right direction.

Thanks,
Raghu
I have a REST service but i am not able to cover this class. 
Below is my code, need help ASAP.

Thanks You in advance.
@RestResource(urlMapping='/AttachPDF/*')
global class ServiceInvoiceRedirectController {
	
	@HttpGet
        global static void AttachPDFtoRecordREST() {
        	List<Id> accId = new List<Id>();
        	List<String> emailList = new List<String>();
            RestRequest req = RestContext.request;
            id recordId = req.requestURI.substring(req.requestURI.lastIndexOf('/')+1);

            PageReference pdfPage = new PageReference('/apex/ServiceInvoicePDF?Id='+recordId);
            pdfPage.getParameters().put('id',recordId);
            Blob pdf = pdfPage.getContentAsPdf(); //!Test.isRunningTest() ? pdfPage.getContentAsPdf() : Blob.ValueOf('dummy text');
            
			//List of accoutn Id's of related project
            for(Account_Project_Junction__c accPrjJunRec: [SELECT Id,Project__c,Account__c From Account_Project_Junction__c WHERE Project__c =: recordId]){
            	accId.add(accPrjJunRec.Account__c);
            }
            
            //List of email id's of the selected account's
            for(Contact conRec: [SELECT Id,AccountID,Email,Is_Primary_Contact__c From Contact where AccountID IN: accId AND Is_Primary_Contact__c = true]){
            	if(conRec.Email != null){
            		emailList.add(conRec.Email);
            	}
            }
            
            Project__c prjRec = [Select Id,Name from Project__c where Id =: recordId];
            //Insert Invoice record for related project
	        Invoice__c invoRec = new Invoice__c();
	        invoRec.RecordTypeId = Constants_PicklistVariables.serInvoice; 
	        invoRec.Project__c = recordId;
	        
	        try{
	        insert invoRec;
	        }catch(Exception e){
	            System.debug('Invoice=Exception-->'+e);
	        }
	        System.debug('Invoice=invoRec.id-->'+invoRec);
	        
	        //Insert Attacment to the invoice        
	        Attachment a = New Attachment();
	        a.body = pdf;
	        a.parentID = invoRec.id;
	        a.ContentType  = 'application/pdf';
	        a.Name = 'SER-INV-'+invoRec.id+'.pdf';
	        try{
	        insert a;
	        }catch(Exception e){
	            System.debug('Attachment=Exception-->'+e);
	        }
	        
	        //Create the email attachment
	    	Messaging.EmailFileAttachment efa = new Messaging.EmailFileAttachment();
	    	efa.setFileName('SER-INV-'+invoRec.id+'.pdf');//Pleace ad pdf name from contact name project and oppty concatinate 
		    efa.setContentType('application/pdf');
		    efa.setBody(pdf);
		    
		    // Create the Singal Email Message
		    Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
		    email.setSubject('Service Invoice Notification');
		    String[] CCEmails = emailList;
			email.setToAddresses(CCEmails);
		    //email.setToAddresses(new String[] { 'developer@extentor.com' });//add Contact email id
		    email.setPlainTextBody( 'Dear:Sir/Madam <br/> Please Find Attachment your financial report Attached with this email.');
		    email.setFileAttachments(new Messaging.EmailFileAttachment[] {efa});
		    
		    // Sends the email
		    Messaging.SendEmailResult [] r = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});
            
        }

        // call this method from your Batch Apex
        global static void attachPdfToRecord( Id recordId, String sessionId )
        {
        	System.debug('recordId==>'+recordId);
        	System.debug('sessionId==>'+sessionId);
        	System.debug('Iam in REST API Call method');
            HttpRequest req = new HttpRequest();
            req.setEndpoint(URL.getSalesforceBaseUrl().toExternalForm()+'/services/apexrest/AttachPDF/'+recordId);
            req.setMethod('GET');
            req.setHeader('Authorization', 'OAuth ' + sessionId);

            Http http = new Http();
            HttpResponse response = http.send(req);    
        }
        
}

Test class:
@isTest(seeAllData=false)
global class Test_ServiceInvoiceRedirectController{
   
    static testMethod void testDoGet() {
		Account acc= InitialTestData.createAccount('Raj');
        insert acc;
        
        Contact contact1=InitialTestData.createContact(acc.id,'Sen','raj@gmail.com');
        insert contact1;
        
        Opportunity_Deal__c oppdeal=InitialTestData.createOpportunityDeal('Opp1',acc.id,contact1.id,false,'Quote');
        insert oppdeal;
        
        Project__c project1=InitialTestData.createPlotProject('Pro',acc.id,'Submitted',oppdeal.id);
        insert project1;
        
    RestRequest req = new RestRequest(); 
    RestResponse res = new RestResponse();

    // pass the req and resp objects to the method     
    req.requestURI = URL.getSalesforceBaseUrl().toExternalForm()+'/services/apexrest/AttachPDF/'+project1.Id;  
    req.httpMethod = 'GET';

    ServiceInvoiceRedirectController.attachPdfToRecord results = ServiceInvoiceRedirectController.AttachPDFtoRecordREST(req,res);

    System.assertEquals('true', results.success);
    System.assertEquals(10, results.records.size());
    System.assertEquals('Query executed successfully.', results.message);

  }
	
}
Hi Team,

I have a code written to change the Status of the record from Notice Period to Inactive for custom object 'Enrollments'. The code is https://eu3.salesforce.com/setup/build/viewApexClass.apexp?id=01p20000000HVDd

However since November this is not working as there are lot of Notice period records that are ot changing the status to inactive in the link: https://eu3.salesforce.com/setup/build/viewApexClass.apexp?id=01p20000000HVDd

I tried to debug the code but could not find any reason why its not firing. I would like to know which part of that trigger is causing the issue. Test record t replicate is https://eu3.salesforce.com/0032000000xVJEQ

Please help to find which part of the code is causing the issue in not obtaining the record status.

Provided login access for salesforce.com. Any help would be highly appreciated!!
Here inthis page using the {!SaveDueFrom} i can insert the input text values into object..but i also want to insert the inputfiled values also with the same action what to do? How to pass that to that SaveDueFrom method in controller.

My vf page:
<apex:page standardController="File_New_Protest__c" Extensions="Filenewexten">
<apex:form>
<apex:pageBlock >
<apex:pageBlockSection title="Protester " columns="3">
<apex:inputText value="{!CompanyName}" />
<apex:inputText value="{!StreetName}" id="cstreet"/>
<apex:inputField value="{!File_New_Protest__c.Agency_Tier1__c}"/>
<apex:inputField value="{!File_New_Protest__c.Comments__c}"/> 
<apex:commandButton value="Save" action="{!SaveDueFrom}"/>
</apex:pageBlockSection>
</apex:pageBlock >
<apex:form>
<<apex:page>

My controller:

public with sharing class Filenewexten {
public Filenewexten(ApexPages.StandardController controller) {
}
 public string  CompanyName{get;set;}
      public string  StreetName{get;set;}

public Void SaveDueFrom(){
File_New_Protest__c Insertfile=New File_New_Protest__c();
 Insertfile.Company_Name__c=CompanyName;
Insertfile.Street_Name__c=StreetName;
insert(Insertfile);
}


please help me inthis ...thanks in advance
I have a batch class that makes a external Http callout to create case records with a CreatePublicStuffCases() which is called in the start(). In the execute function, I have another callout to get users details for specific cases that were previously inserted in the CreatePublicStuffCases(). Then at the end, do a DML to insert new account and also, update the cases that were previously inserted with thier respective case owners. I keep getting the error "System.CalloutException: You have uncommitted work pending. Please commit or rollback before calling out". Even when I tried doing the insert outside the loop with a List DML insert. Any help is much appreciated.

The start function : 
public Database.QueryLocator start(Database.BatchableContext context)
{
    CreatePublicStuffCases();
    String ps = 'Public Stuff';
    return Database.getQueryLocator('SELECT External_Source_Id__c FROM Case WHERE Requires_User_Details__c = true AND External_Source_Id__c != Null AND Origin =: ps');
}
The execute function :
public void execute(Database.BatchableContext context, List<Case> scope)
{

    //List<Account> publicStuffAccounts = new List<Account>();
    for (Case cse : scope)
    {            
        String newReq = cse.External_Source_Id__c;
        HttpRequest req = new HttpRequest();
        req.setMethod('GET');
        req.setEndpoint('https://www.publicstuff.com/api/2.0/request_view?request_id='+newReq');
        Http http = new Http();
        HTTPResponse res = http.send(req);

        String resonseBody = res.getBody();
        String jsonString = resonseBody;
        Map<String,Object> rawObj = (Map<String,Object>) JSON.deserializeUntyped(jsonString);

        Map<String,Object> responseObj = (Map<String,Object>)rawObj.get('response');
        Map<String,Object> userDetails = (Map<String,Object>) responseObj.get('user_detail');

        //select a specific value
        String requeststatus = (String) responseObj.get('request_status');
        String firstname = (String) userDetails.get('firstname');
        String lastname = (String) userDetails.get('lastname');
        String email = (String) userDetails.get('email');
        String phone = (String) userDetails.get('phone');
        String address = (String) userDetails.get('address');
        String zipcode = (String) userDetails.get('zipcode');
        String space = (String) userDetails.get('space');
        String state = (String) userDetails.get('state');

        //check
        Account newPublicStuffContact = new Account(LastName = lastname, FirstName = firstname, PersonEmail = email, Phone = phone, PersonMailingStreet = address, PersonMailingPostalCode = zipcode,
            PersonMailingState = space, PersonMailingCountry = state);
        if (lastname == Null){
            return;
        }
        else{
            try{
                insert newPublicStuffContact;
                //publicStuffAccounts.add(newPublicStuffContact);
                Case caseUpdate = [SELECT Id, ContactId, Requires_User_Details__c FROM Case WHERE Id = :cse.Id];
                //update and mark the case's Requires_User_Details__c as false
                caseUpdate.Requires_User_Details__c = false;
                caseUpdate.AccountId = newPublicStuffContact.Id;
                System.debug('The newPublicStuffContact Id : ' + newPublicStuffContact.Id);
                Update caseUpdate;
                }
                catch (Exception e){
                    System.debug('Error inserting case' + e.getMessage())
                }
        }
        //mapPSContact.put(newPublicStuffContact.Id, newPublicStuffContact);
    }
    //insert publicStuffAccounts;
}
The CreatePublicStuffCases function : 
public static void CreatePublicStuffCases()
{
    // Callout code verbatim from the question
    Date d = Date.today();
    JSONGenerator gen = JSON.createGenerator(true);

    HttpRequest req = new HttpRequest();
    req.setMethod('GET');
    req.setEndpoint('https://www.publicstuff.com/api/2.0/requests_list?limit=2&client_id=****&status=open');
    Http http = new Http();
    HTTPResponse res = http.send(req);
    String resonseBody = res.getBody();
    String jsonString = resonseBody;
    Map<String,Object> rawObj = (Map<String,Object>) JSON.deserializeUntyped(jsonString);
    Map<String,Object> responseObj = (Map<String,Object>)rawObj.get('response');
    List<Case> newCases = new List<Case>();
    Map<String, Object> iMap = new Map<String, Object> ();
    Map<String,Object> id = new Map<String, Object>();
    List<Object> reqs = (List<Object>)responseObj.get('requests');
    for (Object x : reqs)
    {
        iMap = (Map<String, Object>)x;
        for (String field : iMap.keySet())
        {
            id = (Map<String,Object>) iMap.get(field);                
            String idx = 'id';
            String title = 'title';
            String description = 'description';
            String status = 'status';
            String address = 'address';
            String location = 'location';
            String zipcode = 'address';

            Integer OId = (Integer) id.get(idx);
            String Otitle = (String) id.get(title);
            String Odescription = (String) id.get(description);
            String OStatus = (String) id.get(status);
            String Oaddress = (String) id.get(address);
            String OLocation = (String) id.get(location);
            String OZipCode = (String) id.get(zipcode);
            Boolean OrequiresUserDetails = true;

                String CaseRecordTypeId = GlobalStaticMetaDataCache.getRTId('Case', GlobalFixedParams.RECORDTYPE_CASE_SERVICE_REQUEST);
                Case c = new Case(recordTypeId = CaseRecordTypeId, External_Source_Id__c = String.valueOf(OId), Customer_Request_Details__c = Otitle + ' ' + 
                    Odescription, Status = OStatus, SuppliedTargetAddress__c = Oaddress + ' ' + OLocation + ' ' + OZipCode, Requires_User_Details__c = OrequiresUserDetails, Origin = 'Public Stuff');
                newCases.add(c);
        }
    }
    try{
            insert newCases;
    }catch (Exception e){
    }
}
The excute function will send an email but that is no problem at the moment.
 
Hi,
i have a requirement in which i need to get  javascript variables in apex class.If anyone can help with a code example, I'd appreciate it.
Hi,

I want to disable a vf page save button which is in <apex:pageBlockButtons> block. I have read many articles related to this and tried them but none had helped me.

I have tried the action function from some other post but its posting my data twice to server.
Please see below my code.

<apex:actionStatus id="mySaveStatus1"> <apex:facet name="stop"> <apex:commandButton action="{!saveOverride}" status="mySaveStatus1" value="Save" disabled="false" rerender="pgMsg"/> </apex:facet> <apex:facet name="start"> <apex:commandButton status="mySaveStatus1" value="Saving..." disabled="true"/> </apex:facet>

Please suggest me a way to get this done.
Thanks in advance.
Hi All,

I have a VF template with Apex Class on our Production. I update the Apex Class on our sandbox to add a filter criteria to limit the result. unfortunately when I try to deploy it, I receive an error that says "DerekUpdateSource.updateUpdateSource(), Details: System.LimitException: AVTRRT:Too many SOQL queries: 101 (AVTRRT)".

The tricky part is DerekUpdateSource test class is not what I am deploying its a different one and that "DerekUpdateSource" is already deployed on our Production.

What I did was, I run a test on DerekUpdateSource on our Production and it gave the error "Too many SOQL queries: 101 " but on our Sandbox when I run the test it passed.

The only changes that happened on our Org recently was Target Recruit (third party app) deployed a patch update on our production to resolve a bug. After that I can no longer deploy any class that uses queries record. 

Target Recruit on our Sandbox is not yet update to the lastest patch of Target Recruit.

Is the DerekUpdateSource test class that has a problem or the recent patch of target recruit?

If its DerekUpdateSource test class, I really do not have any other ideas how to shorten this.

DerekUpdateSource Test Class:

@IsTest
public class DerekUpdateSource {

    static testmethod void updateUpdateSource(){

        AVTRRT__Config_Settings__c mycs = AVTRRT__Config_Settings__c.getValues('Default');
    if(mycs == null) 
    {
        mycs = new AVTRRT__Config_Settings__c(Name= 'Default');
        mycs.Trigger_Disable_UpdateAccountName__c = true;
        insert mycs;
    }
        Contact c = new contact();
            c.LastName = 'Test';
            c.RecordtypeID = '012A0000000v0La';
            c.AVTRRT__Source__c = null;
        insert c;
        
        AVTRRT__ETCObject__c a = new AVTRRT__ETCObject__c();
            a.AVTRRT__Name__c = 'jobsDB';
            a.AVTRRT__Candidate__c = c.id;
        insert a;        
        AVTRRT__ETCObject__c b = [Select id from AVTRRT__ETCObject__c where AVTRRT__Name__c = 'jobsDB' and AVTRRT__Candidate__c = :c.Id limit 1];
        update b;
        
        Contact c1 = new contact();
            c1.LastName = 'Test1';
            c1.RecordtypeID = '012A0000000v0La';
            c1.AVTRRT__Source__c = null;
        insert c1;
        
        AVTRRT__ETCObject__c e = new AVTRRT__ETCObject__c();
            e.AVTRRT__Name__c = 'Clyde Marine Recruitment';
            e.AVTRRT__Candidate__c = c1.id;
        insert e;
        AVTRRT__ETCObject__c f = [Select id from AVTRRT__ETCObject__c where AVTRRT__Name__c = 'Clyde Marine Recruitment' and AVTRRT__Candidate__c = :c1.Id limit 1];
        update f;
        
        Contact c2 = new contact();
            c2.LastName = 'Test2';
            c2.RecordtypeID = '012A0000000v0La';
            c2.AVTRRT__Source__c = null;
        insert c2;
        
        AVTRRT__ETCObject__c h = new AVTRRT__ETCObject__c();
            h.AVTRRT__Name__c = 'Corporate Event';
            h.AVTRRT__Candidate__c = c2.id;
        insert h;
        AVTRRT__ETCObject__c f1 = [Select id from AVTRRT__ETCObject__c where AVTRRT__Name__c = 'Corporate Event' and AVTRRT__Candidate__c = :c2.Id limit 1];
        update f1;
        
        Contact c3 = new contact();
            c3.LastName = 'Test3';
            c3.RecordtypeID = '012A0000000v0La';
            c3.AVTRRT__Source__c = null;
        insert c3;
        
        AVTRRT__ETCObject__c k = new AVTRRT__ETCObject__c();
            k.AVTRRT__Name__c = 'e Financial Careers';
            k.AVTRRT__Candidate__c = c3.id;
        insert k;
        AVTRRT__ETCObject__c f3 = [Select id from AVTRRT__ETCObject__c where AVTRRT__Name__c = 'e Financial Careers' and AVTRRT__Candidate__c = :c3.Id limit 1];
        update f3; 
        
        Contact c4 = new contact();
            c4.LastName = 'Test4';
            c4.RecordtypeID = '012A0000000v0La';
            c4.AVTRRT__Source__c = null;
        insert c4;
        
        AVTRRT__ETCObject__c n = new AVTRRT__ETCObject__c();
            n.AVTRRT__Name__c = 'Email/Mailer Application';
            n.AVTRRT__Candidate__c = c4.id;
        insert n;
        AVTRRT__ETCObject__c f4 = [Select id from AVTRRT__ETCObject__c where AVTRRT__Name__c = 'Email/Mailer Application' and AVTRRT__Candidate__c = :c4.Id limit 1];
        update f4;
        
        Contact c5 = new contact();
            c5.LastName = 'Test5';
            c5.RecordtypeID = '012A0000000v0La';
            c5.AVTRRT__Source__c = null;
        insert c5;
        
        AVTRRT__ETCObject__c q = new AVTRRT__ETCObject__c();
            q.AVTRRT__Name__c = 'Indeed';
            q.AVTRRT__Candidate__c = c5.id;
        insert q;
        AVTRRT__ETCObject__c f5 = [Select id from AVTRRT__ETCObject__c where AVTRRT__Name__c = 'Indeed' and AVTRRT__Candidate__c = :c5.Id limit 1];
        update f5;      
        
        Contact c6 = new contact();
            c6.LastName = 'Test6';
            c6.RecordtypeID = '012A0000000v0La';
            c6.AVTRRT__Source__c = null;
        insert c6;
        
        AVTRRT__ETCObject__c t = new AVTRRT__ETCObject__c();
            t.AVTRRT__Name__c = 'Jobstreet';
            t.AVTRRT__Candidate__c = c6.id;
        insert t;
        AVTRRT__ETCObject__c f6 = [Select id from AVTRRT__ETCObject__c where AVTRRT__Name__c = 'Jobstreet' and AVTRRT__Candidate__c = :c6.Id limit 1];
        update f6;
        
        Contact c7 = new contact();
            c7.LastName = 'Test7';
            c7.RecordtypeID = '012A0000000v0La';
            c7.AVTRRT__Source__c = null;
        insert c7;
        
        AVTRRT__ETCObject__c w = new AVTRRT__ETCObject__c();
            w.AVTRRT__Name__c = 'LinkedIn - Resourcer';
            w.AVTRRT__Candidate__c = c7.id;
        insert w;
        AVTRRT__ETCObject__c f7 = [Select id from AVTRRT__ETCObject__c where AVTRRT__Name__c = 'LinkedIn - Resourcer' and AVTRRT__Candidate__c = :c7.Id limit 1];
        update f7;
        
        Contact c8 = new contact();
            c8.LastName = 'Test8';
            c8.RecordtypeID = '012A0000000v0La';
            c8.AVTRRT__Source__c = null;
        insert c8;
        
        AVTRRT__ETCObject__c a1 = new AVTRRT__ETCObject__c();
            a1.AVTRRT__Name__c = 'Linkedin Advert';
            a1.AVTRRT__Candidate__c = c8.id;
        insert a1;
        AVTRRT__ETCObject__c f8 = [Select id from AVTRRT__ETCObject__c where AVTRRT__Name__c = 'Linkedin Advert' and AVTRRT__Candidate__c = :c8.Id limit 1];
        update f8;  
        
        Contact c9 = new contact();
            c9.LastName = 'Test8';
            c9.RecordtypeID = '012A0000000v0La';
            c9.AVTRRT__Source__c = null;
        insert c9;
        
        AVTRRT__ETCObject__c a9 = new AVTRRT__ETCObject__c();
            a9.AVTRRT__Name__c = 'Reed';
            a9.AVTRRT__Candidate__c = c9.id;
        insert a9;
        AVTRRT__ETCObject__c f9 = [Select id from AVTRRT__ETCObject__c where AVTRRT__Name__c = 'Reed' and AVTRRT__Candidate__c = :c9.Id limit 1];
        update f9;
        
        Contact c10 = new contact();
            c10.LastName = 'Test10';
            c10.RecordtypeID = '012A0000000v0La';
            c10.AVTRRT__Source__c = null;
        insert c10;
        
        AVTRRT__ETCObject__c a10 = new AVTRRT__ETCObject__c();
            a10.AVTRRT__Name__c = 'Red Website';
            a10.AVTRRT__Candidate__c = c10.id;
        insert a10;
        AVTRRT__ETCObject__c f10 = [Select id from AVTRRT__ETCObject__c where AVTRRT__Name__c = 'Red Website' and AVTRRT__Candidate__c = :c10.Id limit 1];
        update f10;
        
        Contact c11 = new contact();
            c11.LastName = 'Test11';
            c11.RecordtypeID = '012A0000000v0La';
            c11.AVTRRT__Source__c = null;
        insert c11;
        
        AVTRRT__ETCObject__c a11 = new AVTRRT__ETCObject__c();
            a11.AVTRRT__Name__c = 'Trade Winds';
            a11.AVTRRT__Candidate__c = c11.id;
        insert a11;
        AVTRRT__ETCObject__c f11 = [Select id from AVTRRT__ETCObject__c where AVTRRT__Name__c = 'Trade Winds' and AVTRRT__Candidate__c = :c11.Id limit 1];
        update f11;
}
}
Did anone face this issue in APEX Class?
 I a

Code
List<Opportunity> oppoList = [SELECT Id, Broker_Agent__c, Seller__c, Primary_Contact__c FROM Opportunity WHERE Id = : opportunityRoles.keySet()];

I am not getting this error in Prod but when I copied the code from Prod to Full sandbox, its failing deployment with Illegal assignment from LIST<Opportunity> to LIST<Opportunity> error. Not sure whats wrong. Any suggestion/info is appreciated.

Thanks 


 
Hi, I am trying to write a test method fo rthe following. I am a total newbie when it comes to code, so need lots of help, please.

public with sharing class accsearchcontroller { 
   public list <account> acc {get;set;} 
   public string searchstring {get;set;} 
   public accsearchcontroller(ApexPages.StandardController controller) { 
   } 
   public void search(){ 
     string searchquery='select OwnerName__c,name,owner.phone,Account_Manager__c,BDM__c,BillingState,BillingCity, id from account where (name like \'%'+searchstring+'%\' OR OwnerName__c like \'%'+searchstring+'%\') Limit 1000'; 
     acc= Database.query(searchquery); 
   } 
   public void clear(){ 
   acc.clear(); 
   } 
 }


Here is what i wrote, but gets an error, Error: Compile Error: Constructor not defined: [accsearchcontroller].<Constructor>() :

@isTest
public class accsearchcontrollerTest{
static testMethod void test() {
    accsearchcontroller acc = new accsearchcontroller();
    Test.startTest();
    account[] accounts = acc.getAccounts();
    Test.stopTest();
    System.assertNotEquals(null, accounts);
}
}


Please advise, thanks!!!!!
  • November 13, 2014
  • Like
  • 0
Hi All I am looking to get the contact that is associated with the user who logged in and redirect to the detail page. But it is not throwing any error but I am not able to redirect properly can some one help where the code is wrong?

public class MyContact {

    public PageReference redirect() {
    
   User u=[Select contactid from User where id=:UserInfo.getUserId()];
        system.debug(u);
    
system.debug(u.contactid);
PageReference pageRef = new PageReference('/' + 'u.contactid');
pageref.setredirect(True);
        return pageref;
    }


public MyContact(){}




}
Hi
i am trying to get controller variable in my javascript but getting the value as spaces.

VF page
<apex:commandButton value="AddEmail" action="{!addEmail}" oncomplete="fillIn();" />   ===> calling controller method and building a string.

function fillIn() {
     alert('inside fill in');
     var customeremail = '{!finalemail}';
     alert('customeremail----'+customeremail);  ==>  controller variable  is not populating  in alert
}

Controller :
public String finalemail{get; set;}
public void addEmail(){
        for(SARWrapper sw : SARlist){
            if(sw.ischeck == true){
               finalemail=sw.custemail + ';';
            }
        }
            if (finalemail==null || finalemail =='') {
                apexPages.message msg = new ApexPages.Message(ApexPages.Severity.Fatal,' No Email is selected');
                ApexPages.addmessage(msg);    
                  
            }
            else{
                system.debug('final email is ' + finalemail); ===> string contains valid data, trying to access in javascript.
              
            }
                
}


Please advice

Thanks in Advance
 
Hi All ,
Say the are two picklists A and B and two visual force pages 1 and 2 . Page 1 consists of Next button and page two consists of Back button 
I was trying to enable a picklist B on page1  when i click on back command button on  page2 using javascript. But the picklistB in which i am trying to enable is enabled or  disabled based on the other picklistA values in the page 1 itself. So when i was trying to move forward from page 1 to 2 i am able to succeed , but when i am trying to move backward the picklist B value is getting locked (disabled) which should not happen .
Could any one  possibly help me with how to handle with your valuable suggestions .  

Thanks 
Preetham SFDC 

 
i created vf page for dispalying account list one side and contact list other side seperate by using the wraper class (i dont know weather i can use two wraper classes in one class or not ) here is vf page

vf page :
<apex:page controller="accountcontactwraper" sidebar="false" >
<apex:form >
<apex:commandButton value="save"/>
<apex:pageBlock >
<apex:pageBlockSection collapsible="false" columns="2">

<apex:pageBlockTable value="{!Accounttable}" var="a">
<apex:column >
<apex:inputCheckbox value="{!a.selected}"/>
</apex:column>
<apex:column value="{!a.acc.name}"/>
<apex:column value="{!a.acc.phone}"/>
</apex:pageBlockTable>

<apex:pageBlockTable value="{!contacttable}" var="C">
<apex:column>
 <apex:inputCheckbox value="{!c.select}"/>
</apex:column>
<apex:column value="{!a.con.name}"/>
<apex:column value="{!a.con.phone}"/>
</apex:pageBlockTable>
</apex:pageBlockSection>
</apex:pageBlock>

</apex:form>
</apex:page>

and my class:

public class accountcontactwraper {

  public List<accountcontactwrapercreate> Accounttable{get;set;}
  public string contacttable{get;set;}
  
 
 public accountcontactwraper (){
 
 if(Accounttable==null){
 Accounttable=New LIst<accountcontactwrapercreate>();
 for(Account accs:[select id,name,phone from account limit 10]){
 Accounttable.add(New accountcontactwrapercreate(accs) );
 }
 }
 if(contacttable==null){
 contacttable=New List<wrapercon>();
 for(contact cc:[select id,name,lastname from contact limit 10]){
 contacttable.add(New wrapercon(cc));
 }
 }
 }
 
 
 public class accountcontactwrapercreate{
 public Account acc{get;set;}
 public boolean selected{get;set;}
    public accountcontactwrapercreate(Account a){
    acc=a;
    selected=false;
    }
 }
 
 public class wrapercon{
 public contact con{get;set;}
 public boolean select{get;set;}
    public wrapercon(contact c){
    con=c;
    select=false;
    }
 }
 
 
}


now while saving this class am getting this error :
 accountcontactwraper Compile Error: unexpected token: 'select' at line 35 column 16

Help me thanks  in advance
 
Hi all,
In first VF page I am getting basic Lead information and I want to pass that information to another VF page which will have detailed information about the Lead. Now after click on Save button I need to pass that record information and then add more info and save that Lead.

Here is my first VF page:
<apex:page controller="myLeadController">
    <apex:sectionHeader title="New Lead Page" />
    <apex:form >
        <apex:pageBlock title="Create a New Lead">
            <apex:pageBlockButtons >
                <apex:commandButton action="{!save}" value="Save"/>
            </apex:pageBlockButtons>        
            <apex:pageBlockSection title="Lead Information">
                <apex:inputField id="firstName" value="{!Lead.FirstName}"/>
                <apex:inputField id="lastName" value="{!Lead.LastName}"/>
                <apex:inputField id="companyName" value="{!Lead.Company}"/>
            </apex:pageBlockSection>
        </apex:pageBlock>
    </apex:form>
</apex:page>

public class myLeadController {
    
    Lead lead;

    public Lead getLead() {
        if(lead == null) lead = new Lead();
        return lead;
    }
    
    public PageReference save() {
        // Add the lead to the database. 
        insert lead;
        // Send the user to the detail page for the new lead.
       // need to pass the record id to Thankyou Page
        PageReference leadPage = new ApexPages.Thankyou
        leadPage.setRedirect(true);
        return leadPage;
    }

}