+ Start a Discussion
Gheorghe SimaGheorghe Sima 

how to create an "Add button" on a related list

Hi,
I have a custom object named Service__c and it has a lookup with other object named Product__c. I want to create a button which allows me to add multiple products on the Product related list from Service object. This button should do what the "Add product" button from Order does(whitout that filter )
User-added image
Best Answer chosen by Gheorghe Sima
Mohit Bansal6Mohit Bansal6
Hi Amit

I think you know how to create a custom button and show it on the related list of product.

Before creating a new custom button, create a new vf page and class and paste below code to it. This is a dummy page which list all the contacts and we can select any of them as per our needs. So you can modify this code to list your products and can select any of them and link to your service record.

Kindly refer the concept of Wrapper Class:
https://developer.salesforce.com/page/Wrapper_Class

Visualforce Page:
<apex:page controller="wrapperClassController">
    <apex:form >
        <apex:pageBlock >
            <apex:pageBlockButtons >
                <apex:commandButton value="Process Selected" action="{!processSelected}" rerender="table"/>
            </apex:pageBlockButtons>
            <!-- In our table we are displaying the cContact records -->
            <apex:pageBlockTable value="{!contacts}" var="c" id="table">
                <apex:column >
                    <!-- This is our selected Boolean property in our wrapper class -->
                    <apex:inputCheckbox value="{!c.selected}"/>
                </apex:column>
                <!-- This is how we access the contact values within our cContact container/wrapper -->
                <apex:column value="{!c.con.Name}" />
                <apex:column value="{!c.con.Email}" />
                <apex:column value="{!c.con.Phone}" />
            </apex:pageBlockTable>
        </apex:pageBlock>
    </apex:form>
</apex:page>

Controller:
 
public class wrapperClassController {

	//Our collection of the class/wrapper objects cContact 
	public List<cContact> contactList {get; set;}

	//This method uses a simple SOQL query to return a List of Contacts
	public List<cContact> getContacts() {
		if(contactList == null) {
			contactList = new List<cContact>();
			for(Contact c: [select Id, Name, Email, Phone from Contact limit 10]) {
				// As each contact is processed we create a new cContact object and add it to the contactList
				contactList.add(new cContact(c));
			}
		}
		return contactList;
	}


	public PageReference processSelected() {

                //We create a new list of Contacts that we be populated only with Contacts if they are selected
		List<Contact> selectedContacts = new List<Contact>();

		//We will cycle through our list of cContacts and will check to see if the selected property is set to true, if it is we add the Contact to the selectedContacts list
		for(cContact cCon: getContacts()) {
			if(cCon.selected == true) {
				selectedContacts.add(cCon.con);
			}
		}

		// Now we have our list of selected contacts and can perform any type of logic we want, sending emails, updating a field on the Contact, etc
		System.debug('These are the selected Contacts...');
		for(Contact con: selectedContacts) {
			system.debug(con);
		}
		contactList=null; // we need this line if we performed a write operation  because getContacts gets a fresh list now
		return null;
	}


	// This is our wrapper/container class. A container class is a class, a data structure, or an abstract data type whose instances are collections of other objects. In this example a wrapper class contains both the standard salesforce object Contact and a Boolean value
	public class cContact {
		public Contact con {get; set;}
		public Boolean selected {get; set;}

		//This is the contructor method. When we create a new cContact object we pass a Contact that is set to the con property. We also set the selected value to false
		public cContact(Contact c) {
			con = c;
			selected = false;
		}
	}
}

You can modify the code as per your needs and object details.

Finally link this page to the custom button.

Regards
Mohit Bansal

In case, you face any issue, drop me message on forum or Skype me @mohit_bansal17, if you need any help.

Please mark this as solution by selecting it as best answer if this solves your problem, So that if anyone has this issue this post can help.

All Answers

ManojjenaManojjena
Hi Gheorghe Sima,

You need to create a list button in product  object .Need to edit the layout of service object and click on related list .Go to the product related list and click on the wrench symbol .

Click on the button section and add the button like below .

User-added image

Let me know if it helps .

Thanks 
Manoj

 
Gheorghe SimaGheorghe Sima
I know how to create a list button. I want to see the code for that button. I am new in salesforce and i think that this button has a code in the back. Can you help me with this problem?
ManojjenaManojjena
No , you will not able to see the code behind the button . 


 
Amit  TrivediAmit Trivedi

