Detect unselect date of datepicker with selectionMode multiple (Primefaces) - primefaces

I am implementing the possibility to select several dates in a calendar and thus create recurring items on different dates.
For this I show below the calendar a table with the selected dates, and this is why I need an event to detect when the selection of a date is removed (to update the lower table).
I have tried with the onchange event but this is for inputs changes and it doesn't work because I need remove the selection from the calendar, and the onclick or dateSelect event doesn't detect it either.
<p:datePicker id="multiselect" locale="es"
selectionMode="multiple" value="#{altaSuceso.multi}" readonlyInput="true" mode="inline" mindate="#{listado.getFechaAct()}"
disabledDates="#{altaSuceso.invalidDates}">
<p:ajax event="dateSelect" listener="#{altaSuceso.onDateSelect}" update="formEdicion:fechasSuc"/>
</p:datePicker>
<p:dataTable id="fechasSuc" var="suc" value="#{altaSuceso.sucRecurrente}" >
<p:column headerText="Fecha de Inicio">
<h:outputText value="#{altaSuceso.getFechaFormateada(suc.fechaIniSuc)}" />
</p:column>
<p:column headerText="Fecha de Fin">
<h:outputText value="#{altaSuceso.getFechaFormateada(suc.fechaFinSuc)}" />
</p:column>
<p:column id="idInfoVialidad" headerText=""
styleClass="infoVialidad" style="width: 50px !important;"
resizable="false">
<p:commandButton id="moreInfoVialidad" icon="fa fa-fw fa-info" styleClass="btnGeneral btnGris"
type="button"
onclick="mostrarDialogoInfoVialidadAlta(event,'#{altaSuceso.mostrarVialidadesToolTip(suc.vialidades)}','tabla');"
onerror="onError();"/>
</p:column>
</p:dataTable>
AltaSuceso.java
public void onDateSelect(SelectEvent event) {
#SuppressWarnings("unchecked")
ArrayList<Date> f = (ArrayList<Date>) event.getObject();
calcularFechasNuevasVialidades(f.get(f.size()-1));
}
public void calcularFechasNuevasVialidades (Date fSelec) {
List<Date> listOfDatesIni = new ArrayList<Date>();
List<Date> listOfDatesFin = new ArrayList<Date>();
ArrayList<GrupoVialidades> listaNewVialidades = new ArrayList<>();
if(listaVialidades != null && listaVialidades.size() > 0)
for(GrupoVialidades v : listaVialidades) {
GrupoVialidades vialidadEdicion = new GrupoVialidades(v.isObligada(), v.isNueva(), (v.isOriginalmenteActiva()? Valores.ACT: Valores.INA));
BeanUtils.copyProperties(v, vialidadEdicion);
// El copyProperties copia no crea objetos nuevos para el ArrayList<VialidadGrupo>
// por lo que se llama a un método que genera los objetos nuevos
vialidadEdicion.setVialidades(new ArrayList<>());
vialidadEdicion.copyVialidades(v.getVialidades());
Date f = getFechaCalculada(fSelec, v.getFechaIni());
vialidadEdicion.setFechaIni(f);
listOfDatesIni.add(f);
if(v.getFechaFin() != null) {
Date f2 = getFechaCalculada(fSelec, v.getFechaFin());
vialidadEdicion.setFechaFin(f2);
if(f2 != null) listOfDatesFin.add(f2);
}
listaNewVialidades.add(vialidadEdicion);
}
Date fIniSuc = null;
Date fFinSuc = null;
if(listOfDatesIni != null && listOfDatesIni.size() > 0)
fIniSuc = Collections.min(listOfDatesIni);
if(listOfDatesFin != null && listOfDatesFin.size() > 0)
fFinSuc = Collections.max(listOfDatesFin);
SucesoRecurrente suc = new SucesoRecurrente();
suc.setFechaIniSuc(fIniSuc);
suc.setFechaFinSuc(fFinSuc);
suc.setVialidades(listaNewVialidades);
sucRecurrente.add(suc);
log.debug("calcularFechasNuevasVialidades "+sucRecurrente.size() + " "+ sucRecurrenteOriginal.size());
multi.add(fIniSuc);
}

