• Rohit K Sethi
  • SMARTIE
  • 608 Points
  • Member since 2016
  • Dev
  • IBirds

  • Chatter
    Feed
  • 15
    Best Answers
  • 2
    Likes Received
  • 3
    Likes Given
  • 7
    Questions
  • 91
    Replies
Here's my Visualforce page:
<apex:page docType="html-5.0" sidebar="false" showHeader="false" standardStylesheets="false" controller="TestController">

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

    <script type="text/javascript">
        jQuery.noConflict();

        jQuery(document).ready(function() {
            jQuery('[id$=polamonolaa]').bind( "click", function() {
              alert( "Test" );
            });
        })
    </script>

    <apex:form>
        <apex:commandLink action="{!showTest}" value="Show" reRender="panelTest"/>
        <br/>
        <apex:outputPanel id="panelTest">
            <apex:outputPanel id="panelTest2" rendered="{!showTestPanel2}">
                <apex:commandLink id="polamonolaa" reRender="panelTest" value="TOP"/>
            </apex:outputPanel>
        </apex:outputPanel>
    </apex:form>
</apex:page>
Here's my controller:
public class TestController {
    public Boolean showTestPanel2{get;set;}

    public TestController(){
        showTestPanel2 = false;
    }

    public void showTest(){
        showTestPanel2 = true;
    }
}

What I'm trying to do here is to show an alert on a button click. Unfortunately my script doesn't work when button is placed inside outputPanel id="panelTest2" which rendered attribute depends on showTestPanel2 variable. Any suggestions how to fix this issue? Moving my button outside inner panel is not an option.
How can I know the number of fields in an object and how can I append entire fields at once? Please guide.
I am new to Apex and trying to access the value from Custom Controller having SOQL query and show it on visualforce page as an Output link.
Visualforce snippet:
<div class="count"><apex:outputText value="{!Records}"/></div>
Apex Code Snippet:
public Integer getDisplayQueryList() { Records = 0; Records = [select count() from Case where Type like 'MDD Increase from WSC']; return Records; }
Also I have read about the AggregateResult[] which might be the best way to use but not sure how to use it properly. My main aim is to search & Count for all Cases which are NOT Closed & of Type = MDD Increase from WSC and then display that count in the visual force page.
Any Help would be much appreciated.
<apex:pageBlock>
                <apex:pageBlockTable value="{!Questions}" var="ques" id="questable">
                    <apex:column headerValue="Question">
                        <apex:inputText value="{!Questions[ques]}" id="quesid" style="width: 500px;"/>
                    </apex:column>
                    <apex:column headerValue="Language">
                        <apex:OutputText value="{!ques}" id="langid"/>
                    </apex:column>
                </apex:pageBlockTable>
</apex:pageBlock>
My apex code: 
public Map<String,String> Questions {
        get {
            return new Map<String, String> {
                'French' => '', 
                'German' => '', 
                'Italian' => '',
                'Japanese' => '', 
                'Korean' => '', 
                'Portuguese' => '',
                'Russian' => '', 
                'Chinese Simplified' => '', 
                'Spanish' => '',
                'Chinese Traditional' => ''
            };
        }
        set;
}

Problems is, I cannot access the input text from vfp to maps in apex code.
 
Hello all - can someone help me with a very basic trigger and test class?

My Trigger:

trigger LeaveBeforeDelete on VBA_CC_Tracking_Leave_Manager__c (before delete)
{
  for  (VBA_CC_Tracking_Leave_Manager__c q: trigger.old)
  
       if (q.Status_of_Request__c != 'Pending')
               
           {
           
           q.adderror('This record cannot be deleted due to the status being other than "Pending". Thank you');
           
           } 
}

My Test Class:

@IsTest
public class LeaveBeforeDeleteTest {

