[SalesForce] Run javascript before redirecting to visualforce page – Custom List button

I have a custom list button on contact with behavior as shown below:
enter image description here

And this custom button is added to the contact related list on account
enter image description here

When I select 2 or more contacts and click on custom button, it redirects me to the visualforce page with the selected contacts and everything looks good. I am trying to put a validation (may be javascript alert message) that before redirecting to visualforce page, atleast 2 contacts are selectes.

Here is my visualforce page:

<apex:page standardController="Contact" recordSetVar="Contacts">
  <apex:form >
     <apex:pageBlock >
       <apex:pageBlockTable value="{!selected}" var="con">
         <apex:column value="{!con.name}"/>
       </apex:pageBlockTable>
     </apex:pageBlock>
  </apex:form>    
</apex:page>

Thanks

Best Answer

I too faced this issue

Try the below method

1) Choose the Onclick Javascript in the content source for custom button

2) Paste the below code for execution of javascript

{!REQUIRESCRIPT("/soap/ajax/30.0/connection.js")} 
{!REQUIRESCRIPT("/soap/ajax/30.0/apex.js")} 
var records={!GETRECORDIDS($ObjectType.**(Your Related List Object - Contact)**)};
if(records.length > 2){
// Call your VF Page like below
// window.open('/apex/VFPAGENAME?id={!Account.Id}','_self');
}
else{
// Alerts
}

3) Save the custom button and check

If this solved your problem, Please check this one as accepted answer so it might be easily helpful to someone...

Related Topic