Related

Chart label overlapping in primefaces

i am facing problem of label overlapping in primeFaces.
i have customers records more than 50k so i have to show it in chart all things are working perfect but problem is that, Active customers records are too many and inactive also pending customers are less than 50 so it is overlapping the label of Pending profile.
Here is Bean:
public void getALLCustomersProfileStatus() {
MainDashboardModel db = new MainDashboardModel();
db.getALLCustomersProfileStatus();
pieModel = new PieChartModel();
dashboardObj = db.getALLCustomersProfileStatus();
int totalActive = 0;
int totalInactive = 0;
int totalPending = 0;
if (dashboardObj != null) {
totalActive = dashboardObj.getTotalActiveCustomerProfileCount();
totalInactive = dashboardObj.getTotalInactiveCustomerProfileCount();
totalPending = dashboardObj.getTotalPendingCustomerProfileCount();
totalCustomerProfiles = (totalActive + totalInactive + totalPending);
}
pieModel.setFill(true);
pieModel.setShowDataLabels(true);
pieModel.setDiameter(150);
pieModel.setShadow(false);
pieModel.set("Active Profile", totalActive);
pieModel.set("Inactive Profile", totalInactive);
pieModel.set("Pending",( totalPending ));
pieModel.setSeriesColors("2CC5A2,F05129,F28E8E");//#e69900
pieModel.setLegendPosition("w");
}
Here is xhtml:
<ui:define name="content">
<div class="ui-g dashboard">
<div class="ui-g-12 ui-md-12">
<div class="card overview">
<div class="overview-content clearfix">
<span class="overview-title">Total Customer Profiles</span>
<span class="overview-detail">#{mainDashboardBean.totalCustomerProfiles}</span>
</div>
</div>
</div>
<div class="ui-g-12 ui-md-12">
<p:panelGrid layout="grid" columns="2">
<p:chart type="pie" model="#{mainDashboardBean.pieModel}" style="width: 400px; height: 300px"></p:chart>
</p:panelGrid>
</div>
</div>
</ui:define>
Again i am explaining that data is fetching perfect but only overlapping issue facing.
Pending profiles are only 26.
Here is Image
Thanks.

ASP.NET SQLDataSource SelectParameters default value not working