    static void testLeaveBeforeDelete() {
       
        User u = new User();
        u.FirstName = 'Mr';
        u.LastName = 'Tester';
        u.Email = 'mr.tester@va.gov';
        u.Alias = 'mtest';
        u.Username = 'mr.tester@va.gov';
        u.ProfileID = '00et0000000QGuG';
        
        u.TimezoneSidKey = 'America/Denver';
        u.LocaleSidKey = 'en_US';
        u.EmailEncodingKey = 'UTF-8';
        u.LanguageLocaleKey = 'en_US';
        
        insert u;
        
        system.runAs(u){
    
        VBA_CCTracking_Agent_Production_Data__c a = new VBA_CCTracking_Agent_Production_Data__c();
        a.Name = 'MrTester-2016-05-13';
        a.VBA_CC_Date_of_Data__c = date.newInstance(2016, 5, 13);
        
        insert a;                                        
                       
        VBA_CC_Tracking_Leave_Manager__c b = new VBA_CC_Tracking_Leave_Manager__c();        
        b.Agent_Name_Date__c = a.Id;
        b.Status_of_Request__c = 'Approved';
        
               
        insert b;
           
        try
           {
               Delete a;
               System.assert(true);
            }
           catch(Exception e) 
           {
               system.assertEquals('This record cannot be deleted due to the status being other than "Pending". Thank you', e.getMessage());
            }      
        
        }
                        
        
    }

}
public class  myy{
public integer pagenum{get;set;}
public integer fr{get;set;}
public integer to{get;set;}  

//GETTER SETTER___________________________________________________
Set<Id> i = new Set<Id>();
public integer count{get;set;}
public integer offset { get; set; }
public List<wrap> list1{get;set;}
public boolean Box{get;set;}
public boolean blo{get;set;}
public String search{get;set;}
public String search1{get;set;}
public String a1{get;set;}
public String search3{get;set;}
public integer totalRecs{get;set;}
public integer OffsetSize{get;set;}
public integer LimitSize{get;set;}
public boolean msg{get;set;}
public boolean nude{get;set;}
 public boolean check{get;set;}
 public String Ab{get;set;}
 List<SelectOption> options = new List<SelectOption>();
//CONSTRUCTOR_____________________________________________________   
  public myy(){
  fr= 0;
  pagenum = 0;
  OffsetSize= 0;
  LimitSize= 3;
  totalRecs=0;
  blo=false;
  msg=false;
  nude=true;
Box=false;
}
//ACCOUNT SELECT _______________________________________________________________
    public void abc2() {
    
count= 0;
     if(ab !='none' && ab!=null){
    
      Box=true;
      system.debug(ab);
    totalRecs = [select count() from contact where accountid =:Ab and name LIKE :'%'+ search3 +'%'];
    }
    
    else{
    system.debug(ab);
    Box=false;
    }     
    }
//SEND EMAIL_____________________________________________________________________    
     public PageReference sendmail() {
        
        for(wrap w: list1)
            {
           
            if(w.selected==true)
                {
                blo=false;
                count++;
                
                system.debug(list1.size());
                 Messaging.SingleEmailMessage message = new Messaging.SingleEmailMessage();
                 message.toAddresses = new String[]{w.con.email,w.con.email};
                     message.subject = 'sent by Contact';
                    message.plainTextBody = 'how r u:P.';
                    Messaging.SingleEmailMessage[] messages =new List<Messaging.SingleEmailMessage> {message};
                     Messaging.SendEmailResult[] results = Messaging.sendEmail(messages);   
                     ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Confirm,'Email Sent Successfully'));                                
                     }
                     else{
                     w.selected=false;
                    blo=true;
                    count= 0;
                     }
                     
            }
        return null;
    }
//WRAPPER AND CONTACTS  

     public List<SelectOption> getAccounts() {
        totalRecs = [select count() from contact where accountid =:Ab];
           options.clear();
           options.add(new selectOption('none','----None-----'));
             for(schema.account Acct: [SELECT id,name from account]){
             options.add(new selectOption(Acct.id,Acct.name));
             }
              return options;
         }
         
         public List<wrap> getnew() {
        
         if(OffsetSize!=0){
pagenum = ((OffsetSize/LimitSize)+1);

else{
pagenum = 1;
}
 fr = ((pagenum * LimitSize) - LimitSize + 1);
 
 to = (pagenum * LimitSize);
 if(to >totalRecs){
 to = totalRecs;
 }

              blo = false;
               list1=new List<wrap>();
                if(Ab!=null){
               for(contact c:[select name,email,Phone,AssistantPhone from contact where AccountId=:Ab and name LIKE :'%'+ search3 +'%']){
               if(i.contains(c.id)){
               list1.add(new wrap(c,true));}
               else{
               list1.add(new wrap(c));}
               }}
        return list1;
    }
      
         public class wrap{
        public boolean selected{get;set;}
        public Contact con{get;set;}
        public wrap(contact c1){
        con=c1;
        selected=false;
        }
        public wrap(contact c1,boolean boxs){
        con=c1;
        selected=boxs;
        }
    
    }
 //PAGINATION______________________________________________   
 public void FirstPage()
{
OffsetSize = 0;
}

public void previous()
{
for(wrap w:list1){
    if (w.selected==true){
        i.add(w.con.id);
    }else if(i.contains(w.con.id)){
        i.remove(w.con.id);
    }
}if(OffsetSize>0)
OffsetSize = OffsetSize - LimitSize;
}public void next(){

for(wrap w:list1){
    if (w.selected==true){
        i.add(w.con.id);
    }else if(i.contains(w.con.id)){
        i.remove(w.con.id);
    }
}
OffsetSize = OffsetSize + LimitSize;

}public void LastPage()
{
OffsetSize = totalrecs - math.mod(totalRecs,LimitSize);
}

public boolean getprev(){

if(OffsetSize != 0)
return false;
else
return true;
}

public boolean getnxt()
{

if((OffsetSize + LimitSize) > totalRecs)
return true;
else
return false;
}
}
error: at below line Invalid conversion from runtime type Opportunity to Qill__c

Test Class line:
ApexPages.StandardController sc = new ApexPages.standardController(testOppty);

   Controller  controller = new Controller(sc);

Class line:
 this.q = (Qill__c)stdController.getRecord();
 

Hi,
I'm creating 2 columns on one of our visualforce pages and I am able to seperate the fields into 2 columns but whenever I get this happening the field labels are removed.  The visualforce page only shows the actual input text fields but not the labels.
Below is my code on the VF page:


<apex:pageBlockSection columns="2">
            <apex:pageblock title="Account Information">
                <apex:inputField label="Lead Status" value="{!newLead.Status}" required="true" /> <br> </br>
                <apex:inputField label="Fuel Type" value="{!newLead.Fuel_Type__c}" /> <br> </br>
                <apex:inputField label="Region" value="{!newLead.Region__c}" /> <br> </br>
                <apex:outputField value="{!newLead.RecordTypeId}" /> <br> </br>
                </apex:pageblock>
                <apex:pageblock title="Account Information 2">
                <apex:inputField value="{!newLead.Consumption__c}" /> <br> </br>
                <apex:inputField value="{!newLead.Dual_Fuel__c}" /> <br> </br>
                <apex:inputField value="{!newLead.Associated_Dual_Fuel_Site__c}" /> <br> </br>
                <apex:inputField value="{!newLead.Qualification_Check__c}" /> <br> </br>
                </apex:pageBlock>
            </apex:pageBlockSection>