<apex:page standardController="Products_SFDC__c" extensions="FirstHomePageController" docType="html-5.0" id="pgopp"> <apex:includeScript value="{!URLFOR($Resource.TM_jQuery, 'jQuery/jquery2.1.1.min.js')}"/> <br/><br/><br/> <style> h1 { margin-left: 300px; font-size: 1.5em; font-family: 'Source Sans Pro', sans-serif !important; font-weight: 600; } .rectyppanel { margin-left: 150px; } </style> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <apex:form id="frm" > <apex:pageMessages ></apex:pageMessages> <script type="text/javascript"> var j$ = jQuery.noConflict(); j$(document).ready(function() { j$("[id*=rectyp]").change(function() { var pickListValue = j$(this).val(); updateit(pickListValue); }); }); function hellofunc() { j$("[id*=thePanel]").show(); j$("[id*=btn]").show(); j$("[id*=thePanel22]").hide(); j$("[id*=pbtable]").hide(); j$("[id*=btnone]").hide(); } function hellofuncone() { j$("[id*=thePanel]").show(); j$("[id*=pbtable]").show(); j$("[id*=btn]").show(); j$("[id*=btnone]").show(); } function hellofunctwo(){ } function selectCheckboxes(inpt,receivedInptID) { var inputCheckBox = document.getElementsByTagName("input"); for(var i=0; i<inputCheckBox.length; i++) { if(inputCheckBox[i].id.indexOf(receivedInptID)!=-1) { inputCheckBox[i].checked = inpt.checked; } } } </script> <br/> <apex:outputpanel styleclass="rectyppanel" > <h1>Select Product </h1>&nbsp;&nbsp;&nbsp; <!-- <apex:selectList multiselect="false" size="1" id="rectyp" > <apex:selectOption ></apex:selectOption> <apex:selectOptions value="{!items}"/> </apex:selectList> --> </apex:outputpanel> <br/><br/><br/> <!--Initially Display this table while selecting record type---> <div align="center" draggable="false" id="btn" style="display:block"> <apex:commandButton value="Select" action="{!selectProduct}" reRender="frm" oncomplete="hellofuncone()"/>&nbsp;&nbsp;&nbsp; <apex:commandButton value="Cancel"/> </div><br/> <apex:outputPanel id="thePanel1" style="display:block"> <apex:pageblock > <apex:pageblocktable value="{!productWraList}" var="wraprec"> <apex:column > <apex:facet name="header"> <apex:inputCheckbox onclick="selectCheckboxes(this,'inputId')"/> </apex:facet> <apex:inputCheckbox value="{!wraprec.selected}" id="inputId"/> </apex:column> <apex:column value="{!wraprec.product.name}"/> <apex:column value="{!wraprec.product.Price__c }" headerValue="List Price"/> <apex:column value="{!wraprec.product.Description__c}" headerValue="Product Description"/> </apex:pageblocktable> </apex:pageblock> </apex:outputPanel> <!--Initially Display this table while selecting record type---> <apex:outputPanel id="thePanel22" style="display:none"> <apex:pageblock > <apex:pageblocktable value="{!productWraListSelected}" var="wraprecrd" id="pbtable" style="display:none" > <apex:column value="{!wraprecrd.Product.Name}" headerValue="Name" id="pbtable1" /> <apex:column headerValue="List Price"> <apex:outputText value="{!wraprecrd.Product.Price__c}"/> </apex:column> <apex:column headerValue="Sales Price *"> <apex:inputText value="{!wraprecrd.Product.Price__c}" styleClass="spsc" id="salespriceid"/> </apex:column> <apex:column headerValue="Discount(%)"> <apex:inputText value="{!wraprecrd.Discount}" /> </apex:column> <apex:column headerValue="Number of Users *" rendered="{!selectedoptionb}"> <apex:inputText value="{!wraprecrd.quantity}" id="quantityid" rendered="{!selectedoptionb}"/> </apex:column> <apex:column headerValue="Potential Subscription Start Date" rendered="{!selectedoptionb}"> <apex:input type="date" value="{!wraprecrd.PotentialSubscriptionStartDate}" id="pssdid" rendered="{!selectedoptionb}"/> <!-- <apex:inputText value="{!wraprecrd.PotentialSubscriptionStartDate}" id="datepicker" rendered="{!selectedoptionb}" onclick="datepicker()" />--> </apex:column> <apex:column headerValue="Term Length(Year)" rendered="{!selectedoptionb}"> <apex:inputText value="{!wraprecrd.TermLength}" id="termlengthid" rendered="{!selectedoptionb}"/> </apex:column> <!-- <apex:column headerValue="Line Description"> <apex:inputText value="{!wraprecrd.lineDescription}" /> </apex:column>--> </apex:pageblocktable> </apex:pageblock> </apex:outputPanel> <div align="right" draggable="false" id="btnone" style="display:none" > <apex:commandButton value="Add Products" action="{!selectLineItem}" reRender="frm" oncomplete="hellofuncone()"/> </div> <!-- <apex:actionFunction name="updateit" action="{!productfetch}" reRender="thePanel1,btn" oncomplete="hellofunc()" > <apex:param name="firstParam12" value="" assignTo="{!selectedoption}" /> </apex:actionFunction> --> </apex:form> </apex:page>
 