I wrote a simple ASP.NET form to manage a particular query on my (MySQL) db. Such query is handled by this stored procedure:
CREATE DEFINER=`root`#`localhost` PROCEDURE `noleggio_conducenti`(IN _id_convenzionato INT(10))
BEGIN
IF _id_convenzionato IS NOT NULL THEN
SELECT * FROM
(
SELECT
*
FROM
noleggi AS H
WHERE
id_convenzionato = _id_convenzionato
UNION
SELECT
*
FROM
noleggi AS H
WHERE
id_convenzionato IN (SELECT
id_recipiente
FROM
sosautomotive.transizioni_point
WHERE
id_cedente = _id_convenzionato )
) H
WHERE (H.uscita IS NOT NULL) AND (H.rientro IS NOT NULL);
ELSE
SELECT
*
FROM
noleggi
WHERE (uscita IS NOT NULL) AND (rientro IS NOT NULL);
END IF;
END
As you can see the only parameter can be NULL ... my hope was to use this stored procedure to provide data to the following SQLDataSource object:
<asp:SqlDataSource
ID="_sdsConducenti"
runat="server"
ConnectionString="<%$ ConnectionStrings:sos_db %>"
ProviderName="<%$ ConnectionStrings:sos_db.ProviderName %>"
SelectCommandType="StoredProcedure"
SelectCommand="noleggio_conducenti">
<SelectParameters>
<asp:Parameter Name="_id_convenzionato" Type="Int32" DefaultValue="" ConvertEmptyStringToNull="true" />
</SelectParameters>
</asp:SqlDataSource>
That provides data to a GridView :
<asp:GridView
ID="_gvConducenti"
runat="server"
DataSourceID="_sdsConducenti"
OnSorting="_gvConducenti_Sorting"
OnPageIndexChanging="_gvConducenti_PageIndexChanging"
OnRowDataBound="_gvConducenti_RowDataBound"
AutoGenerateColumns="false"
EmptyDataText="Nessun conducente presente."
BorderStyle="None"
CellSpacing="0"
CellPadding="0"
ShowHeader="true"
ShowFooter="true"
AllowSorting="true"
AllowPaging="true"
PageSize="10"
GridLines="Horizontal"
SelectedIndex="0"
Style="width: 100%;"
HorizontalAlign="Center">
<SelectedRowStyle CssClass="SelRow" />
<HeaderStyle CssClass="GridHeader" />
<AlternatingRowStyle BackColor="#F7F5E9" CssClass="AltRow" />
<PagerStyle HorizontalAlign="Center" />
<PagerSettings
Visible="true"
Mode="NumericFirstLast"
PageButtonCount="3"
Position="Bottom"
NextPageText="Pagina successiva"
PreviousPageText="Pagina precedente"
FirstPageText="Prima pagina"
LastPageText="Ultima pagina" />
<Columns>
<asp:TemplateField Visible="false">
<HeaderTemplate> </HeaderTemplate>
<ItemTemplate>
<%#Eval("idnoleggio")%>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Numero" SortExpression="numero">
<ItemTemplate>
<asp:LinkButton
runat="server"
CommandArgument='<%# Eval("idnoleggio")%>'
CommandName="Link"
OnCommand="Link_Command">
<%#Eval("numero_completo")%>
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="Conducente" DataField="conducente" />
<asp:BoundField HeaderText="Via" DataField="conducente_via" />
<asp:BoundField HeaderText="N° Civico" DataField="conducente_num_civico" />
<asp:BoundField HeaderText="CAP" DataField="conducente_cap" />
<asp:BoundField HeaderText="Città" DataField="conducente_residente_in" />
<asp:BoundField HeaderText="Prov." DataField="conducente_residente_in_provincia" />
<asp:BoundField HeaderText="Convenzionato" DataField="convenzionato" />
<asp:BoundField HeaderText="Uscita" DataField="uscita" DataFormatString="{0:dd/MM/yyyy HH:mm}" />
<asp:BoundField HeaderText="Rientro" DataField="rientro" DataFormatString="{0:dd/MM/yyyy HH:mm}" />
<asp:BoundField HeaderText="Tipologia noleggio" DataField="modalita_noleggio" />
</Columns>
</asp:GridView>
of course this form has other fields used to filter the query and those are handled by this couple of functions:
private void Ricerca()
{
if (!String.IsNullOrWhiteSpace(_txtConvenzionato.Text.Trim()))
{
int _nIdConvenzionato = CUtilita.RitornaIdConvenzionato(_txtConvenzionato.Text);
if (_nIdConvenzionato != -1)
_sdsConducenti.SelectParameters["_id_convenzionato"].DefaultValue = _nIdConvenzionato.ToString();
else
_sdsConducenti.SelectParameters["_id_convenzionato"].DefaultValue = null;
}
_sdsConducenti.FilterExpression = Filter();
}
private string Filter()
{
StringBuilder _sbFilter = new StringBuilder();
try
{
#region Data fine noleggio
if (!string.IsNullOrWhiteSpace(_txtDallaDataFineNoleggio.Text.Trim()) &&
!string.IsNullOrWhiteSpace(_txtAllaDataFineNoleggio.Text.Trim()))
{
DateTime _dtDallaDataFineNoleggio = DateTime.Parse(_txtDallaDataFineNoleggio.Text.Trim());
DateTime _dtAllaDataFineNoleggio = DateTime.Parse(_txtAllaDataFineNoleggio.Text.Trim());
_sbFilter.AppendFormat("((uscita>='{0:yyyy-MM-dd}') AND (uscita<='{1:yyyy-MM-dd}'))", _dtDallaDataFineNoleggio, _dtAllaDataFineNoleggio);
}
else if (string.IsNullOrWhiteSpace(_txtDallaDataFineNoleggio.Text.Trim()) &&
!string.IsNullOrWhiteSpace(_txtAllaDataFineNoleggio.Text.Trim()))
{
DateTime _dtAllaDataFineNoleggio = DateTime.Parse(_txtAllaDataFineNoleggio.Text.Trim());
_sbFilter.AppendFormat("(uscita<='{0:yyyy-MM-dd}')", _dtAllaDataFineNoleggio);
}
else if (!string.IsNullOrWhiteSpace(_txtDallaDataFineNoleggio.Text.Trim()) &&
string.IsNullOrWhiteSpace(_txtAllaDataFineNoleggio.Text.Trim()))
{
DateTime _dtDallaDataFineNoleggio = DateTime.Parse(_txtDallaDataFineNoleggio.Text.Trim());
_sbFilter.AppendFormat("(uscita>='{0:yyyy-MM-dd}')", _dtDallaDataFineNoleggio);
}
#endregion
}
catch (FormatException ex)
{
_lblStatus.Text = ex.Message;
_lblStatus.ForeColor = System.Drawing.Color.Red;
}
try
{
#region Data esportazione
if (!string.IsNullOrWhiteSpace(_txtDallaDataEstrazione.Text.Trim()) &&
!string.IsNullOrWhiteSpace(_txtAllaDataEstrazione.Text.Trim()))
{
DateTime _dtDallaDataEstrazione = DateTime.Parse(_txtDallaDataEstrazione.Text.Trim());
DateTime _dtAllaDataEstrazione = DateTime.Parse(_txtAllaDataEstrazione.Text.Trim());
_sbFilter.AppendFormat("((data_esportazione_conducenti>='{0:yyyy-MM-dd}') AND (data_esportazione_conducenti<='{1:yyyy-MM-dd}'))", _dtDallaDataEstrazione, _dtAllaDataEstrazione);
}
else if (string.IsNullOrWhiteSpace(_txtDallaDataEstrazione.Text.Trim()) &&
!string.IsNullOrWhiteSpace(_txtAllaDataEstrazione.Text.Trim()))
{
DateTime _dtAllaDataEstrazione = DateTime.Parse(_txtAllaDataEstrazione.Text.Trim());
_sbFilter.AppendFormat("(data_esportazione_conducenti<='{0:yyyy-MM-dd}')", _dtAllaDataEstrazione);
}
else if (!string.IsNullOrWhiteSpace(_txtDallaDataEstrazione.Text.Trim()) &&
string.IsNullOrWhiteSpace(_txtAllaDataEstrazione.Text.Trim()))
{
DateTime _dtDallaDataEstrazione = DateTime.Parse(_txtDallaDataEstrazione.Text.Trim());
_sbFilter.AppendFormat("(data_esportazione_conducenti>='{0:yyyy-MM-dd}')", _dtDallaDataEstrazione);
}
#endregion
}
catch (FormatException ex)
{
_lblStatus.Text = ex.Message;
_lblStatus.ForeColor = System.Drawing.Color.Red;
}
#region Tipo Noleggio
if (!string.IsNullOrWhiteSpace(_ddlTipoNoleggio.SelectedValue) && !_ddlTipoNoleggio.SelectedValue.Equals("TUTTI"))
{
if (_sbFilter.Length > 0)
_sbFilter.Append(" AND");
_sbFilter.Append("(modalita_noleggio = '" + _ddlTipoNoleggio.SelectedValue + "')");
}
#endregion
if (_sbFilter.Length == 0)
return null;
return _sbFilter.ToString();
}
I tested the stored procedure trough MySQL Workbench and I'm sure it works (both with a valid parameter and with NULL).
BUT when I try to use it within the form it works ONLY if the parameter value is provided and when then value is set to NULL (i.e. _sdsConducenti.SelectParameters["_id_convenzionato"].DefaultValue = null) the query did not provide any data (while it should retrieve a large number of records).
Where did I fail? How can I check if the NULL value is correctly set as the parameter value before calling the stored procedure?
Full code available here.
Try specifying below property in SQLDataSource definition -
CancelSelectOnNullParameter="false"
And it is described as
true if a data retrieval operation is canceled when a parameter
contained in the SelectParameters collection evaluated to null;
otherwise, false. The default is true
The similar problem is explained here -
Set SqlDataSource parameter to null
For more information refer here-

