How to set default value of <p:selectOneMenu - java

I have a jsf containing two <p:selectOneMenu ...> components.
Part of JSF:
<p:selectOneMenu id="speakerLanguage"
value="#{speakerAddFormView.currentSpeaker.nativLang1}">
<f:selectItem itemLabel="Select Language" itemValue="-1" />
<f:selectItems value="#{speakerAddFormView.languages.entrySet()}"
var="languages" itemLabel="#{languages.key}"
itemValue="#{languages.value}" />
<p:ajax listener="#{speakerAddFormView.updateStateSecondNativeLangSOM}"
update="speakerLanguage2" />
</p:selectOneMenu>
<p:selectOneMenu id="speakerLanguage2"
value="#{speakerAddFormView.currentSpeaker.nativLang2}"
disabled="#{speakerAddFormView.disableSecondNativeLangSOM}">
<f:selectItem itemLabel="Select second Language" itemValue="-1" />
<f:selectItems value="#{speakerAddFormView.languages.entrySet()}"
var="languages" itemLabel="#{languages.key}"
itemValue="#{languages.value}"/>
</p:selectOneMenu>
Within my bean I have a public static final Map<String, String> LANGUAGE_CODES = new TreeMap<String, String>(); containing native languages. This TreeMap is referenced at initialization of the bean at:
#PostConstruct
public void init() {
this.languages = ConstantCodes.LANGUAGE_CODES;
}
When I reload the page, the both <p:selectOneMenus > are seleected not to the default <f:selectItem itemLabel="Select Language" itemValue="-1" /> or <f:selectItem itemLabel="Select second Language" itemValue="-1" />.
Screen Snip:
Edit: These two items are selected from the beginning.
Is there a way to force the default selected value ?

Set your nativLang1 and nativLang2 to -1 in your #PostConstruct method.
#PostConstruct
public void init() {
System.out.println("initializing");
this.languages = ConstantCodes.LANGUAGE_CODES;
nativLang1 = "-1";
nativLang2 = "-1";
}

Related

Filtering City by state in java - Using Array

So,
I've an ArrayList with the values of State and City, And I've to check if state are equals to some variable, lets call its "var1" and if this state are equals, I've to get the city names...
I'm creating a menu filter.
<div class="col-md-3">
<label>#{msg['state']}</label>
<h:selectOneMenu id="mdl-state" value="#{saisReportQueryBean.keyState}" class="form-control">
<f:ajax listener="#{saisReportQueryBean.Teste()}"/>
<f:selectItem itemValue="#{null}" itemLabel="#{msg['select_state']}" noSelectionOption="true" />
<f:selectItems value="#{saisReportQueryBean.keyState}" var="estado" itemValue="#{estado}" itemLabel="#{estado}" />
</h:selectOneMenu>
</div>
<div class="col-md-3">
<label>#{msg['city']}</label>
<h:selectOneMenu id="mdl-city" value="#{saisReportQueryBean.keyCity}" class="form-control">
<f:selectItem itemValue="#{null}" itemLabel="#{msg['select_city']}" noSelectionOption="true" />
<f:selectItems value="#{saisReportQueryBean.keyCity}" var="cidade" itemValue="#{cidade}" itemLabel="#{cidade}" />
</h:selectOneMenu>
</div>
When I select the state, I've to update my city itens with just only city in references with the state selected.
Here is my java code.:
protected void updateData() {
this.reportQuery = new SaisReportQuery();
this.queryExecuted = false;
cidades = cidadesIbgeBeanRemote.findAll();
cidades.sort((f1, f2) -> f1.getMunicipio().compareTo(f2.getMunicipio()));
Map<String, List<CidadeIbge>> estados = cidades.stream().collect(Collectors.groupingBy(CidadeIbge::getUf));
setKeyState(estados.keySet());
getKeyState().toString();
System.out.println(keyState);
}
Tks.
Sorry everyone for my uncompleted question.
My point is, when I select some value in my menu, this have to change another menu with the values in referente:
Front Implementation:
<h:panelGroup layout="block" class="col-md-3" id="panel-state">
<label>#{msg['state']}</label>
<h:selectOneMenu id="mdl-state" value="#{saisReportQueryBean.reportQuery.state}" binding="#{uf}" class="form-control input_no_round_corner">
<f:selectItem itemValue="#{null}" itemLabel="#{msg['select_state']}" noSelectionOption="true" />
<f:selectItems value="#{saisReportQueryBean.keyState}" var="estado" itemValue="#{estado}" itemLabel="#{estado}" />
<f:ajax listener="#{saisReportQueryBean.UpdateCityByState(uf.value)}" render=":panel-city" event="change" execute="#this" onevent="initializeChosenFieldsCity">
</f:ajax>
</h:selectOneMenu>
</h:panelGroup>
<h:panelGroup layout="block" class="col-md-3" id="panel-city">
<label>#{msg['city']}</label>
<h:selectOneMenu id="mdl-city" value="#{saisReportQueryBean.listCidades}" class="form-control input_no_round_corner">
<f:selectItem itemValue="#{null}" itemLabel="#{msg['select_city']}" noSelectionOption="true" />
<f:selectItems value="#{saisReportQueryBean.listCidades}" var="cidade" itemValue="#{cidade.municipio}" itemLabel="#{cidade.municipio}" />
</h:selectOneMenu>
</h:panelGroup>
Back implementation:
cidades = cidadesIbgeBeanRemote.findAll();
setKeyState(new ArrayList(estados.keySet()));
getKeyState().toString();
getKeyState().sort((f1, f2) -> f1.compareTo(f2));