Am I doing something wrong here?  Does anyone know how I can get the labels to appear?
Any help is much appreciated

Hi-
I am trying to grab the area code out of the phone number field on the lead object, and then use this as a lookup to a custom object from which I can pull territory assignments.
I am getting this err-> UpdateLeadACA: execution of BeforeUpdate caused by: System.StringException: Ending position out of bounds: 3

 - which i believe means that a three digit return (aka the area code) is NOT three digits.
I tried to add a length formula into the code - but that did not seem to remove the error.

I'm not sure what I am missing, any advice would be very welcome.
Thanks, S.


Here is my class:
public with sharing class UpdateLeadACAHandler {

// Set aca on Lead create

     public void setAreaCodeInsert(List<Lead> leads) {
        Area_Code_Assignment__c defaultAreaCode = null;
        Map<String, Area_Code_Assignment__c> areaCodeMap = new Map<String, Area_Code_Assignment__c>();
     
            for(Area_Code_Assignment__c areaCodeA : [SELECT Id, Name FROM Area_Code_Assignment__c LIMIT 500]) {
                areaCodeMap.put(areaCodeA.Name, areaCodeA);
            }
        
        if(System.Label.Default_Area_Code != null && areaCodeMap.containsKey(System.Label.Default_Area_Code)) {
            defaultAreaCode = areaCodeMap.get(System.Label.Default_Area_Code);
        }
        for(Lead lead : leads) {
                     
            if(lead.Phone != null && lead.Assignment_Area_Code1__c == null) {
                String phone = lead.Phone.replace('(', '').replace(')', '');
                String areaCodeA = phone.substring(0,3);              
                
                if((areaCodeA.Length()==3) && (areaCodeMap.containsKey(areaCodeA))) {
                    lead.Assignment_Area_Code1__c = areaCodeMap.get(areaCodeA).Id;
                }
            
            if((areaCodeA.Length()!=3) || (defaultAreaCode != null && lead.Assignment_Area_Code1__c == null)){
                lead.Assignment_Area_Code1__c = defaultAreaCode.Id;
            }}
        }
    }
    
// Set aca on Lead edit

public void setAreaCodeUpdate(List<Lead> newLeads, Map<Id, Lead> oldLeads) {
        Area_Code_Assignment__c defaultAreaCode = null;
        Map<String, Area_Code_Assignment__c> areaCodeMap = new Map<String, Area_Code_Assignment__c>();
      
            for(Area_Code_Assignment__c areaCodeA : [SELECT Id, Name FROM Area_Code_Assignment__c LIMIT 500]) {
                areaCodeMap.put(areaCodeA.Name, areaCodeA);
            }
      
        if(System.Label.Default_Area_Code != null && areaCodeMap.containsKey(System.Label.Default_Area_Code)) {
            defaultAreaCode = areaCodeMap.get(System.Label.Default_Area_Code);
        }
        for(Lead lead : newLeads) {
            if(lead.Phone != null && lead.Phone != oldLeads.get(lead.Id).Phone ) {
                String phone = lead.Phone.replace('(', '').replace(')', '');
                String areaCodeA = phone.substring(0,3);
                
                if((areaCodeA.Length()==3) && (areaCodeMap.containsKey(areaCodeA))) {
                    lead.Assignment_Area_Code1__c = areaCodeMap.get(areaCodeA).Id;
                }
            
            if((areaCodeA.Length()!=3) || (lead.Assignment_Area_Code1__c == null && defaultAreaCode != null)) {
                lead.Assignment_Area_Code1__c = defaultAreaCode.Id;
            }}
        }
    }
}
and here is my trigger:
 
trigger UpdateLeadACA on Lead (before insert, before update) {
    UpdateLeadACAHandler handler = new UpdateLeadACAHandler();
    if(Trigger.isBefore) {
        if(Trigger.isInsert) {
            handler.setAreaCodeInsert(Trigger.new);
           
        }
        if(Trigger.isUpdate) {
            handler.setAreaCodeUpdate(Trigger.new, Trigger.oldMap);
           
        }
    }

}


 
  • May 13, 2016
  • Like
  • 0
I already have VF page which has the Save and cancel button , I want to create a new button " Save & New ".. i do not know how to make it return to the page to create a new record 

public PageReference doFullSave(){
 // this is my Save method
}
public PageReference doFullSave1(){ // this is my save and new method which has to return to the save mode again 
   doFullSave();
  PageReference retPage = new PageReference('/'+ ApexPages.currentPage().getParameters().get('retURL'));
  PageReference returnPage = new PageReference(ApexPages.currentPage().getParameters().get('retURL'));
   return returnPage;
    }

VF page :
<apex:pageBlockButtons >
<apex:commandButton value="Save" action="{!doFullSave}"/>
<apex:commandButton value="Cancel" action="{!doCancel}" immediate="true"/>
<apex:commandButton value="Save and New" action="{!doFullSave1}"/>
</apex:pageBlockButtons>

This is the url on the new record page 
sandbox--c.cs4.visual.force.com/apex/CallLog?CF00N6000000268Gm=test12345&CF00N6000000268Gm_lkid=a0wP00000010bHcIAI&retURL=%2Fapex%2FSL_MassEdit_CallLog%3FpId%3Da0wP00000010bHcIAI%26justView%3Dtrue%26page%3D0%26cbf%3Dnull%26cbaf%3Dnull%26qb%3DAll%26qs%3DAll%26qct%3DAll%26qtt%3D%26sortE%3DName%26sortD%3DASC%26cb_letterFilter%3DAll&scontrolCaching=1&sfdc.override=1
Hi guys.I need in an apex class a Map of Cases ID with their Attachemnts and a List with that Attachment. Now i write this:
Map<Id, List<Attachment>> AttachMap = new Map<Id,List<Attachment>>([
                           select id,(select id from attachments) from case]);