How to pass data from one Managed Bean to another? [duplicate]

This question already has answers here:
Creating master-detail pages for entities, how to link them and which bean scope to choose
(2 answers)
Closed 4 years ago.
I am developing a website using JSF 2.2 and Primefaces 6.1 where I have, initially, 2 pages: A "list" page, where I can show the data to the user, and a "create" page, where I can create new data or edit existing ones.
NOTE: "Cargo" means occupation.
list.xhtml:
...
<h:form>
<p:commandButton value="Cadastrar" styleClass="ui-button-sucesso" action="create.xhtml?faces-redirect=true"/>
</h:form>
...
<h:form>
<p:dataTable value="#{cargoListMB.listaCargo}" var="cargo" rowKey="#{cargo.codigo}" emptyMessage="Nenhum cargo encontrado" filteredValue="#{cargoListMB.listaCargoFiltro}">
<f:facet name="header">Tabela de Cargos</f:facet>
<p:column headerText="Código" sortBy="#{cargo.codigo}" filterBy="#{cargo.codigo}" filterPosition="top">
<h:outputText value="#{cargo.codigo}"/>
</p:column>
<p:column headerText="Nome" sortBy="#{cargo.nome}" filterBy="#{cargo.nome}" filterPosition="top" filterMatchMode="contains">
<h:outputText value="#{cargo.nome}"/>
</p:column>
<p:column headerText="Funcionários" sortBy="#{cargo.funcionariosNesteCargo}"filterBy="#{cargo.funcionariosNesteCargo}" filterPosition="top">
<h:outputText value="#{cargo.funcionariosNesteCargo}"/>
</p:column>
<p:column headerText="Editar">
<p:commandButton icon="fa fa-pencil" title="Editar" styleClass="ui-button-icone-apenas" action="create.xhtml?faces-redirect=true">
<f:param name="objcargo" value="#{cargo.codigo}"/>
</p:commandButton>
</p:column>
</p:dataTable>
</h:form>
CargoListMB.java:
#ManagedBean(name = "cargoListMB")
#ViewScoped
public class CargoListMB implements Serializable {
private List<Cargo> listaCargo;
private List<Cargo> listaCargoFiltro;
public List<Cargo> getListaCargo() {
if (listaCargo == null) {
listaCargo = CargoDAO.listarTodos(); //load data from database
}
return listaCargo;
}
public void setListaCargo(List<Cargo> listaCargo) {
this.listaCargo = listaCargo;
}
...
}
create.xhtml:
<h:form>
<f:metadata>
<f:viewParam name="objcargo" value="#{cargoCreateMB.cargo}" converter="cargoConverter"/>
<f:viewAction action="#{cargoCreateMB.inicializar()}"/>
</f:metadata>
<div class="ui-grid ui-grid-responsive">
<div class="ui-grid-row">
<div class="ui-grid-col-6">
<h1 class="if-page-title"><h:outputText value="#{cargoCreateMB.cargo.codigo == 0? 'Cadastro de Cargos' : 'Edição de cargo'}"/></h1>
</div>
<div class="ui-grid-col-6"></div>
</div>
<br/>
<div class="ui-grid-row">
<div class="ui-grid-col-12">
<div class="ui-grid-row">
<div class="ui-grid-col-1">
<p:outputLabel for="nome" value="Nome:"/>
</div>
<div class="ui-grid-col-3">
<p:inputText id="nome" placeholder="nome" value="#{cargoCreateMB.cargo.nome}" required="true""/>
</div>
<div class="ui-grid-col-8">
<p:message for="nome"/>
</div>
</div>
<br/>
<div class="ui-grid-row">
<div class="ui-grid-col-3">
<p:commandButton value="Salvar" actionListener="#{cargoCreateMB.salvar}" update="form" styleClass="ui-button-salvar"/>
</div>
<div class="ui-grid-col-9"></div>
</div>
</div>
</div>
</div>
</h:form>
CargoCreateMB.java
#ManagedBean(name = "cargoCreateMB")
#ViewScoped
public class CargoCreateMB implements Serializable {
private Cargo cargo;
public void salvar() {
try {
ControleCargo.insereCargo(cargo); //saves the 'occupation' on the database
MensagensUtil.mensagemInfo("Atenção", "Cargo inserido com sucesso");
} catch (RuntimeException e) {
MensagensUtil.mensagemInfo("Erro", "Erro ao inserir cargo");
System.out.println("Erro: " + e);
}
}
public void inicializar() {
//QUESTION!! : Due to a JSF page's life cycle, could I put this code on the constructor??
if (this.cargo == null) {
this.limpar();
}
}
private void limpar() {
cargo = new Cargo();
}
public Cargo getCargo() {
return cargo;
}
public void setCargo(Cargo cargo) {
this.cargo = cargo;
}
}
As you can see, I am trying to pass the selected 'occupation' from page list.xhtml to crate.xhtml using <f:param> and <f:viewParam> tags. When I click on button 'Cadastrar' (means 'register'), everything works fine (the "cargo" object is initially null, as expected), but when I click on the edit button, the "cargo.codigo" (occupation's ID) value, sent by the <f:param> tag, does not "arrive" to the "cargo" object. The converter ('cargoConverter') should be working fine, BUT, when I checked the String value that the method getAsObject was receiving, it was ALWAYS "0", no matter which occupation I choose on my list.
I also tried to send the "raw" data: Instead of using a converter, I sent the "cargo.codigo" value directly to a String field, but it was ALWAYS null.
Could someone help me discover what was my mistake? Also, if it is possible, is there another way to send data to other Managed Beans? Thanks in advance.
Edit: Based on Kukeltje's comments, I formatted my code (which can be seen above) and removed all the nested <h:form> elements BUT the problem still persists. Therefore, the answers on question How to use <h:form> in JSF page? didn't help at all and this question is not a duplicate.
Based on Kukeltje's comments and tips and the answers on this question, I managed to find my mistake: my <f:metadata> was indeed inside a <h:form>
tag. I removed it from there and it worked perfectly.

JSP Data table Limit number of rows on each div

I'm doing a page where i display some labels and input text field so the user can introduce some data and send it back to the server. But sometimes the server send back more than 50 rows of information. In this case the user need to scoll multiple times in order to see all the fields. I want to create 2/3 divs and each contains maybe ~20 fields so that all fields can be displayed without scrolling. Any idea?
Here is my code
<div class="container">
<div class="row">
<f:view>
<h:form>
<h:dataTable value="#{Message.bits}" var="bit">
<h:column>
<div class="col-lg-4">
<h:outputText value="#{bit.id} #{bit.name}" />
<div class="input-group">
<h:inputText styleClass="form-control" size="100"
maxlength="100" value="#{bit.value}" />
</div>
</p>
</div>
</h:column>
</h:dataTable>
</h:form>
</f:view>
</div>
</div>
Class Message -> A container of bits. It is a bean manager
#ManagedBean
#ViewScoped
public class Message implements Serializable {
/**
*
*/
private static final long serialVersionUID = 2712306195992874273L;
private List<Bit> bits = null;
public List<Bit> getBits() {
return bits;
}
//Do more things
Bit class
public class Bit implements Serializable {
/**
*
*/
private static final long serialVersionUID = -6341896264030346040L;
private String name = null;
private String value = null;
private int id = 0;
//Business logic
I can use html, css, any js framework, jsp,java.
Thanks for your time.
If I got your question right, you want to display your data like this:
1 4 7
2 5 8
3 6 9
Instead of this:
1
2
3
4
5
..
I don't know if this is the best solution but it works for me.
You can try the code below.
<div class="row">
<ui:repeat var="bit" value="#{message.bits}" varStatus="bitstatus">
<h:outputText escape="false" value="<div class='col-lg-4'>" rendered="#{(bitstatus.index + 1) % 20 eq 1}" />
<h:outputText value="#{bit.id} #{bit.name}" />
<div class="input-group">
<h:inputText styleClass="form-control" size="100" maxlength="100" value="#{bit.value}" />
</div>
<h:outputText escape="false" value="</div>" rendered="#{(productstatus.index + 1) % 5 eq 0}" />
</ui:repeat>
</div>

Salesforce Visual force pages

My object is Consumer:
Here is a Consumer object has a following fields and want to create a record. But the null pointer exception is reported.
Visualforce page:
<apex:page controller="signup1" >
<apex:form >
<h1>User SignUp</h1>
<apex:panelGrid columns="2" style="margin-top:2em;">
<p><b>Name :</b><br />
<apex:inputField id="name" value="{!con.Name}"/>
</p>
<p><b>Address :</b><br />
<apex:inputField id="address" value="{!con.address__c}"/>
</p>
<p><b>Email Id :</b><br />
<apex:inputField required="true" id="emailid" value="{!con.email_id__c}"/>
</p>
<p><b>Password :</b><br />
<apex:inputSecret id="password" value="{!con.password__c}"/>
</p>
<p><b>Confirm Password :</b><br />
<apex:inputSecret id="confirmpassword" value="{!con.Confirm_Password__c}"/>
</p>
<p><b>Security Question :</b><br />
<apex:inputField required="true" id="securityquestion" value="{!con.Security_Question__c}"/>
</p>
<p><b>Answer :</b><br />
<apex:inputField required="true" id="answer" value="{!con.Answer__c}" />
</p>
<p><b>Ph No :</b><br />
<apex:inputField required="true" id="phno" value="{!con.phone__c}"/>
</p>
<p><b>Pan Card No :</b><br />
<apex:inputField required="true" id="pancardno" value="{!con.Pan_Card_No__c}"/>
</p>
<p> <apex:commandButton action="{!registerUser}" value="SignUp" id="SignUp"/></p>
</apex:panelGrid>
</apex:form>
</apex:page>
controller :
public class signup1
{
Consumer__c con = new Consumer__c();
public void signup1()
{
con = [SELECT Name, address__c, email_id__c, password__c, Confirm_Password__c, Security_Question__c, Answer__c, phone__c from Consumer__c where Name =: ApexPages.currentPage().getParameters().get('Name')];
}
public Consumer__c getcon()
{
return con;
}
public PageReference registerUser()
{
try
{
insert Con;
}
catch(System.DMLException e)
{
ApexPages.addMessages(e);
return null;
}
PageReference pageRef = new PageReference(ApexPages.currentPage().getUrl());
pageRef.setRedirect(true);
return pageRef;
}
}
I cannot insert data into the Consumer object due to the null exception.
This coding the entirely wrong.
1. What is the purpose of the fetching the fields Name, address__c, email_id__c, password__c, Confirm_Password__c, Security_Question__c, Answer__c and phone__c from customer object, as those input fields only.
2. why don't you have Standard Controller on Customer object.
3. If you are fetching values based on name, you need to put search button next to name field and fetch values.
regards,
PK
Consumer is not accessible in your Visual Force page as there is no getter or setter method for it.
public class signup1
{
public Consumer__c con {get; set;}
public signup1()
{
try
{
// Make sure 'ApexPages.currentPage().getParameters().get('Name')' is indeed not null.
con = [SELECT Name, address__c, email_id__c, password__c, Confirm_Password__c, Security_Question__c, Answer__c, phone__c from Consumer__c where Name =: ApexPages.currentPage().getParameters().get('Name')];
}
catch(Exception ex)
{
system.debug(ex.getMessage());
}
}
..............
}
You are not setting the values retrieved from the VF page into any parameter in the controller. First set them. Then create a object of type Consumer and then assign these values from VF page into the fields from the object. Only then you will be able to insert con.