Primefaces <p:ajax update...> crashes form

I have a problem when I select an item from a component and when updating another component, it stops working. The strange thing is that with the application works correctly but with it breaks.
<p:panelGrid columns="#{bundle.columnas}" layout="grid" id="panel">
<p:outputLabel for="provincia" value="Provincia *" />
<p:selectOneMenu id="provincia"
value="#{inmuebleBacking.provincia}"
converter="provinciaConverter">
<f:selectItem itemLabel="Seleccione Una Provincia" itemValue="" noSelectionOption="true"/>
<f:selectItems value="#{provinciaBacking.findAllProvincias()}" var="prov" itemLabel="#{prov.provinciaNombre}" />
<p:ajax update="ciudad" listener="#{inmuebleBacking.provinciaSelecionada()}"/>
</p:selectOneMenu>
<p:outputLabel for="ciudad" value="Ciudad *" />
<h:selectOneMenu id="ciudad"
value="#{inmuebleBacking.ciudad}"
converter="ciudadConverter"
required="true">
<f:selectItem itemLabel="Seleccione Una Ciudad" itemValue="" />
<f:selectItems value="#{inmuebleBacking.ciudades}" var="ciudad" itemLabel="#{ciustrong textdad.ciudadNombre} cp: #{ciudad.cp}"/>
</h:selectOneMenu>
BackingBeans
#ViewScoped
#ManagedBean(name = "inmuebleBacking")
public class InmuebleBacking {
#EJB
private CiudadDAO ciudadDAO;
private List<Ciudad> ciudades;
public void provinciaSelecionada() {
Inmueble inmueble = (Inmueble) getEntity();
ciudades = ciudadDAO.findAllNamedBy("Ciudad.findByProvinciaId", "provinciaId", inmueble.getProvincia().getId());}
SCREENSHOTS

Update Value by AjaxListener

my problem is, that I got two fields. Here is the definition:
<h:selectOneMenu id="selectSource" update=":relationTableForm:selectObject" value="#{tabDefineRelationTable.sourceId}" style="width: 100%;" required="true" requiredMessage="Source is required">
<p:ajax listener="#{tabDefineRelationTable.handleSourceChange}" />
<f:selectItem itemLabel="Select Source" itemValue="0" noSelectionOption="true" />
<f:selectItems value="#{tabDefineRelationTable.mySources}"
update=":createArtifactForm:selectObject"
var="source"
itemLabel="#{source.s_name}"
itemValue="#{source.s_id}" />
</h:selectOneMenu>
<h:selectOneMenu id="selectObject" value="#{tabDefineRelationTable.objectId}" style="width: 100%;" required="true" requiredMessage="Object is required" onchange="submit()">
<f:selectItem itemLabel="first select Source" itemValue="0" noSelectionOption="true" />
<f:selectItems value="#{tabDefineRelationTable.myObjects}"
var="object"
itemLabel="#{object.o_name}"
itemValue="#{object.o_id}" />
</h:selectOneMenu>
I want to implement, if I select in my selectSource a field, I update the variable objectId in the backend, and see it in my frontend.
Here is my first try to implement it:
Variable definition
private List<Source> mySources;
private List<Objects> myObjects;
private Integer sourceId = 0;
private Integer objectId = 0;
Constructor:
public TabDefineRelationTable (TabLoader parent, List<Source> sources, List<Objects> objects) {
parentForm = parent;
mySources = sources;
myObjects = objects;
}
Listener:
public void handleSourceChange() {
this.objectId = 0;
if (sourceId != 0) {
for (Source curSource : mySources) {
if (curSource.getS_id() == sourceId) {
myObjects.clear();
myObjects.addAll(curSource.getObjects());
}
}
}
}
Thanks a lot.
Best regards
Björn
Update 1:
After I tried the solution to use <p:ajax event="select" update="tabView:relationTableForm:selectObject" listener="#{tabDefineRelationTable.handleSourceChange}" />,
<p:ajax event="select" update=":relationTableForm:selectObject" listener="#{tabDefineRelationTable.handleSourceChange}" /> or
<p:ajax event="select" update=":selectObject" listener="#{tabDefineRelationTable.handleSourceChange}" />.
I got this errormessage:Cannot find component with identifier "tabView:relationTableForm:selectObject" referenced from tabView:relationTableForm:selectSource".
Any other Ideas?
Update 2:
update="#([id$=output])" testet this one. Didn't got an error, but the field is also not updated :/
could you try this..
<p:ajax update="selectObject" listener="#{tabDefineRelationTable.handleSourceChange}" />
The solution was to change the ajax line into
<p:ajax update="selectObject" listener="#{tabDefineRelationTable.handleSourceChange}" />
Big thanks to serdar for help!

JSF onchange event

I have a JSF application in which I have an combobox like this.
<script type="text/javascript" defer="defer">
<!--//--><![CDATA[//><!--
helpKey = 'APPLICATION_EDIT_DATASOURCE';
function reapplyStyles() {}
function selectT(data){
if(data.status == "begin"){
$('editForm:selectTypeButton').click();
}
}
//--><!]]>
</script>
<h:form id="editForm">
<h:inputHidden id="id" value="#{applicationObject.objectId}"/>
<h:inputHidden id="type" value="#{applicationObject.object.type}"/>
<h:inputHidden id="selectedDSForApp" value="#{applicationObject.selectedDataSourceId}"/>
<ui:param name="activityDataSource" value="#{applicationObject.selectedDataSourceBean}"/>
<a4j:outputPanel id="activityDataSourceRulesPanel">
<h:panelGrid columns="2" columnClasses="padded" rowClasses="padded">
<h:outputText value="#{msgs.transformation_rule}"/>
<h:panelGroup>
<h:selectOneMenu id="dsTransformationRule" value="#{activityDataSource.selectedTransformationRule}"
disabled="#{!sp:hasRight(facesContext, 'ManageApplication')}"
readonly="#{!sp:hasRight(facesContext, 'ManageApplication')}">
<f:selectItems value="#{activityDataSource.transformationRules}"/>
</h:selectOneMenu>
<ui:fragment rendered="#{sp:hasRight(facesContext, 'ManageRules')}" >
<input type="button" value="#{msgs.button_ellipsis}" class="ruleEditorBtn"
onclick="SailPoint.Rule.Editor.edit($('editForm:dsTransformationRule').value,
'ActivityTransformer',
$('editForm:refreshActivityDataSourceRulesButton'))" />
</ui:fragment>
</h:panelGroup>
<h:outputText value="#{msgs.correlation_rule}"/>
<h:panelGroup>
<h:selectOneMenu id="dsCorrelationRule" value="#{activityDataSource.selectedCorrelationRule}"
disabled="#{!sp:hasRight(facesContext, 'ManageApplication')}"
readonly="#{!sp:hasRight(facesContext, 'ManageApplication')}">
<f:selectItems value="#{activityDataSource.correlationRules}"/>
</h:selectOneMenu>
<ui:fragment rendered="#{sp:hasRight(facesContext, 'ManageRules')}" >
<input type="button" value="#{msgs.button_ellipsis}" class="ruleEditorBtn"
onclick="SailPoint.Rule.Editor.edit($('editForm:dsCorrelationRule').value,
'ActivityCorrelation',
$('editForm:refreshActivityDataSourceRulesButton'))" />
</ui:fragment>
</h:panelGroup>
<h:outputText value="#{msgs.activity_data_src_type}"/>
<h:panelGroup>
<a4j:outputPanel id="collectorSettings">
<h:selectOneMenu id="collectorType"
value="#{activityDataSource.object.type}"
rendered="#{empty activityDataSource.object.id}"
disabled="#{!sp:hasRight(facesContext, 'ManageApplication')}"
readonly="#{!sp:hasRight(facesContext, 'ManageApplication')}">
<!-- onchange="$('editForm:selectTypeButton').click();"> -->
<f:ajax event="change"
onevent="selectT"
execute="#this dsTransformationRule dsCorrelationRule"
render="dsTransformationRule dsCorrelationRule"
listener="#{activityDataSource.handleCollectorTypeChange}" />
<f:selectItem itemValue="" itemLabel="#{msgs.select_collector_type}"/>
<f:selectItems value="#{activityDataSource.collectorTypes}"/>
</h:selectOneMenu>
<h:selectOneMenu id="fixedCollectorType" value="#{empty activityDataSource.object.type ? 'None' : activityDataSource.object.type}"
rendered="#{not empty activityDataSource.object.id}"
disabled="true"
readonly="true">
<f:selectItem itemValue="#{empty activityDataSource.object.type ? 'None' : activityDataSource.object.type}"
itemLabel="#{empty activityDataSource.object.type ? msgs.none : activityDataSource.object.type}"/>
</h:selectOneMenu>
</a4j:outputPanel>
</h:panelGroup>
</h:panelGrid>
</a4j:outputPanel>
<a4j:outputPanel id="configSettings">
<h:messages infoClass="formInfo" warnClass="formWarn" errorClass="formError" fatalClass="formError"/>
<h:panelGroup rendered="#{not empty activityDataSource.object.collector}">
<ui:include src="#{activityDataSource.configPage}"/>
</h:panelGroup>
</a4j:outputPanel>
<h:panelGroup>
<div class="buttonRow">
<ui:fragment rendered="#{sp:hasRight(facesContext, 'ManageApplication')}">
<h:commandButton id="activityDataSourceSave" action="#{activityDataSource.saveAction}" value="#{msgs.button_save}" styleClass="primaryBtn"/>
</ui:fragment>
<h:commandButton id="activityDataSourceCancel" action="#{activityDataSource.cancelAction}" value="#{msgs.button_cancel}" styleClass="secondaryBtn"/>
</div>
</h:panelGroup>
<a4j:commandButton id="refreshActivityDataSourceRulesButton"
style="display:none"
immediate="true"
render="activityDataSourceRulesPanel"/>
<a4j:commandButton id="selectTypeButton" action="#{activityDataSource.selectType}" style="display:none"
render="configSettings, collectorSettings"
oncomplete="initializeSelectedConfigPage();"/>
</h:form>
Bean Class
public String getSelectedTransformationRule() {
if (_selectedTransformationRule == null) {
ActivityDataSourceDTO dto = getObject();
if (dto != null)
_selectedTransformationRule = dto.getTransformationRule();
}
return _selectedTransformationRule;
}
public String getSelectedCorrelationRule() {
if (_selectedCorrelationRule == null) {
ActivityDataSourceDTO dto = getObject();
if (dto != null)
_selectedCorrelationRule = dto.getCorrelationRule();
}
return _selectedCorrelationRule;
}
In the above code I have a normal onchange event & an ajax onchange event on combobox element id= collectorType.
Is there any limitation in using two change for same element in JSF.
Also how can I merge first onchange to ajax onchange.
Use onevent attribute of <f:ajax> as follows:
<h:selectOneMenu id="collectorType"
value="#{activityDataSource.object.type}"
rendered="#{empty activityDataSource.object.id}"
disabled="#{!sp:hasRight(facesContext, 'ManageApplication')}"
readonly="#{!sp:hasRight(facesContext, 'ManageApplication')}">
<f:ajax event="change"
execute="#this"
render="dsTransformationRule dsCorrelationRule"
listener="#{activityDataSource.handleCollectorTypeChange}"
onevent="$('#editForm\\:selectTypeButton').click();"/>
<f:selectItem itemValue="" itemLabel="#{msgs.select_collector_type}"/>
<f:selectItems value="#{activityDataSource.collectorTypes}"/>
</h:selectOneMenu>
also notice I've modified the selector '#editForm\\:selectTypeButton' to escape the : in your button's id.
[UPDATE]
Here's what you can do to achieve the scenario we've discussed in the comments:
First to populate both dsTransformationRule and dsCorrelationRule with _selectedTransformationRule and _selectedCorrelationRule respectively, create an initialization method for them, and call it in #PostConstruct method (check Why use #PostConstruct?), so in your bean class you would have something like this:
#PostConstuct
public void init() {
initRules();
//include another things you want to be initializaed when this page finishes constructing.
}
private void initRules() {
ActivityDataSourceDTO dto = getObject();
if (dto == null)
return;
if (_selectedTransformationRule == null)
_selectedTransformationRule = dto.getTransformationRule();
if (_selectedCorrelationRule == null)
_selectedCorrelationRule = dto.getCorrelationRule();
}
//Let the getters do no dto access, so it won't matter if they're called twice on change
public String getSelectedTransformationRule() {
return _selectedTransformationRule;
}
public String getSelectedCorrelationRule() {
return _selectedCorrelationRule;
}
Now your f:ajax can normally execute and render your select menus without fearing to access your DTO layer multiple times
<f:ajax event="change" onevent="selectT"
execute="#this dsTransformationRule dsCorrelationRule"
render="dsTransformationRule dsCorrelationRule"
listener="#{activityDataSource.handleCollectorTypeChange}" />
This way, when handleCollectorTypeChange is invoked, will have both _selectedTransformationRule and _selectedCorrelationRule populated with their last selected values.
On a side note, if you want to get the values of select menus dsTransformationRule and dsCorrelationRule in a validation or conversion phase, or directly via an event listener method that is called before the Update Model Values phase, check this answer that would help you reach the value from the component.
Hopefully this would solve your issue, or at least set you in the right direction.