But i receive the error:
 Invalid initial type List<Case> for Map<Id,List<Attachment>>.
How can i get the Map and after the list of Attachment based on case Id. Please help me 
This is my Both classes And code coverage is 86% please help me to achieve 100% code coverage
Thanks & Regards
Jasveer Singh

public class WrapperClearFunda {

public List<Account> acclist{get;set;}
public List<Contact> conlist{get;set;}
public List<Wrapperclass> wl{get;set;}

public List<Wrapperclass> wlacc{get;set;}
public List<Wrapperclass> wlcon{get;set;}

public WrapperClearFunda(){
acclist=new List<Account>();
conlist=new List<Contact>();

wlacc=new List<Wrapperclass>();
wlcon=new List<Wrapperclass>();

wl=new List<Wrapperclass>();
acclist=[select name from account];
conlist=[select Lastname from Contact];

// insert value into 1st Constructor
for(Integer i=0;i<5;i++)
{
wl.add(new Wrapperclass(acclist[i],conlist[i]));
}

// insert value into 2nd Constructor
for(Account a:acclist){
wlacc.add(new Wrapperclass(a));
}


// insert value into 3rd Constructor
for(Contact c:conlist){
wlcon.add(new Wrapperclass(c));
}


}



public class Wrapperclass{
public Account acc{get;set;}
public Contact con{get;set;}

// 1st Constructor
public Wrapperclass( Account acc, Contact con){
this.acc=acc;
this.con=con;
}

// 2nd Constructor
public Wrapperclass( Account acc){
this.acc=acc;
}

// 3rd Constructor
public Wrapperclass( Contact con){
this.con=con;
}

}


}


+++++++++++++++++++++++++++++++++++++++

@isTest 
private class WrapperClearFundaTest{
  // WrapperClearFunda wcf=new WrapperClearFunda ();
  
    static testMethod void validateHelloWorld1() {
    Account acc=new Account();
    Contact con=new Contact();
    WrapperClearFunda.Wrapperclass w1=new WrapperClearFunda.Wrapperclass(acc,con);
    }
    
    static testMethod void validateHelloWorld2() {
    Account acc=new Account();  
    WrapperClearFunda.Wrapperclass w2=new WrapperClearFunda.Wrapperclass(acc);
    }


    static testMethod void validateHelloWorld3() {
    Contact con=new Contact();
    WrapperClearFunda.Wrapperclass w3=new WrapperClearFunda.Wrapperclass(con);
    }


    static testMethod void validateHelloWorld4() {
    WrapperClearFunda wcf=new WrapperClearFunda ();
   // WrapperClearFunda.Wrapperclass w4=new WrapperClearFunda.Wrapperclass();
    Account acc=new Account(name='axz');
    Contact con=new Contact(lastname='abc');
          insert acc;
          insert con;
          System.assertEquals('abc', con.lastname);
          System.assertEquals('axz', acc.name);
    }

}
 
Hi All,

I have to schedule an Apex class, using a custom schedule page. I have to write the CRON EXPRESSION based on the requirements like :
It should be scheduled between specific days (like, we would have a start date and an end date) along with on specific days of the week (like, on Saturday or Sunday); i.e. something like Schedule an apex class on Sundays between 12/05/2016 to 12/06/2016.
Please help.
Thanks in advance.
<apex:page standardController="Account" extensions="contrller">
  <apex:form >
    <apex:pageblock >
       <!-- Display Account related Contacts -->
       <apex:pageBlockTable value="{!relatedContacts}" var="val">
         <apex:column value="{!val.name}"/>
         <apex:column value="{!val.email}" />
         <apex:inputField value="{!val.name}"/>
       </apex:pageBlockTable> 
    </apex:pageblock>
  </apex:form>
</apex:page>

public with sharing class contrller {
Public id Current_Acc_Id;

    public contrller(ApexPages.StandardController controller) {
    Current_Acc_Id = controller.getRecord().id;
    }

    public List<Contact> getrelatedContacts(){
        List <contact> conList = New List<Contact>();
        for(Account acc:[select id,name,(select name,id,email from contacts) from account where id=:Current_Acc_Id]){
           for(contact con:acc.contacts)
               conList.add(con); 
        }
        return conList;
    }
}
Need help for Code coverage to json parser in locationcallouts apex class
Hi,

Need to help for code coverage i got 66% but json part not coveing in my controller please look into my code
================Apex Class====================
public class LocationCallouts {

