GXT Grid in ContentPanel messes up BorderLayout - java

EDIT
Although, thanks to Colin, the problems with the Grid itself are now fixed, the BorderLayoutPanel still initializes the grid on a strange (small) height and the middle border is nowhere to be found.
--
I have a GWT application that has a GXT viewport, containing a BorderLayoutContainer containing another BorderLayoutContainer, like so:
Now this works fine if I substitute my Grid for a GXT ContentPanel:
However, I am unpleasantly surprised when I implement the Grid:
The grid suddenly brings the size of the North component back to something smaller, it hides further under the header (the north component already has a margin-top of 10px), and the line between the grid and TabPanel can no longer be grabbed to resize the viewports. Also, one'd expect the grid to show scrollbars in this scenario. Also, on collapsing the Grid's ContentPanel, the center component doesn't proceed to fill up the leftover space as it should.
The Grid worked fine back when I used GWT panels (DockLayoutPanel, SplitLayoutPanel), so I proceeded to wrap the grid in a VerticalPanel (within a GXT ContentPanel). No changes ensued.
DocGrid UiBinder
<!DOCTYPE ui:UiBinder SYSTEM "http://dl.google.com/gwt/DTD/xhtml.ent">
<ui:with type="com.sencha.gxt.widget.core.client.grid.ColumnModel"
field="cm"></ui:with>
<ui:with type="com.sencha.gxt.data.shared.ListStore" field="store"></ui:with>
<ui:with type="com.sencha.gxt.widget.core.client.grid.GridView"
field="view">
<ui:attributes stripeRows="true" forceFit="true"></ui:attributes>
</ui:with>
<gxt:ContentPanel ui:field="contentPanel" height="100%" width="100%">
<row:VerticalLayoutContainer borders="false">
<row:child>
<grid:Grid ui:field="grid" cm="{cm}" store="{store}" view="{view}"
loadMask="true" columnReordering="true" borders="false"
height="500px">
</grid:Grid>
</row:child>
<row:child>
<toolbar:PagingToolBar pageSize="20" ui:field="toolBar" width="100%"></toolbar:PagingToolBar>
</row:child>
</row:VerticalLayoutContainer>
</gxt:ContentPanel>
Any help or clues are greatly appreciated.
EDIT
by request, DocGrid.java
package nl.opensatisfaction.postkamer.client.ui;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import com.google.gwt.cell.client.DateCell;
import com.google.gwt.core.client.GWT;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiFactory;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.IsWidget;
import com.google.gwt.user.client.ui.Widget;
import com.sencha.gxt.core.client.IdentityValueProvider;
import com.sencha.gxt.core.client.Style.SelectionMode;
import com.sencha.gxt.data.shared.ListStore;
import com.sencha.gxt.widget.core.client.ContentPanel;
import com.sencha.gxt.widget.core.client.box.MessageBox;
import com.sencha.gxt.widget.core.client.grid.CheckBoxSelectionModel;
import com.sencha.gxt.widget.core.client.grid.ColumnConfig;
import com.sencha.gxt.widget.core.client.grid.ColumnModel;
import com.sencha.gxt.widget.core.client.grid.Grid;
import com.sencha.gxt.widget.core.client.grid.GridView;
import com.sencha.gxt.widget.core.client.grid.filters.DateFilter;
import com.sencha.gxt.widget.core.client.grid.filters.GridFilters;
import com.sencha.gxt.widget.core.client.grid.filters.StringFilter;
import com.sencha.gxt.widget.core.client.toolbar.PagingToolBar;
public class DocGrid implements IsWidget {
private static final DocumentNodeProperties props = GWT
.create(DocumentNodeProperties.class);
AlfrescoServiceAsync metadata = GWT.create(AlfrescoService.class);
interface MyUiBinder extends UiBinder<Widget, DocGrid> {
}
private static MyUiBinder uiBinder = GWT.create(MyUiBinder.class);
#UiField
ColumnModel<DocumentNode> cm;
#UiField
ListStore<DocumentNode> store;
#UiField
Grid<DocumentNode> grid;
#UiField
GridView<DocumentNode> view;
#UiField
PagingToolBar toolBar;
#UiField
ContentPanel contentPanel;
#Override
public Widget asWidget() {
IdentityValueProvider<DocumentNode> identity = new IdentityValueProvider<DocumentNode>();
final CheckBoxSelectionModel<DocumentNode> sm = new CheckBoxSelectionModel<DocumentNode>(identity);
sm.setSelectionMode(SelectionMode.MULTI);
ColumnConfig<DocumentNode, String> nameCol = new ColumnConfig<DocumentNode, String>(
props.nodeRef(), 100, "nodeRef");
ColumnConfig<DocumentNode, String> documentIdCol = new ColumnConfig<DocumentNode, String>(
props.documentIdentificatie(), 100, "Document ID");
ColumnConfig<DocumentNode, Date> ontvangenCol = new ColumnConfig<DocumentNode, Date>(
props.documentOntvangstdatum(), 100, "Ontvangen");
ontvangenCol.setCell(new DateCell(OpenPostModule.DATE_FORMAT));
ColumnConfig<DocumentNode, Date> aanschrijfCol = new ColumnConfig<DocumentNode, Date>(
props.documentAanschrijfdatum(), 100, "Aangeschreven");
aanschrijfCol.setCell(new DateCell(OpenPostModule.DATE_FORMAT));
ColumnConfig<DocumentNode, String> doctypeCol = new ColumnConfig<DocumentNode, String>(
props.documentTypeOmschrijving(), 100, "Type");
ColumnConfig<DocumentNode, String> subjectCol = new ColumnConfig<DocumentNode, String>(
props.afzenderIdentificatie(), 100, "BSN/KVK");
ColumnConfig<DocumentNode, AlfrescoUser> behandelaarCol = new ColumnConfig<DocumentNode, AlfrescoUser>(
props.documentBehandelaar(), 100, "Behandelaar");
ColumnConfig<DocumentNode, AlfrescoObject> groepCol = new ColumnConfig<DocumentNode, AlfrescoObject>(
props.documentGroep(), 100, "Groep");
List<ColumnConfig<DocumentNode, ?>> l = new ArrayList<ColumnConfig<DocumentNode, ?>>();
l.add(sm.getColumn());
l.add(documentIdCol);
l.add(ontvangenCol);
l.add(aanschrijfCol);
l.add(doctypeCol);
l.add(subjectCol);
l.add(groepCol);
l.add(behandelaarCol);
cm = new ColumnModel<DocumentNode>(l);
store = new ListStore<DocumentNode>(props.key());
Widget component = uiBinder.createAndBindUi(this);
contentPanel.setCollapsible(true);
contentPanel.setAnimCollapse(true);
view.setAutoExpandColumn(nameCol);
grid.setSelectionModel(sm);
// Column filters
StringFilter<DocumentNode> nameFilter = new StringFilter<DocumentNode>(props.documentIdentificatie());
DateFilter<DocumentNode> dateFilter = new DateFilter<DocumentNode>(props.documentOntvangstdatum());
DateFilter<DocumentNode> dateFilter2 = new DateFilter<DocumentNode>(props.documentAanschrijfdatum());
StringFilter<DocumentNode> docTypeFilter = new StringFilter<DocumentNode>(props.documentTypeOmschrijving());
StringFilter<DocumentNode> subjectFilter = new StringFilter<DocumentNode>(props.documentTitel());
StringFilter<DocumentNode> groepFilter = new StringFilter<DocumentNode>(props.documentGroepLabel());
StringFilter<DocumentNode> behandelaarFilter = new StringFilter<DocumentNode>(props.documentBehandelaarLabel());
GridFilters<DocumentNode> filters = new GridFilters<DocumentNode>();
filters.initPlugin(grid);
filters.setLocal(true);
filters.addFilter(nameFilter);
filters.addFilter(dateFilter);
filters.addFilter(dateFilter2);
filters.addFilter(docTypeFilter);
filters.addFilter(subjectFilter);
filters.addFilter(groepFilter);
filters.addFilter(behandelaarFilter);
return component;
}
#UiFactory
ColumnModel<DocumentNode> createColumnModel() {
return cm;
}
#UiFactory
ListStore<DocumentNode> createListStore() {
return store;
}
public void fillGrid(AlfrescoUser user) {
metadata.getPoststukken(user, new AsyncCallback<ArrayList<DocumentNode>>() {
#Override
public void onSuccess(ArrayList<DocumentNode> result) {
// Sorts DocumentNode by its generatedPriority
Collections.sort(result);
store.addAll(result);
if(result.size()==0) {
new MessageBox("", "er zijn geen poststukken gevonden.").show();
}
}
#Override
public void onFailure(Throwable caught) {
if(caught instanceof CustomException) {
new MessageBox(((CustomException) caught).getTitle(), caught.getMessage()).show();
if(caught instanceof CustomException) {
// TODO: move logic to PostCenter, then act appropriately
new MessageBox("Uitgelogd", "U bent uitgelogd.");
}
}
}
});
}
public void removeDocument(String documentIdentificatie) {
for(DocumentNode doc : grid.getStore().getAll()) {
if(doc.getDocumentIdentificatie().equals(documentIdentificatie)) {
DebugClient.debug("Removing row with id " + doc.getDocumentIdentificatie(), this.getClass());
grid.getStore().remove(doc);
break;
}
}
}
public void updateRow(DocumentNode node) {
DebugClient.debug("Updating row with id " + node.getDocumentIdentificatie(), this.getClass());
grid.getStore().update(node);
}
}
EDIT: BLP UiBinder
This is the UiBinder code that includes the DocGrid. This is the one directly on the RootPanel.
<!DOCTYPE ui:UiBinder SYSTEM "http://dl.google.com/gwt/DTD/xhtml.ent">
<ui:style>
.important {
font-weight: bold;
}
</ui:style>
<ui:with type="com.sencha.gxt.core.client.util.Margins" field="zeroMargins">
<ui:attributes top="0" right="0" bottom="0" left="0" />
</ui:with>
<ui:with type="com.sencha.gxt.core.client.util.Margins" field="correctionMargins">
<ui:attributes top="10" right="0" bottom="0" left="0" />
</ui:with>
<ui:with
type="com.sencha.gxt.widget.core.client.container.BorderLayoutContainer.BorderLayoutData"
field="northData">
<ui:attributes size="35" collapsible="false" split="false"
margins="{zeroMargins}" />
</ui:with>
<ui:with
type="com.sencha.gxt.widget.core.client.container.BorderLayoutContainer.BorderLayoutData"
field="southData">
<ui:attributes size="20" collapsible="false" split="false"
margins="{zeroMargins}" />
</ui:with>
<ui:with
type="com.sencha.gxt.widget.core.client.container.BorderLayoutContainer.BorderLayoutData"
field="innerWestData">
<ui:attributes size="600" collapsible="true" split="true"
margins="{zeroMargins}" />
</ui:with>
<ui:with
type="com.sencha.gxt.widget.core.client.container.BorderLayoutContainer.BorderLayoutData"
field="gridContainerData">
<ui:attributes size="500" collapsible="true" split="true"
margins="{correctionMargins}" />
</ui:with>
<container:Viewport>
<container:BorderLayoutContainer
ui:field="dockPanel">
<container:north layoutData="{northData}">
<os:Header ui:field="osHeader" />
</container:north>
<container:west layoutData="{innerWestData}">
<container:BorderLayoutContainer
ui:field="innerSplitPanel">
<container:north layoutData="{gridContainerData}">
<os:DocGrid ui:field="docGrid" />
</container:north>
<container:center>
<os:MetaTabPanel ui:field="metaTabs"></os:MetaTabPanel>
<!-- <gxt:ContentPanel /> -->
</container:center>
</container:BorderLayoutContainer>
<!-- <g:SplitLayoutPanel ui:field="innerSplitPanel"> <g:north size="500">
<os:DocGrid ui:field="docGrid" /> </g:north> <g:center> <os:MetaTabPanel
ui:field="metaTabs" /> </g:center> </g:SplitLayoutPanel> -->
</container:west>
<container:center>
<g:Frame ui:field="viewport" width="100%" height="100%"
styleName="pdfPanel" />
</container:center>
<container:south layoutData="{southData}">
<container:HtmlLayoutContainer
ui:field="footer" />
</container:south>
</container:BorderLayoutContainer>
</container:Viewport>
</ui:UiBinder>
The relevant java is as such (constructor of the UiBinder's class):
initWidget(uiBinder.createAndBindUi(this));
osHeader.setMenuLabel(this.user.getLabel());
docGrid.fillGrid(user);
// Docgrid selection handler
docGrid.grid.getSelectionModel().addSelectionChangedHandler(new SelectionChangedHandler<DocumentNode>() {
#Override
public void onSelectionChanged(SelectionChangedEvent<DocumentNode> event) {
List<DocumentNode> selected = event.getSelection();
if (selected.size()>0) {
documentSelected(selected.get(0));
}
}
});

Add layout data to the Grid and PagingToolbar within the VLC in that widget. The toolbar probably should be set to be 100% width (i.e. width="1.0"), and use only the height it needs (height="-1"), and the Grid should use all width and all height (height="1.0" and `width="1.0"). This will probably look more or less like this (from http://www.sencha.com/examples/#ExamplePlace:paginguibindergrid)
<ui:with type="com.sencha.gxt.widget.core.client.container.VerticalLayoutContainer.VerticalLayoutData" field="middleData">
<ui:attributes width="1" height="1" />
</ui:with>
<ui:with type="com.sencha.gxt.widget.core.client.container.VerticalLayoutContainer.VerticalLayoutData" field="bottomData">
<ui:attributes width="1" height="-1" />
</ui:with>
<ui:with type="com.sencha.gxt.widget.core.client.grid.GridView" field="view">
<ui:attributes stripeRows="true" forceFit="true"></ui:attributes>
</ui:with>
<gxt:FramedPanel ui:field="panel" headingText="Grid UiBinder Example" pixelSize="600, 300"
collapsible="true" addStyleNames="margin-10">
<row:VerticalLayoutContainer borders="true">
<row:child layoutData="{middleData}">
<grid:Grid ui:field="grid" cm="{cm}" store="{store}" view="{view}" loadMask="true" columnReordering="true"
borders="false">
</grid:Grid>
</row:child>
<row:child layoutData="{bottomData}">
<toolbar:PagingToolBar pageSize="50" ui:field="toolBar"></toolbar:PagingToolBar>
</row:child>
</row:VerticalLayoutContainer>
</gxt:FramedPanel>
It is then also important that your class backing that xml file is capable of being resized by its parent. Either extend ResizeComposite to get that notification or implement RequiresResize and have that call the ContentPanel's own onResize function, or don't deal with Composite at all, but just implement IsWidget, and have asWidget() return the ContentPanel.
In this case you've got the Java resize wiring correct. However, if asWidget() is called multiple times, you will end up generating multiple copies of a widget - make sure this always returns the same one, probably by storing it in a field and checking if it is null (i.e. createAndBind hasn't been called yet).

Related

ZK How to update ListBox ListModel using selected item

I'm making a web file browser using ZK Components and find a block. Is there any way to update the ListBox model using the selected item of the listbox?
The use case is when traversing the files and folder, the user click the folder, and the list is refreshed with the content of the selected folder. The selection event is triggered and for regular file, it handle well, but not the folder.
My Code:
myfilesvm.zul
<zk>
<window apply="org.zkoss.bind.BindComposer"
viewModel="#id('vm') #init('com.my.zk.mvvm.MyFilesViewModel')">
<hlayout>
<listbox vflex="true" hflex="1" model="#load(vm.files)"
id="fileBrowser" selectedItem="#bind(vm.selectedFile)">
<auxhead>
<auxheader colspan="3">File List</auxheader>
<auxheader colspan="3">
<hlayout>
<!-- breadcrumb, implemented later -->
</hlayout>
</auxheader>
</auxhead>
<listhead>
<listheader label="Name" />
<listheader label="Size" />
<listheader label="Modified" />
</listhead>
<template name="model" var="file">
<listitem>
<listcell label="#load(file.name)" />
<listcell label="#load(file.length())" />
<listcell label="#load(file.lastModified())" />
</listitem>
</template>
</listbox>
</hlayout>
<separator />
</window>
</zk>
MyFilesViewModel.java
package com.my.zk.mvvm;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Arrays;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.zkoss.bind.annotation.Init;
import org.zkoss.bind.annotation.NotifyChange;
import org.zkoss.zul.Filedownload;
import org.zkoss.zul.ListModel;
import org.zkoss.zul.ListModelList;
import com.my.zk.FileCrumbManager;
public class MyFilesViewModel {
private static Logger log = LoggerFactory.getLogger(MyFilesViewModel.class);
// AuthenticationService authService = new AuthenticationServiceImpl();
// UserCredential cre = authService.getUserCredential();
String homeFolder = "D:\\path\\home";
ListModel<File> files = new ListModelList<File>(Arrays.asList(FileCrumbManager.populateList(new File(homeFolder))));
File selectedFile;
#Init
public void init() { // Initialize
}
public ListModel<File> getFiles() {
return files;
}
#NotifyChange({ "selectedFile" })
public void setFiles(ListModel<File> files) {
this.files = files;
}
public File getSelectedFile() {
return selectedFile;
}
public void pilihFile() {
if (getSelectedFile().isDirectory()) {
log.info("File is a directory");
this.files = new ListModelList<File>(
Arrays.asList(FileCrumbManager.populateList(new File(getSelectedFile().getAbsolutePath()))));
} else {
try {
Filedownload.save(getSelectedFile(), null);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
log.error(e.getMessage());
}
}
}
public void setSelectedFile(File selectedFile) {
this.selectedFile = selectedFile;
pilihFile();
}
}
Appreciate for any help. Thank you.
The correct way to refresh ListModelList in pilihFile() is:
this.files.clear();
this.files.addAll(Arrays.asList(FileCrumbManager.populateList(new File(getSelectedFile().getAbsolutePath()))));
Because Listbox is model-driven rendering, you should control the rendering by manipulating the model object. When you call methods of ListModelList, it will notify Listbox to render into a browser. If you replace this.files with a new object, ZK doesn't know it. That's why your browser doesn't have the update.

NullPoinerException in javafx when looking up objects

I have three ellipses that I need to reference in my FXML Controller:
<Ellipse fx:id="selectorontop" id="selectorontop" fill="WHITE" layoutX="121.0" layoutY="101.0" radiusX="14.0" radiusY="27.0" stroke="WHITE" strokeType="INSIDE" style="-fx-opacity: 70%;" visible="false" />
<Ellipse fx:id="selectoronmiddle" id="selectoronmiddle" fill="WHITE" layoutX="121.0" layoutY="168.0" radiusX="14.0" radiusY="27.0" stroke="WHITE" strokeType="INSIDE" style="-fx-opacity: 70%;" visible="false" />
<Ellipse fx:id="selectoronbottom" id="selectoronbottom" fill="WHITE" layoutX="120.0" layoutY="466.0" radiusX="14.0" radiusY="27.0" stroke="WHITE" strokeType="INSIDE" style="-fx-opacity: 70%;" visible="false" />
The scene is passed to the controller after it is created:
public class QuickCopy extends Application {
#Override
public void start(Stage stage) throws Exception {
FXMLLoader loader = new FXMLLoader(getClass().getResource("Main.fxml"));
AnchorPane root = (AnchorPane)loader.load();
Scene scene = new Scene(root);
stage.setScene(scene);
stage.sizeToScene();
stage.setResizable(false);
stage.show();
MainController controller = (MainController)loader.getController();
controller.sendScene(scene);
System.out.println("new: " +scene.lookup("selectorontop"));
}
The scene is received by the controller, yet the result of the lookup is still "null", both in the main Java file (seen above), and in the Controller, and I can't figure out why.
Thanks in advance
The selector you're using selects by type, not by id. It selects nodes of type selectorontop and I'm pretty sure this type doesn't exist. (At least there are no nodes of this type in the scene.)
You need to use the proper CSS selector. In this case you need to use #selectorontop to select by id:
System.out.println("new: " +scene.lookup("#selectorontop"));

CookSwing - Retrieving the string from a textfield

I'm using CookSwing (http://cookxml.yuanheng.org/cookswing/) to build a Java Swing UI, but the site doesn't have a lot of information. I'm stuck trying to get my Java class to retrieve the string from a textfield in the form (declared in XML). This should be easy to do, but nothing I've tried works. Does anyone have experience doing this? Here is the Java class:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import cookxml.cookswing.CookSwing;
public final class CookSwingForm
{
// Listener for the Quit button
public ActionListener exitAction = new ActionListener()
{
public void actionPerformed (ActionEvent e)
{
System.exit(0);
}
};
public CookSwingForm()
{
CookSwing cookSwing = new CookSwing(this);
cookSwing.render("sampleform.xml").setVisible(true);
}
public static void main(String[] args)
{
new CookSwingForm();
}
}
Here is the XML file ("sampleform.xml"):
<frame title="Sample Form" size="300,70"
defaultcloseoperation="EXIT_ON_CLOSE">
<borderlayout>
<constraint location="West">
<textfield columns="20" />
</constraint>
<constraint location="East">
<button text="Quit" actionlistener="exitAction" />
</constraint>
</borderlayout>
</frame>
I just need to have the Java class retrieve the string from the textfield that's declared in the XML file. Any help is greatly appreciated. Thanks!
I think you should use the id attribute and then use that as the variable name for the text field.
The xml would look as : <textfield id="box1" />
Here is what you have to do:
JTextField txtField = (JTextField) cookSwing.getId("box1").object;
//now,set some text
txtField.setText("Blah!");
//or get some text as you may wish
Also. Looks like the library is no longer being developed. That's a red flag right there.

how to use a seam validator in jsf?

I have made a new Seam validator:
package validators;
import java.io.Serializable;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.component.UIInput;
import javax.faces.context.FacesContext;
import javax.faces.validator.ValidatorException;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.faces.Validator;
import org.jboss.seam.annotations.intercept.BypassInterceptors;
import org.jboss.seam.log.Log;
import org.jboss.seam.log.Logging;
#Name("roCountyValidator")
#Validator
#BypassInterceptors
public class RoCountyValidator implements javax.faces.validator.Validator,
Serializable {
/**
*
*/
private static final long serialVersionUID = -3876319398131645955L;
Log log = Logging.getLog(RoCountyValidator.class);
public void validate(FacesContext context, UIComponent component,
Object value) throws ValidatorException {
log.info("validating....!");
if (String.valueOf(value).equals("Arad"))
((UIInput) component).setValid(true);
else {
((UIInput) component).setValid(false);
FacesMessage message = new FacesMessage();
message.setDetail("Invalid county");
message.setSeverity(FacesMessage.SEVERITY_ERROR);
throw new ValidatorException(message);
}
}
}
The problem is that I do not know how to use it directly from jsf...
The following does not work....
I have declared it in a special taglib file: myvalidators.taglib.xml
<facelet-taglib>
<namespace>http://example.com/jsf/my/validators</namespace>
<tag>
<tag-name>roCountyValidator</tag-name>
<validator>
<validator-id>roCountyValidator</validator-id>
</validator>
</tag>
and tried to use it like:
<h:inputText id="someField" value="#{booking.creditCardName}"
required="true" label="County">
<my:roCountyValidator/>
<h:message for="someField"/>
</h:inputText>
Can you tell me where I am wrong?
Thanks.
Two ways to solve this.
One, is to use as #BalusC has written.
You don't need to define anything in faces-config.xml
<h:inputText id="cc" required="true" value="#{booking.creditCardName}">
<f:validator validatorId="roCountyValidator"/>
<f:attribute name="oldCreditCardNumber" value="#{booking.creditCardName}" />
<s:validate />
</h:inputText>
Here you can even bind the old credit card number, if you want to check that also.
Then in your validate method:
public void validate(FacesContext context, UIComponent component,
Object value) throws ValidatorException {
log.info("validating....!");
String oldCreditcard = String.valueOf(component.getAttributes().get("oldCreditCardNumber"));
String newCreditCard = (String) value;
if(SomeClass.isCorrectCreditcard(newCreditCard)) {
//You don't need to setValid(false), this is done automatically
Map<String, String> messages = Messages.instance();
throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR, messages.get("wrongCreditCardNumber"), messages
.get("wrongCreditCardNumber")));
}
}
The other way, is to use the validator tag in <h:inputText>
You don't even need to create a #Validator class, as long as it's a seam component and if you use the same method signature.
I use a validator component for all my general validators
#Name("validator")
#Scope(ScopeType.EVENT)
#BypassInterceptors
public class Validator {
public void positiveInteger(FacesContext context, UIComponent toValidate, Object value) {
String val = (String) value;
try {
int v = Integer.parseInt(val);
if (v < 0)
throw new NumberFormatException();
} catch (NumberFormatException e) {
((UIInput) toValidate).setValid(false);
FacesMessages.instance().addToControlFromResourceBundle(toValidate.getId(), "invalid.integer");
}
}
}
Now you can add the validator:
<h:inputText value="#{foo.bar}" required="true" validator="#{validator.positiveInteger}">
<s:validate/>
<h:inputText>
I have no idea about the Seam part, it might have different approaches for this, but in standard JSF, you normally define it as <validator> in faces-config.xml.
<validator>
<validator-id>roCountyValidator</validator-id>
<validator-class>validators.RoCountyValidator</validator-class>
</validator>
and use it as follows:
<h:inputText>
<f:validator validatorId="roCountyValidator" />
</h:inputText>
Solution found:).
Forget about taglibs and stuff!
Use it like:
<h:inputText id="someField" value="#{booking.creditCardName}"
required="true" label="County" validator="roCountyValidator">
<h:message for="someField"/>
</h:inputText>
Please remark that
validator="roCountyValidator"
it shouldn't be used like EL expression !!! (my first wrong decision)
So the advantage of using Seam + #Validator: Seam will transform that component in the background to a jsf validator so you do no longer need jsf validator tags or any other configuration in faces-config.xml.

Seam - ListSelectMenus with dependencies

I'm trying to build some select boxes with dependencies on other select boxes. I'm fairly new to Seam - just to add this. Here is my JSF - for test purposes I'm trying to display a dataTable
<f:facet name="header">Profil</f:facet>
<a:form ajaxSubmit="true" reRender="testTable">
<s:decorate id="techTypeField" template="layout/edit.xhtml">
<ui:define name="label">Choose tech</ui:define>
<h:selectOneRadio id="techType" value="#{technologyType}" onchange="submit()">
<s:selectItems value="#{technologyTypes}" var="elem" label="#{elem.name}" id="typeId"/>
<s:convertEntity/>
</h:selectOneRadio>
</s:decorate>
</a:form>
<div style="clear:both"/>
<h:dataTable var="productLine" id="testTable" value="#{productLines}" rendered="#{productLines.rowCount > 0}">
<h:column >
<f:facet name="header">pl</f:facet>
#{productLine.id}
</h:column>
</h:dataTable>
My backing bean
package de.ac.dmg.productfinder.workflow;
import java.util.List;
import javax.ejb.Remove;
import javax.ejb.Stateful;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.jboss.seam.annotations.Factory;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Logger;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.datamodel.DataModel;
import org.jboss.seam.annotations.datamodel.DataModelSelection;
import org.jboss.seam.international.StatusMessages;
import org.jboss.seam.log.Log;
import de.ac.entity.Machine;
import de.ac.entity.ProductLine;
import de.ac.entity.TechnologyType;
#Stateful
#Name("Profil")
public class ProfilBean implements IProfil {
#PersistenceContext
private EntityManager entityManager;
#Logger
private Log log;
#DataModel(value = "technologyTypes")
private List<TechnologyType> technologyTypes;
#DataModelSelection(value = "technologyTypes")
private TechnologyType technologyType;
#DataModel(value = "productLines")
private List<ProductLine> productLines;
#DataModel(value = "machines")
List<Machine> machines;
#In
StatusMessages statusMessages;
// add additional action methods
#Factory("technologyTypes")
public void loadTechTypes() {
technologyTypes = entityManager.createQuery("Select t from TechnologyType t").getResultList();
}
#Factory("productLines")
public void loadProductLinies() {
System.out.println(technologyType);
productLines = entityManager.createQuery("select p from ProductLine p where p.technologyType = :type ")
.setParameter("type", technologyType).getResultList();
}
public void next() {
// implement your business logic here
log.info("Profil.next() action called with: #{Profil.value}");
statusMessages.add("next #{Profil.value}");
}
#Remove
public void destroy() {
}
}
I can set the tech type on time - after one click it isn't refreshed sadly. What I'm doing wrong here?
When selecting a 'technology type', you need an action which reloades the product types based on the selected techtype. Something like action=#{Profil.loadProductLines()}

Categories

Resources