How to call a method in controller on picklist change? - salesforce

<apex:selectList size="1" value="{! LimitSize}">
<apex:selectOptions value="{! paginationSizeOptions}" />
</apex:selectList>
This is my pick list.
private String LimitSize = '';
public String getLimitSize() {
return LimitSize;
}
public void setLimitSize(String LimitSize) {
this.LimitSize = LimitSize;
}
public SelectOption[] paginationSizeOptions {
public get;
private set;
}
public SiteController2(){
String[] paginationSize = new String[]{'2','5','10','200','250' };
this.paginationSizeOptions = new SelectOption[]{};
for (String c: paginationSize) {
this.paginationSizeOptions.add(new SelectOption(c,c));
}
LimitSize = paginationSize[0];
}
public checkLimitSize(){
system.debug('Limit Size : '+LimitSize);
}
Now on change of picklist I want to assign LimitSize variable with selected value of picklist and call method checkLimitSize() to check the value. How can I do that?Thanks.

You can use apex:actionFunction component:
add actionFunction component to page
<apex:actionFunction action="{!yourControllerMethod}" name="yourFunction"/>
Add method to controller
public PageReference yourControllerMethod(){
//body of method
checkLimitSize();
return null;
}
add actionFunction call on
<apex:selectList onchange="yourFunction() ...."
For more information read the documentation.

Related

Why can't I iterate through a list of a Wrapper class in Salesforce Visualforce?