     @future (callout=true)  // future method needed to run callouts from Triggers
      static public void getLocation(id accountId){
        // gather account info
        Account a = [SELECT BillingCity,BillingCountry,BillingPostalCode,BillingState,BillingStreet FROM Account WHERE id =: accountId];
 
        // create an address string
        String address = '';
        if (a.BillingStreet != null)
            address += a.BillingStreet +', ';
        if (a.BillingCity != null)
            address += a.BillingCity +', ';
        if (a.BillingState != null)
            address += a.BillingState +' ';
        if (a.BillingPostalCode != null)
            address += a.BillingPostalCode +', ';
        if (a.BillingCountry != null)
            address += a.BillingCountry;
 
        address = EncodingUtil.urlEncode(address, 'UTF-8');
        
        General_Settings__c ge= General_Settings__c.getValues('API Key');
        General_Settings__c eurl= General_Settings__c.getValues('Geocoding URL');        
        System.debug('##########'+eurl);
        System.debug('@@@@@@@@@@'+ge);
        String geocodingKey = ge.Value__c;
        String endpointurl= eurl.Value__c;
 
        // build callout
        Http h = new Http();
        HttpRequest req = new HttpRequest();
      //req.setEndpoint('http://maps.googleapis.com/maps/api/geocode/json?address='+address+'&sensor=false');
        req.setEndpoint(endpointurl+'?address='+ address + '&key=' + geocodingKey + '&sensor=false');
        req.setMethod('GET');
        req.setTimeout(60000);
 
        try{
            // callout
            HttpResponse res = h.send(req);
             System.debug('&&&&&'+res.getBody());
             System.debug('#####');
            // parse coordinates from response
            JSONParser parser = JSON.createParser(res.getBody());
            double lat = null;
            double lon = null;
            while (parser.nextToken() != null) {
                if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) &&
                    (parser.getText() == 'location')){
                       parser.nextToken(); // object start
                       while (parser.nextToken() != JSONToken.END_OBJECT){
                           String txt = parser.getText();
                           parser.nextToken();
                           if (txt == 'lat')
                               lat = parser.getDoubleValue();
                           else if (txt == 'lng')
                               lon = parser.getDoubleValue();
                       }
 
                }
            }
 
            // update coordinates if we get back
            if (lat != null){
                a.GeoLocations__Latitude__s = lat;
                a.Location_Latitude__c = lat;
                a.GeoLocations__Longitude__s = lon;
                a.Location_Longitude__c = lon;
                Lat= lat;
                Lon= lon;
                update a;
            }
 
        } catch (Exception e) {
        }
    }
}
===================ApexTest Class===================
@IsTest(SeeAllData=False)
public class Test_LocationCallouts {
    static testMethod void validateLocationCallouts() {
   
    General_Settings__c setting1 = new  General_Settings__c();
    setting1.Name = 'Geocoding URL';
    setting1.Value__c = 'https://maps.googleapis.com/maps/api/geocode/json';
    insert setting1;
    General_Settings__c setting2 = new  General_Settings__c();
    setting2.Name = 'API Key';
    setting2.Value__c = 'AIzaSyBdTDHIFZgg1lG_p9fCg5QYcWWKrWe6K_E';
    insert setting2;
   
    Account a = new Account(Name='Testsup', BillingCountry='USA',BillingState='New Jersey',BillingCity='Cliff Wood',
                            BillingPostalCode='07010',BillingStreet='cliff wood');
    insert a;

        LocationCallouts.getLocation(a.id);
        Test.startTest();
        Test.setMock(HttpCalloutMock.class, new MockHttpResponseGenerator());
        Test.stopTest();
        HttpResponse res = CalloutClass.getInfoFromExternalService(); 
    }
}

================Dummy callout class===========
@isTest
global class MockHttpResponseGenerator implements HttpCalloutMock {
    global HTTPResponse respond(HTTPRequest req) {
        // Create a fake response.
        // Set response values, and
        // return response.
        system.debug('Mock ApiListMtgListMeetingsResult');
       
        //System.assertEquals('http://api.salesforce.com/foo/bar', req.getEndpoint());
        System.assertEquals('GET', req.getMethod());

 
       HttpResponse res = new HttpResponse();
       res.setHeader('Content-Type', 'text/xml;charset=UTF-8');
       //req.setEndpoint('http://maps.googleapis.com/maps/api/geocode/json?address='+address+'&sensor=false');
       res.setBody('{"name":"testrec","billingcountry":"United States","BillingState":"New Jersey","BillingCity":"California","BillingPostalcode":"07010","lat":37.386,"lon":-122.084}');
       res.setStatusCode(200);
       return res; 
       
    }
}
===============Coverage Status===============


Can any one help?
User-added image
Hello All,

I have launched my new chrome extension "Quick Access and Backup". For salesforce developer, user or admin this extension is helpful to quickly access salesforce component and you can take backup also.

Please download by clicking below link and share your feedback:
https://chrome.google.com/webstore/detail/quick-access-and-backup/elphfagjcohjcfblfidejpiolkocfkhd

For quick demo how to use quick access and backup visit the below link :
https://youtu.be/vttWypc4Jl0
 
Thanks and regards
Rohit Sethi
 
 
Hi All,

Please send me an example which is included the jQuery.

Thanks.
Hi All,

I have a requirement that, i need to be open a new window from detail page button.
And that opened window contains a update button. And when click on update button i want to reload previous page from its opened.

Example :
Suppose I created the detail page button on account and that open the visualforce page and after click on 
update button i want to reload the account.

Please guide me ,how can we achive this requirement.

Thanks.

Actually we insert the attachment under account as pdf
and once a pdf  is attached with the account and next time If with same content the pdf is attached with same account then I have to prevent.
Thanks.
 
Hi All,

Can we create the AccountHistory Reocrd in test class if it is possible plz post how ?

Thanks.
hi ,

I have to create google chart from apex class and insert the chart into attachement.

Thanks.
hi ,

I have to create google chart from apex class and insert the chart into attachement.

Thanks.
Hi All,

I have created the below visual force page and apex controller, but get the following error message when redirected to this page. Can anybody see an error with the code, this visual force page URL is embedded in a custom button on a custom object within our org.

Invalid id: <a href="https://cs57.salesforce.com/a3Z0k0000004QjG" target="_blank">Process Payment</a>
Error is in expression '{!validateAndRedirect}' in component <apex:page> in page svmxredirectpage: Class.SVMXGenericRedirectController.validateAndRedirect: line 8, column 1
 