Value didn't set selectOneMenu to ManagedBean

I have a selectOneMenu that loads anothers in demand. See:
<h:outputLabel value="Tabela: *" />
<p:selectOneMenu id="selectOneMenuTabela"
converter="entityConverter"
value="#{orcamentoMB.tabelaSelecionada}" effect="fade"
required="true" requiredMessage="A Tabela é obrigatória">
<f:selectItem itemLabel="Selecione uma Tabela" itemValue="" />
<f:selectItems value="#{orcamentoMB.tabelas}" var="tabela"
itemLabel="#{tabela.nome}" itemValue="#{tabela}" />
<p:ajax event="change" update="selectOneMenuProcedimento" />
</p:selectOneMenu>
<h:outputText value="Procedimento: *" />
<p:selectOneMenu id="selectOneMenuProcedimento"
disabled="#{orcamentoMB.tabelaSelecionada == null}"
converter="entityConverter" filter="true"
filterMatchMode="contains"
value="#{orcamentoMB.itemTabelaProcedimentoSelecionado}"
effect="fade" required="true"
requiredMessage="O procedimento é obrigatório">
<f:selectItem itemLabel="Selecione um Procedimento" itemValue="" />
<f:selectItems value="#{orcamentoMB.tabelaSelecionada.itens}"
var="item" itemLabel="#{item.procedimento.nome}"
itemValue="#{item}" />
<p:ajax event="change"
update="localAplicacao, selectOneMenuDente,selectOneMenuFace" />
</p:selectOneMenu>
<h:outputText value="Local Aplicação: *" />
<h:outputText id="localAplicacao"
value="#{orcamentoMB.itemTabelaProcedimentoSelecionado.procedimento.localAplicacao.descricao}" />
<h:outputText value="Dente: *" />
<p:selectOneMenu id="selectOneMenuDente" converter="entityConverter"
filter="true" filterMatchMode="contains"
disabled="#{orcamentoMB.itemTabelaProcedimentoSelecionado.procedimento == null || orcamentoMB.itemTabelaProcedimentoSelecionado.procedimento.dentesAsList.size() == 0}"
value="#{orcamentoMB.denteSelecionado}" effect="fade">
<f:selectItem itemLabel="Selecione um Dente" itemValue="" />
<f:selectItems
value="#{orcamentoMB.itemTabelaProcedimentoSelecionado.procedimento.dentesAsList}"
var="dente" itemLabel="#{dente.descricao}" itemValue="#{dente}" />
</p:selectOneMenu>
<h:outputText value="Face: *" />
<p:selectOneMenu id="selectOneMenuFace" converter="entityConverter"
disabled="#{orcamentoMB.itemTabelaProcedimentoSelecionado.procedimento.facesAplicacaoAsList.size() == 0 || orcamentoMB.itemTabelaProcedimentoSelecionado == null}"
value="#{orcamentoMB.faceSelecionada}" effect="fade">
<f:selectItem itemLabel="Selecione uma Face" itemValue="" />
<f:selectItems
value="#{orcamentoMB.itemOrcamento.itemTabelaProcedimento.procedimento.facesAplicacaoAsList}"
var="face" itemLabel="#{face.descricao}" itemValue="#{face}" />
</p:selectOneMenu>
The "selectOneMenuTabela" and "selectOneMenuProcedimento" works fine, the value are setted in ManagedBean, but the others not.
When i try to execute this commandButton bellow:
<p:commandButton value="Incluir" icon="ui-icon-plus" process="#this"
disabled="#{orcamentoMB.bean.situacao.codigo != 'AGUARDANDO_ACEITACAO'}"
update=":formManterOrcamento:tabViewManterOrcamento:tabProcedimentos,:formManterOrcamento:panelTotais"
actionListener="#{orcamentoMB.addItemOrcamento}" />
THe value inside "denteSelecionado" is null, and the values inside "selectOneMenuFace" aren't loaded.
Since you are having p:ajax event="change"on first two selectOneMenu they are being submitted that is why you are getting those value. To process them on click of commandButton add those component ids to process attribute along with #this like process like process="#this,selectOneMenuFace,selectOneMenuDente,.."
If the component is disabled or readOnly then they won't be processed.
Hope this helps

Categories