Gheorghe SimaGheorghe Sima
I think that you don't understand exactly what i said. I want to create a custom button which allows me to add multiple products on the service and when i click "Add product" it must open a new page where i can select the products i click Select. If you look at the "Add product" from order you will understand what my button must do.
Amit  TrivediAmit Trivedi
public class FirstHomePageController
{
    List<String> productrectype{get;set;}
    public boolean selectedoptionb{get;set;}
    public String selectedoption{get;set;}
   public List<Products_SFDC__c> prod{get;set;}
    public List<ProductWrapper> productWraList{get;set;}
    public List<ProductWrapper> productWraListSelected{get;set;}
    public List<Opportunity_Line_Item_SFDC__c> oppLineItemList{get;set;}
    public String Disc{get;set;}
 
Amit  TrivediAmit Trivedi

  public FirstHomePageController(ApexPages.StandardController controller)
    {
        prod = new List<Products_SFDC__c>();
        Id opportunityparent = ApexPages.currentPage().getParameters().get('oid');
        Opportunity_SFDC__c op =  [select RecordType.Name from Opportunity_SFDC__c where id=:opportunityparent];
        if(op.RecordType.Name == 'Product Subscription')
        selectedoption = 'Product Subscription Pricebook';
        if(op.RecordType.Name == 'Salesforce Implementation')
        selectedoption = 'Service Subscription Pricebook';
     
Gheorghe SimaGheorghe Sima
@Amit Trivedi
Can you explain me what you do in your visualforce page?
Mohit Bansal6Mohit Bansal6
Hi Amit

I think you know how to create a custom button and show it on the related list of product.

Before creating a new custom button, create a new vf page and class and paste below code to it. This is a dummy page which list all the contacts and we can select any of them as per our needs. So you can modify this code to list your products and can select any of them and link to your service record.

Kindly refer the concept of Wrapper Class:
https://developer.salesforce.com/page/Wrapper_Class

Visualforce Page:
<apex:page controller="wrapperClassController">
    <apex:form >
        <apex:pageBlock >
            <apex:pageBlockButtons >
                <apex:commandButton value="Process Selected" action="{!processSelected}" rerender="table"/>
            </apex:pageBlockButtons>
            <!-- In our table we are displaying the cContact records -->
            <apex:pageBlockTable value="{!contacts}" var="c" id="table">
                <apex:column >
                    <!-- This is our selected Boolean property in our wrapper class -->
                    <apex:inputCheckbox value="{!c.selected}"/>
                </apex:column>
                <!-- This is how we access the contact values within our cContact container/wrapper -->
                <apex:column value="{!c.con.Name}" />
                <apex:column value="{!c.con.Email}" />
                <apex:column value="{!c.con.Phone}" />
            </apex:pageBlockTable>
        </apex:pageBlock>
    </apex:form>
</apex:page>

Controller:
 
public class wrapperClassController {

	//Our collection of the class/wrapper objects cContact 
	public List<cContact> contactList {get; set;}

	//This method uses a simple SOQL query to return a List of Contacts
	public List<cContact> getContacts() {
		if(contactList == null) {
			contactList = new List<cContact>();
			for(Contact c: [select Id, Name, Email, Phone from Contact limit 10]) {
				// As each contact is processed we create a new cContact object and add it to the contactList
				contactList.add(new cContact(c));
			}
		}
		return contactList;
	}


	public PageReference processSelected() {

                //We create a new list of Contacts that we be populated only with Contacts if they are selected
		List<Contact> selectedContacts = new List<Contact>();

		//We will cycle through our list of cContacts and will check to see if the selected property is set to true, if it is we add the Contact to the selectedContacts list
		for(cContact cCon: getContacts()) {
			if(cCon.selected == true) {
				selectedContacts.add(cCon.con);
			}
		}

		// Now we have our list of selected contacts and can perform any type of logic we want, sending emails, updating a field on the Contact, etc
		System.debug('These are the selected Contacts...');
		for(Contact con: selectedContacts) {
			system.debug(con);
		}
		contactList=null; // we need this line if we performed a write operation  because getContacts gets a fresh list now
		return null;
	}


	// This is our wrapper/container class. A container class is a class, a data structure, or an abstract data type whose instances are collections of other objects. In this example a wrapper class contains both the standard salesforce object Contact and a Boolean value
	public class cContact {
		public Contact con {get; set;}
		public Boolean selected {get; set;}

		//This is the contructor method. When we create a new cContact object we pass a Contact that is set to the con property. We also set the selected value to false
		public cContact(Contact c) {
			con = c;
			selected = false;
		}
	}
}

You can modify the code as per your needs and object details.

Finally link this page to the custom button.

Regards
Mohit Bansal

In case, you face any issue, drop me message on forum or Skype me @mohit_bansal17, if you need any help.

Please mark this as solution by selecting it as best answer if this solves your problem, So that if anyone has this issue this post can help.
This was selected as the best answer
Vincent van Drunen LittelVincent van Drunen Littel

@Mohit Bansal6

Could you explain to me how to do the exact same thing but instead of contacts i want to get a list of Accounts. 

My intentions might be a bit complicated, but long story short, I need to create a button within a related list of Accounts that pops up this kind of list where you can multi-select and add (in this case) accounts

I have been breaking my head over this for about a month now.. If you could help me on this I would really really appreciate it!!!

Thanks in advance!