An unexpected error has occurred. Your development organization has been notified.

SVMXRedirectPage
 
<apex:page controller="SVMXGenericRedirectController" action="{!validateAndRedirect}">
  <apex:pageMessages ></apex:pageMessages>
</apex:page>
 
SVMXGenericRedirectController
public class SVMXGenericRedirectController {
 
 
    public Id objId {get; set;}
   
    public PageReference validateAndRedirect(){
       
        if (ApexPages.currentPage().getParameters().get('objId') != null && ApexPages.currentPage().getParameters().get('objId') != '') {
            objId = ApexPages.currentPage().getParameters().get('objId');
           
            PageReference retURL = new PageReference('/' + objId);
            retURL.setRedirect(true);
            return retURL;
        } else {
            ApexPages.addMessage(new ApexPages.message(ApexPages.severity.WARNING, Label.SVMXMissingId));
        }
       
        return null;
    }
   
}
 
SVMXGenericRedirectControllerTest
@isTest
public class SVMXGenericRedirectControllerTest {
 
 
    public testmethod static void SVMXGenericRedirectControllerTest() {
        
        Test.StartTest();
       
        PageReference pageRef = Page.SVMXRedirectPage;
        pageRef.getParameters().put('objId', 'a3Z0k0000004Lwi');
        Test.setCurrentPage(pageRef);
       
        SVMXGenericRedirectController svmxController = new SVMXGenericRedirectController();
        svmxController.validateAndRedirect();
       
        Test.StopTest(); 
         
    } 
   
    public testmethod static void SVMXGenericRedirectControllerWithoutParamsTest() {
        
        Test.StartTest();
       
        PageReference pageRef = Page.SVMXRedirectPage;
        Test.setCurrentPage(pageRef);
       
        SVMXGenericRedirectController svmxController = new SVMXGenericRedirectController();
        svmxController.validateAndRedirect();
       
        Test.StopTest(); 
         
    } 
   
}

Thanks,
Brenden
Hi,

We are invoking a apex class through js on click of a button. In that apex class we are invoking the webservice. 
Before invoking the webservice we are checking for some conditions and need to display some custom exceptions but it is not wokring.
js code behind the button
{!REQUIRESCRIPT("/soap/ajax/29.0/connection.js")}
{!REQUIRESCRIPT("/soap/ajax/29.0/apex.js")}
var result = sforce.apex.execute("HPGenerateLicnese","HPLic",{LicId:"{!HP_License__c.HP_License_Id__c}"});
window.location.reload();

custom exception class:
public class HPCusotmException extends Exception {}