I am trying to iterate through a list of records inside a wrapper class and show them on a Visualforce page. The custom object is called Campaign_Products__c, and the wrapper class is meant to show if the product has been selected by the user to add to a "cart".
Apex Controller code (extraneous bits removed):
public with sharing class CONTROLLER_Store {
...
public List<productOption> cpList { get; set; }
public class productOption {
public Campaign_Product__c product;
public Boolean inCart;
public Integer quantity;
}
...
public CONTROLLER_Store(){
...
List<Campaign> cmpList = getCampaignWithProducts(CampaignId,'');
// method above calls a campaign with a related list of Campaign Product records
if(cmpList.size() > 0){
cmp = cmpList[0];
cpList = new List<productOption>();
for(Campaign_Product__c pro : cmp.Campaign_Products__r){
productOption option = new productOption();
option.product = pro;
option.inCart = false;
option.quantity = 0;
cpList.add(option);
}
} else {
cmp = new Campaign();
CampaignId = null;
cpList = new List<productOption>();
}
....
}
Visualforce page (extraneous bits removed)
<apex:page controller="CONTROLLER_Store" >
<apex:repeat value="{! cpList }" var="option">
{!option.product.Product__r.Name}
<apex:inputCheckbox value="{! option.inCart }"/>
</apex:repeat>
</apex:page>
I get this error when trying to save the visualforce page:
Unknown property 'CONTROLLER_Store.productOption.product'
You need to make the properties in your wrapper visible to VF too. Something like
public class productOption {
public Campaign_Product__c product {get; private set};
public Boolean inCart {get; set};
public Integer quantity {get; set};
}
(assuming product should be readonly in VF). You need these access modifiers or full getter/setter methods.

Displaying custom controller data in visualforce page after onchange event

I have a picklist containing names of records of an object, "Test_Script".When I select any option from a picklist("selectlist" & selectoption are used for implementing picklist),at onchange event the other fields related to that record name should be displayed on visualforce page.
VF Page:
<h1>Choose Script:</h1>
<apex:selectlist value="{!selectedValue}" size="1"onchange="{!setValues}">
<apex:selectOptions value="{!scriptoptions}" />
</apex:selectlist>
<br/>
Executioner Name:
<outputfield value="{!valueResult.executioner_name}"/>
<br/>Planner Name:
<outputfield value="{!valueResult.planner_name}"/>
<br/>Reviewer Name:
<outputfield value="{!valueResult.reviewer_name}"/>
Controller:
public class ScriptAttributesController
{
public String setValues { get; set; }
public List<Test_script__c> scriptListWithValues = [select name, id, Executioner__c, Planner__c, Reviewer__c from Test_Script__c];
public static Test_Script__c valueResult=new Test_Script__c();
public String selectedValue {get;set;}
public void ScriptAttributesController()
{
}
public List<SelectOption> getScriptoptions()
{
List<SelectOption> options = new List<SelectOption>();
options.add(new SelectOption('select a value','select a value'));
for(Test_Script__c s: scriptListWithValues )
{
options.add(new SelectOption(s.id,s.name));
}
return options;
}
public void setValues()
{
valueResult=[select name, id, Executioner__c, Planner__c, Reviewer__c, Iteration__c from Test_Script__c where name='selectedValue' limit 1];
}
}
I am not able to see value on screen on change og picklist value
I would say that a getter is missing for your valueResult.
public Test_Script__c valueResult {get; set;}
and in the controller you can init the object.

Salesforce: Attempt to de-reference a null object

I've searched and found several articles about this error, but I'm new to APEX and Visualforce and so I can't figure out how to apply the solutions to what I'm working on. Any help would be appreciated. What I'm trying to do in the code below is create a visualforce page embedded on Opportunity records that displays 2 multi-select picklists, one being dependent on the choice(s) picked in the first.
public class WatermelonOppController {
//added an instance varaible for the standard controller
private ApexPages.StandardController controller {get; set;}
// the actual opportunity
private Opportunity o;
public String[] parentPicklistVal {public get; public set;}
public String[] childMultiPicklistVal {public get; public set;}
public String childSinglePicklistVal {public get; public set;}
// maps to hold your dependencies between picklists
private Map<String, List<String>> parentDepMap;
private Map<String, List<String>> childDepMap;
private String[] parentOpts = new String[] { 'parent option 1', 'parent option 2' };
private String[] childMultiOpts = new String[] { 'child multi 1', 'child multi 2', 'child multi 3' };
//private String[] childSingleOpts = new String[] { 'child single 1', 'child single 2', 'child single 3' };
public WatermelonOppController(ApexPages.StandardController controller) {
//initialize the stanrdard controller
this.controller = controller;
//this.o = (Opportunity)controller.getRecord();
}
public WatermelonOppController() {
// init dependency maps
parentDepMap = new Map<String, List<String>>();
// childDepMap = new Map<String, List<String>>();
// pick which child options to display for which parent value
parentDepMap.put(parentOpts[0], (new String[]{childMultiOpts[0], childMultiOpts[1]}));
parentDepMap.put(parentOpts[1], (new String[]{childMultiOpts[1], childMultiOpts[2]}));
// pick which single-select options to display for which child value
//childDepMap.put(childMultiOpts[0], (new String[]{childSingleOpts[0], childSingleOpts[2]}));
//childDepMap.put(childMultiOpts[1], (new String[]{childSingleOpts[1], childSingleOpts[2]}));
//childDepMap.put(childMultiOpts[2], childSingleOpts); // or if you want to show them all?
}
public List<SelectOption> getParentPicklistOptions() {
List<SelectOption> selectOpts = new List<SelectOption>();
for ( String s : parentOpts )
selectOpts.add(new SelectOption(s, s));
return selectOpts;
}
public List<SelectOption> getChildMultiPicklistOptions() {
List<SelectOption> selectOpts = new List<SelectOption>();
if ( parentPicklistVal != null && parentPicklistVal.size() > 0 ) {
// build a set of values to avoid dupes, since there may be overlapping dependencies
Set<String> possibleOpts = new Set<String>();
for ( String val : parentPicklistVal )
possibleOpts.addAll(parentDepMap.get(val));
for ( String s : possibleOpts )
selectOpts.add(new SelectOption(s, s));
}
return selectOpts;
}
/*
public List<SelectOption> getChildSinglePicklistOptions() {
List<SelectOption> selectOpts = new List<SelectOption>();
if ( childMultiPicklistVal != null && childMultiPicklistVal.size() > 0 ) {
// build a set of values to avoid dupes, since there may be overlapping dependencies
Set<String> possibleOpts = new Set<String>();
for ( String val : childMultiPicklistVal )
possibleOpts.addAll(childDepMap.get(val));
for ( String s : possibleOpts )
selectOpts.add(new SelectOption(s, s));
}
return selectOpts;
}
*/
public PageReference actionUpdatePicklistVals() {
// this doesn't really need to do anything, since the picklists should be updated when their getters call after returning
return null;
}
}
And the Visualforce page:
<apex:page standardController="Opportunity" extensions="WatermelonOppController">
<apex:form >
<apex:outputPanel id="panel1">
<apex:selectList value="{!parentPicklistVal}" multiselect="true" size="3">
<apex:selectOptions value="{!parentPicklistOptions}" />
<apex:actionSupport event="onchange" action="{!actionUpdatePicklistVals}" rerender="panel1" />
</apex:selectList>
<apex:selectList value="{!childMultiPicklistVal}" multiselect="true" size="3">
<apex:selectOptions value="{!childMultiPicklistOptions}" />
<apex:actionSupport event="onchange" action="{!actionUpdatePicklistVals}" rerender="panel1" />
</apex:selectList>
</apex:outputPanel>
</apex:form>
You should move all your logic from default contructor to the parameterized constructor. Since the class is an extension, it's parameterized contructor with Standard Controller is being called.

Salesforce - cant pass visualforce inputtext values to apex class

I have the following Visualforce page, and apex class as controller.
I would like to pass valus in the input text boxes contain th ids inputText1 and InputText2 to the same variable in the following apex class.
Everytime, the inputText1 and inputText2 in the apex class is null, and I don't know why!
Iv'e bin sitting on it all day long, and I couldn't figgure out why it happens!
Please help me with that, because I'm feeling hopeless with that.
<apex:page controller="LoginPages" rendered="true" showHeader="false" sidebar="false" standardStylesheets="true">
<apex:Pagemessages id="msg"/>
<apex:pageMessages ></apex:pageMessages>
<apex:pageBlock >
<apex:form >
<p><b>Login Page</b><br /></p>
<apex:panelGrid columns="2" style="margin-top:1em;">
<p><b>UserName</b><br />
<apex:inputtext required="true" id="inputText1" value="{!inputText1}"/>
</p>
<p><b>Password</b><br />
<apex:inputtext id="inputText2" value="{!inputText2}"/>
</p>
<apex:commandButton action="{!loginUser}" value="login" id="login" immediate="true"/>
</apex:panelGrid>
</apex:form>
</apex:pageBlock>
</apex:page>
public class LoginPages{
public String inputText1;
public String inputText2;
public String getInputText1(){
return inputText1;
}
public void setInputText1(String str1){
inputText1 = str1;
}
public String getInputText2(){
return inputText2;
}
public void setInputText2(String str2){
inputText1 = str2;
}
public PageReference registerUser() {
PageReference newPage = new PageReference('/apex/newPage');
newPage.setRedirect(true);
return newPage;
}
public void loginUser() {
ApexPages.Message mymsg = new ApexPages.Message(ApexPAges.Severity.INFO, 'sdsdf' + inputText1);
apexpages.addMessage(mymsg);
// PageReference newPage = new PageReference('/apex/login');
System.debug('sdfsdf' + inputText1);
List<User__c> users = [Select Name, Password__c from User__c Where Name = :inputText1];
if (users.size() > 0){
for (User__c user : users){
if (user.Password__c == inputText2){
//newPage.setAnchor('/apex/catalog');
//newPage.setRedirect(true);
}
}
}
//return newPage;
}
}
Remove immediate="true". "Immediate" results in no data being passed from the form to the server.
Also - you could write your variables bit simpler and then you won't need the explicit getXYZ/setXYZ methods:
public String inputText1 {get;set;}

How to get in a Visualforce page controller a value from a custom component controller?

I'm trying do develop a visualforce custom component which is an entity chooser. This custom component displays a UI which helps browsing some records. It's possible to select one record, and I'd like to get it from outside the component or its controller.
I've looked at the standard salesforce binding with assignTo bug it's not bidirectional...
Hope someone can help me..
Thanks
Are you passing an object into the component? Objects are passed by reference, so if your component has an attribute that takes an object and does something to it, your outer page controller will be able to access the changed values.
If you were to pass in a shell object, ie. if your UI is allowing a user to select an Account.
Class SelectedAccount
{
public Account theAccount {get;set;}
}
Component:
<apex:component controller="ComponentController">
<apex:attribute type="SelectedAccount" name="userSelectedAccount" description="Selected Account" assignTo="{!selectedAccount}"
</apex:component>
Component Controller:
public class ComponentController
{
public selectedAccount;
public void ComponentController(){}
public PageReference selectAccountFromUI(Account selected)
{
selectedAccount.theAccount = selected;
return null;
}
}
Page Using the Component:
<c:MyAccountComponent userSelectedAccount="{!instanceOfSelectedAccount}"/>
This would allow you to assign the user selected account into the instance of wrapper object which is owned by the outer controller. You can then reference:
instanceOfSelectedAccount.theAccount
from your main Visualforce Pages controller.
1 - Declare a static variable in the outside class (can be the VF page controller)
Something like :
public static apexType myRecordOutside;
2 -When you Make your choice from records in the method within the custom component controller
Do something like this :
OutsideClass.myRecordOutside = chosenRecord; //notice that when its static you can access it without instantiating the outside class.
3- then, declare in your Visual force
<c:myCustomComponent userSelectedAccount = {!myRecordOutside}></c:myCustomComponent>
this will get myRecordOutside not from the component's controller class, but from the outside class
If you have any question about a part of my answer let me know :)
/* This is an example of getting non static variable value
from visualforce component controller variable to visualforce page controller variable */
VF page: DisplayCountryPage
<apex:page>
<apex:commandButton value="display country list" action="{!displaycountryname}" />
<apex:repeat value="{!displaycountrylistvalue}" var="item">
<div>
{!item}
</div>
</apex:repeat>
<c:testvfcmp vfpageclasscontroller="{!thisPageInstance}"/>
</apex:page>
=====================
DisplayCountryPage VF Page controller: vfpageclass
public class vfpageclass{
public List<String> displaycountrylistvalue{get;set;}
public vfcomponentclass vfcmpobj{get;set;}
public void methodtosetvfcomponentclass(vfcomponentclass vfcmpobj2){
vfcmpobj = vfcmpobj2;
}
public void displaycountryname(){
displaycountrylistvalue = new List<String>();
displaycountrylistvalue = vfcmpobj.listOfCountry;
}
public vfpageclass thisPageInstance{
get{
return this;
}
set;
}
}
======================
vf component: testvfcmp
create an attribute like below:
<apex:component controller="CSTSearchPanelController">
<apex:attribute name="vfpageclasscontroller"
type="vfpageclass"
assignTo="{!vfpageobj}"
description="The controller for the page." />
<apex:commandButton value="set country list" action="{!setCountrylist}" />
</apex:component>
=====================
<testvfcmp> vf component controller: vfcomponentclass
public class vfcomponentclass{
public List<String> listOfCountry = new List<String>();
public vfpageclass vfpageobj{
get;
set{
vfpageobj = value;
vfpageobj.methodtosetvfcomponentclass(this);
}
}
public void setCountrylist(){
listOfCountry.add('India');
listOfCountry.add('USA');
}
}
/* This is an example of getting static variable value
from visualforce component controller variable to visualforce page controller variable */
VF page: DisplayCountryPage
<apex:page>
<apex:commandButton value="display country list" action="{!displaycountryname}" />
<apex:repeat value="{!displaycountrylistvalue}" var="item">
<div>
{!item}
</div>
</apex:repeat>
<c:testvfcmp vfpageclasscontroller="{!thisPageInstance}"/>
</apex:page>
=====================
DisplayCountryPage VF Page controller: vfpageclass
public class vfpageclass{
public List<String> displaycountrylistvalue{get;set;}
public void methodtosetvfcomponentclass(vfcomponentclass vfcmpobj2){
if(vfcmpobj2.getStaticCountryList() !=null){
displaycountrylistvalue = new List<String>();
displaycountrylistvalue = vfcmpobj2.getStaticCountryList();
}
/* USE THIS displaycountrylistvalue VARIABLE THROUGHOUT THE CLASS ONCE YOU SET BY HITTING BUTTON <set country list>.
DO NOT USE vfcmpobj2.getStaticCountryList() IN OTHER METHODS TO GET THE VALUE, IF DO, IT WILL RETURN NULL*/
}
public void displaycountryname(){
}
public vfpageclass thisPageInstance{
get{
return this;
}
set;
}
}
======================
vf component: testvfcmp
create an attribute like below:
<apex:component controller="CSTSearchPanelController">
<apex:attribute name="vfpageclasscontroller"
type="vfpageclass"
assignTo="{!vfpageobj}"
description="The controller for the page." />
<apex:commandButton value="set country list" action="{!setCountrylist}" />
</apex:component>
=====================
<testvfcmp> vf component controller: vfcomponentclass
public class vfcomponentclass{
public static List<String> listOfCountry = new List<String>();
public vfpageclass vfpageobj{
get;
set{
vfpageobj = value;
vfpageobj.methodtosetvfcomponentclass(this);
}
}
public static void setCountrylist(){
listOfCountry.add('India');
listOfCountry.add('USA');
}
public List<String> getStaticCountryList(){
return listOfCountry;
}
}

Resources