Custom class to invoke the webservice:
global class HPGenerateLicnese 
{
   WebService static String HPLic(Id LicId)
    {
        String keyString;
        Integer version;
        Integer seats;
        String expireDate;
        String subExpireDate;
        Boolean cleanserEnabled;
        String returnvalue;
       
        HP_License__c  L = [SELECT Id, HP_Registration_Number__c,HP_Version__c,HP_Qutantity__c, HP_Temporary_License_Expires__c, HP_Expires__c, HP_License_Type__c FROM HP_License__c WHERE Id = :LicId] ;
        
        String sLicType = L.HP_License_Type__c ;
        
        //covert the quantity to integer
        Integer intSeats = L.HP_Qutantity__c.intValue(); 
        
        //Converting version to integer
        String tes = L.HP_Version__c ;
        Integer sld = tes.length();
        String sVer ;
        Integer myInt ;
        if(sld >= 0)
        {
            sVer = tes.substring(0, 1);
            myInt = Integer.valueof(sVer);
        }
       
       //Show error message if service expiry is null and licnese type = Permanent    
        DateTime d;String monthName;String sday;String sYesr;String sDt; String sError;
        if((sLicType == 'Permanent')&&(L.HP_Expires__c == null))
        {           
             try
             { 
                sError = 'Y';
                if(L.HP_Expires__c == null) throw new HPCusotmException('Hi'); 
             }
             catch(HPCusotmExceptione)
             {
               throw new HPCusotmException('Hi');   
             }

             // returnvalue = 'Please enter the Service Expire Date'; 
                
        }
         
        // to get the temporary license expired in a specified format ex. May 21, 2107
        DateTime td;String monthNm;String sdy;String sYr;String sDat;
        if((L.HP_Temporary_License_Expires__c == null)&&(sLicType == 'Temporary'))
        {
           sError = 'Y';
           returnvalue = 'Please enter the Temporary License Exp Date';
        }
        
        //method inputs
        keyString = L.HP_Registration_Number__c ;
        version = myInt ;
        seats = intSeats ;
       
        cleanserEnabled = false;
        
        if((sLicType == 'Permanent')&&(L.HP_Expires__c != null))
        {
            expireDate = 'Never';
             // to get the service expired in a specified format ex. May 21, 2107
             d = L.HP_Expires__c ;                    
            monthName= d.format('MMM');
            sday = d.format('dd');
            sYesr = d.format('YYYY');
            sDt = monthName+' '+sday+','+' '+sYesr ;
             subExpireDate = sDt ;
            //invoke the webservice method
            
        }

can some one let me where am i going wrong ?

Regards,
Pallavi
  • August 19, 2016
  • Like
  • 0
Hi friends,I am getting an error for a trigger. Condition is: I want to create an product whenever I am creating any opportunity. In opportunity, product is on the based of dependent picklist. Error is -  Error    Error: Compile Error: Entity is not api accessible at line 1 column 1

Code is as below:

trigger CreateProduct on Opportunity (after insert) {
for(Opportunity opp: trigger.new){
Product pod = new Product();
pod.Name = opp.Select_Product__c;

pod.Opportunityid = opp.id;
insert pod;
}
}
  • August 12, 2016
  • Like
  • 0
Here's my Visualforce page:
<apex:page docType="html-5.0" sidebar="false" showHeader="false" standardStylesheets="false" controller="TestController">

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

    <script type="text/javascript">
        jQuery.noConflict();

        jQuery(document).ready(function() {
            jQuery('[id$=polamonolaa]').bind( "click", function() {
              alert( "Test" );
            });
        })
    </script>

    <apex:form>
        <apex:commandLink action="{!showTest}" value="Show" reRender="panelTest"/>
        <br/>
        <apex:outputPanel id="panelTest">
            <apex:outputPanel id="panelTest2" rendered="{!showTestPanel2}">
                <apex:commandLink id="polamonolaa" reRender="panelTest" value="TOP"/>
            </apex:outputPanel>
        </apex:outputPanel>
    </apex:form>
</apex:page>
Here's my controller:
public class TestController {
    public Boolean showTestPanel2{get;set;}

    public TestController(){
        showTestPanel2 = false;
    }

    public void showTest(){
        showTestPanel2 = true;
    }
}

What I'm trying to do here is to show an alert on a button click. Unfortunately my script doesn't work when button is placed inside outputPanel id="panelTest2" which rendered attribute depends on showTestPanel2 variable. Any suggestions how to fix this issue? Moving my button outside inner panel is not an option.
Hi,
If the User enters a date in the Selected Date field and presses the 'Go' button, then the system centers the calendar view on the date that was entered. How to achieved this?
Hi,

I have a custom button that is used to generate an order from a Quote. Whenever that is clicked, I want to display an error msg saying this will "create a single order for the Product. do you want to continue?"

How can I do that? Right now the custom button goes like this: /flow/Quote_to_Order?QuoteID={!Quote.Id}&retURL=/{!Quote.Id}
How can I know the number of fields in an object and how can I append entire fields at once? Please guide.
User-added image

As in the above pic shows, I don't want to display the Standard error message which i rounded in pic. How can i make disable it? I want to display only the message what we used generally in 
ApexPages.addMessage(new ApexPages.message(ApexPages.severity.error,'Error Message'));

I can make this possible by using if - else condition (Please see the code which provided), but i want get it through using try - catch blocks only. And also please tell me that how we are getting Required fields are missing: [Account Name] message. Is that system validation rule or any other error message?
You can also see the code which i have used.
public void comittedResult() {
        try{
        aOne=[select id,name,phone,Industry from Account where ID=:accid];
       /* if (String.isBlank(accName)){
            ApexPages.addMessage(new ApexPages.message(ApexPages.severity.error,'Please enter account name'));
        }//!(accPhone.isNumeric())
        else if(!(pattern.matches('[0-9]+',accPhone))){
            ApexPages.addMessage(new ApexPages.message(ApexPages.severity.error,'Please enter correct phone number'));
        }
        else  {*/
        aOne.name = accName;
        aOne.phone = accPhone;
        update aOne;
        displayPopup = false;
        reflectRecords();
   //   }
     }catch(DMLException e){
         ApexPages.addMessage(new ApexPages.message(ApexPages.severity.error,'Please enter Name'));
     }
     }

Thanks in advance.
KS Kumaar
trigger abcAccount on Opportunity (before update) {
    list<id> oppIds = new list<id>();
    //if(trigger.isInsert || trigger.isUpdate){
        for(opportunity opp : trigger.new){
            system.debug('opp'+opp);
            system.debug('opp.Account.name'+opp.Account.name);
            if(opp.Account.name=='Axis'){
             system.debug('opp'+opp);
                opp.amount = opp.amount*10/100;
                //oppIds.add(opp.id);
            }
        }
    //}

}

Hi I am getting null for opp.Account.name when ued system.debug('opp.Account.name'+opp.Account.name);
 Actually iam trying to disount on amount when related account of the opportunity is changed to Axis.
Can some one help me on this?
 

Actually we insert the attachment under account as pdf
and once a pdf  is attached with the account and next time If with same content the pdf is attached with same account then I have to prevent.
Thanks.
 
User-added image

As the above page showing, If i click on the button, the corresponded output should be taken to respected detailed page. But it does not taking into respected output. I tried with following Controller and VF page.
Controller :
public class Redirect_Main1 {

   public List<Account> accs { get; set; }
   public ID aid;
    
    public void access(){
        accs = [select id,name,phone,Industry from account];
        for(Account acc:accs){
            aid = acc.id;
        }
        }
       public String getAccess2(){
         return 'https://ap2.salesforce.com/'+aid;
         }
   }
 
VF Page :
<apex:page Controller="Redirect_Main1" action="{!access}">
    <apex:form >
        <apex:pageBlock >
            <apex:pageBlockTable value="{!accs}" var="a">
                <apex:column value="{!a.Id}"/>
                <apex:column value="{!a.Name}"/>
                <apex:column value="{!a.Phone}"/>
                <apex:column value="{!a.Industry}"/>
                <apex:column >
                    <apex:commandButton value="Click" action="{!access}"/>
                        <apex:param name="account" assignTo="{!aid}" value="{!access2}"/>
               </apex:column>
            </apex:pageBlockTable>
        </apex:pageBlock>
    </apex:form>
</apex:page>
I have tried maximum up to my best, but i could not get respected output. May be i think so, i committed wrong with <apex;param> component. Please let me know where i did mistake.
I get an error before the AND is the last statement. (Description LIKE '%POI Document%') AND LastModifiedDate"

I changed it to WHERE and nada. It verified at OR but that pulled too many records.


SELECT Id, Name, Body, Description, ContentType FROM Attachment WHERE (Description LIKE '%Envelope%') OR (Description LIKE '%PNL Document%') OR (Description LIKE '%OOS Document%') OR (Description LIKE '%POI Document%') AND LastModifiedDate >= YESTERDAY AND LastModifiedDate < TODAY
 
There has been an error in the SOQL query: MALFORMED_QUERY: (Description LIKE '%POI Document%') AND LastModifiedDate >= YESTERDAY ^ ERROR at Row:1:Column:219 unexpected token: AND
I'm using a script and windows.open function to go to a specific URL when a user click a button on the VFpage. Something is going wrong because after the click the same page is reloaded.
SCRIPT:
<script type="text/javascript"> function goback() { window.open(retURL); } </script>


Inside the retURL variable, there is the URL where I want to go, something like:https://eu6.salesforce.com/0015800000DuQWsAAN'
button:
<apex:commandButton action="{!deleteContract}" value="Elimina Contratto e prodotti selezionati" immediate="true" onclick= "goback()" /> </apex:pageBlockButtons>


How can I solve this problem?
Hi All,

Can we create the AccountHistory Reocrd in test class if it is possible plz post how ?

Thanks.
I am new to Apex and trying to access the value from Custom Controller having SOQL query and show it on visualforce page as an Output link.
Visualforce snippet:
<div class="count"><apex:outputText value="{!Records}"/></div>
Apex Code Snippet:
public Integer getDisplayQueryList() { Records = 0; Records = [select count() from Case where Type like 'MDD Increase from WSC']; return Records; }
Also I have read about the AggregateResult[] which might be the best way to use but not sure how to use it properly. My main aim is to search & Count for all Cases which are NOT Closed & of Type = MDD Increase from WSC and then display that count in the visual force page.
Any Help would be much appreciated.

Hi All, Im attemtping to write a controller extention to the standard controller "CIOA_Submissions__c" I have a created a VF page which serves as my submission form and it is being controlled by the standard controller. I need my extension to render the approval process via a 'submit' commandbutton, and also have the record approved from the visual force page via the 'approve' commandbutton. I get an invalid type for "Approval.ProcessWorkitemRequest". Any suggestions on code corrections?

public class ApprovalExtender{
CIOA_Submissions__c extension;

public ApprovalExtender(ApexPages.standardController stdController){
    this.extension=(CIOA_Submissions__c) stdController.getRecord();
}

public override void int(){
}

public PageReference approve(){
   Id id=ApexPages.currentPage().getParameters().get('id');
    
    Integer cnt=[SELECT COUNT() FROM Processinstance WHERE TargetObjectid = :id AND Status='Pending'];
    System.debug ('count=' + cnt);
    if(cnt==0){
        ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.INFO, 'Not pending record'));
        return null;
    }
    return null;
}
    Id processId=[SELECT Id FROM ProcessInstance WHERE TargetObjectId = :id AND Status = 'Pending' Limit 1].Id;
    Id workitemId=[SELECT Id FROM ProcessInstanceWorkItem WHERE ProcessInstanceId = :processId Limit 1].Id;
    
    Approval.ProcessWorkitemRequest = new Approval.ProcessWorkitemRequest();
    request.setAction('Approve');
    request.setNextApproverIds(new Id[]{UserInfo.getUserId()});
    request.setWorkitemId(workitemId);
    Approval.ProcessResult result=Approval.process(request);
    
    if(result.isSuccess()){
         ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.CONFIRM,'Submission Approved'));
        }
        else{
        ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR,'Submission Pending'));
        }
        return null;
    }
     
     public PageReference submit(){
         Id id=ApexPages.currentPages().getParameters().get('id');
         
        Approval.ProcessSubmitRequest req1 = new Approval.ProcessSubmitRequest();
        req1.setComments('Submitting request for approval');
        req1.setNextApproverIds(new Id[]{Userinfo.getUserId()});
        req1.setObjectId(id);
        Approval.ProcessResult result = Approval.process(req1);
         
          if(result.isSuccess()){
        ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.CONFIRM,'Submission Submitted Successfully'));
        }
        else{
        ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity,ERROR,'Submission Not Submitted Please Try Again'));
        }
        return null;
        }
     }
When using Ajax, what is governor restriction with a possibility which occurs?

Posting this in order to help others who, months from now, might Google "OP_WITH_INVALID_USER_TYPE_EXCEPTION" and find this explanation.

 

We wrote an Apex trigger on the User object, to insert a custom object record anytime a user updates their Chatter status.  This was done to fulfill a client's requirement to audit all Chatter activity.

 

The trigger worked fine, until one day the client signed up some Chatter Free users.  When such a user tried to update their status, they got a pop-up with an OP_WITH_INVALID_USER_TYPE_EXCEPTION error.

 

We scratched our collective heads for awhile.  After all, Apex triggers run in "system mode," right?  That is supposed to mean that "object and field-level permissions of the current user are ignored."  And yet this trigger seemed like it was running in "user mode," enforcing restrictions based on who the current user was.

 

The root cause turned out to be that a Chatter Free user cannot be the owner of a custom object record, and SFDC by default sets the current user as a new record's first owner.  We discovered this when we realized, via experiment, that Apex triggers fired as the result of actions by Chatter Free users could definitely update an existing record, but were having problems creating records.

 

So the simple solution was to explicitly set the owner of the new record to some fully-licensed user prior to inserting it.