GWT - GXT - How to get Radio Button Value? - gwt

I am using GWT (Google Web Toolkit) 1.5.3 et GXT (ExtJS) 1.2
I just want to create a simple form with some radio buttons generated after a RPC call, to get some values
Code:
final FormPanel simple = new FormPanel();
simple.setFrame(true);
simple.setWidth(350);
simple.setHeaderVisible(false);
DateField date = new DateField();
date.setFieldLabel("Date");
simple.add(date);
ListFluxServiceAsync service = (ListFluxServiceAsync)
GWT.create(ListFluxService.class);
ServiceDefTarget target = (ServiceDefTarget)service;
String url = GWT.getModuleBaseURL() + "flux.rpc";
target.setServiceEntryPoint(url);
final RadioGroup radioGroup = new RadioGroup("RadioGroup");
radioGroup.setFieldLabel("Flux");
radioGroup.setOrientation(Orientation.VERTICAL);
service.getAllFlux(new AsyncCallback<List<FluxModelData>>(){
public void onFailure(Throwable caught) {
GWT.log("flux.rpx::onFailure", caught);
MessageBox.alert("what?", "onFailure :" + caught.getMessage(), null);
}
public void onSuccess(List<FluxModelData> result) {
Iterator<FluxModelData> it = result.iterator();
while ( it.hasNext() ){
FluxModelData fmd = it.next();
Radio radio = new Radio();
radio.setName("flux");
radio.setValue(true);
//radio.setRawValue("my very long value");
radio.setBoxLabel(fmd.getDescription());
radioGroup.add(radio);
}
simple.add(radioGroup);
simple.layout(); //we need it to show the radio button
}
});
simple.setButtonAlign(HorizontalAlignment.CENTER);
Button button = new Button("Récupérer");
button.addSelectionListener(new SelectionListener<ButtonEvent>(){
#Override
public void componentSelected(ButtonEvent ce) {
MessageBox.alert("what?", radioGroup.getValue().getRawValue() , null);
}});
simple.addButton(button);
RootPanel.get().add(simple);
My problem is I can't set/get radio button value.
If I try the setRawValue("xxxxxxx"), I will get some null errors, while setting setValue(boolean) is working but I was expecting getting the radio value and not the label value.
Any Idea?

Create radio
Radio radio = new Radio();
radio.setBoxLabel("Si");
radio.setValue(true);
radio.setValueAttribute("true");
Radio radio2 = new Radio();
radio2.setBoxLabel("No");
radio2.setValueAttribute("false");
RadioGroup radioGroup = new RadioGroup();
radioGroup.setFieldLabel("Afecto");
radioGroup.add(radio);
radioGroup.add(radio2);
get selected value
Boolean b = Boolean.parseBoolean(radioGroup.getValue().getValueAttribute());

You need to extend the GWT RadioButton class ex:
public class ExtRadioButton extends RadioButton {
public ExtRadioButton(String name, String label) {
super(name, label);
// TODO Auto-generated constructor stub
}
public void setValue(String value)
{
Element span = getElement();
Element input = DOM.getChild(span,0);
DOM.setElementAttribute(input,"value",value);
}
}
Default it allows only boolean value. After initializing the radio button you need set the value.

Using radioButton.setItemId() and getItemId() resolve it.

Check out this
Radio radio1 = new Radio();
.............
Radio radio2 = new Radio();
.............
in order to get value you can do as follow
String value = (radio1.getValue()) ? radio1.getText() : radio2.getText();

Radio includeButton = new Radio();
Radio excludeButton = new Radio();
RadioGroup radioGroup = new RadioGroup();
radioGroup.add(includeButton);
radioGroup.add(excludeButton);
includeButton.setvalue(true)//false

I use radio.setAttributeValue() method to set value for the radio button.

The other way to do this is to use the radio.setValueAttribute(String) method. Then you can use the following code on the RadioGroup to get the set 'value' attribute of the clicked Radio button:
radioGroup.addListener(Events.Change, new Listener<BaseEvent>() {
#Override
public void handleEvent(BaseEvent be)
{
final RadioGroup radioGroup = (RadioGroup)be.getSource();
final Radio clickedRadioBtn = radioGroup.getValue();
final String valueAttribute = clickedRadioBtn.getValueAttribute(); // Correct !!!
}
});

Related

Swap the type of link depending on model object

I'm at complete loss how to proceed further:
I have panel with a DropDownChoice and a submit button next to it. Depending on the selected value of the DropDownChoice (Obtained upon the firing of a OnChangeAjaxBehavior attached to it, the submit button needs to either replace the whole panel with a different one, OR become an ExternalLink.
Currently, the code looks like that:
public class ReportSelectionPanel extends Panel {
protected OptionItem selectedOption ;
public ReportSelectionPanel(String id) {
super(id);
IModel<List<OptionItem>> choices = new AbstractReadOnlyModel() {
// Create a list of options to be displayed in the DropDownChoice
} ;
final IModel<OptionItem> optionModel =
new PropertyModel<OptionItem>(this,"selectedOption") ;
final DropDownChoice<OptionItem> options =
new DropDownChoice("selectChoice",optionModel,choices) ;
// I don't know what the button should be... Plain Button? A Link?
final Component button = ???
options.add( new OnChangeAjaxBehavior() {
protected void onUpdate(AjaxRequestTarget target) {
if ( selectedOption.getChild() == null ) {
// button becomes an ExternalLink.
// A new window will popup once button is clicked
} else {
// button becomes a Something, and upon clicking,
// this ReportSelectionPanel instance gets replaced by
// an new Panel instance, the type of which is
// selectedOption.getChild()
}
} ) ;
I'm really not quite sure what the commented lines should become to achieve the result. Any suggestions?
Thanks!
Eric
IMHO it's nicer to keep just one button and just react differently depending on the selected option:
final Component button = new AjaxButton("button") {
public void onClick(AjaxRequestTarget target) {
if (selectedOption.getChild() == null) {
PopupSettings popup = new PopupSettings();
popup.setTarget("'" + externalUrl + "'");
target.appendJavascript(popup.getPopupJavaScript());
} else {
ReportSelectionPanel.this.replaceWith(new ReportResultPanel("..."));
}
}
};
// not needed if options and button are inside a form
// options.add( new OnChangeAjaxBehavior() { } ) ;

GWT - Finding which button is checked in a Dynamically generated list of Radiobuttons

I have a for loop that displays a list of text fields and radio buttons.
What is the best way to reference the widgets so that I can read the text fields and aslo find which radio button is checked.
Here is my loop
for(int x = 0; x<getLoopCount(); x++)
{
answerTable.setWidget(x,0, new Label("Answer:"));
answerTable.setWidget(x,1, new TextBox());
answerTable.setWidget(x,2, new RadioButton(""));
}
Is there a way to ID each widget so I can reference it?
I would recommend grouping the three widgets together in a composite widget like this:
class AnswerComposite extends Composite {
private final Label label;
private final TextBox textBox;
private final RadioButton radioButton;
public AnswerComposite() {
label = new Label("Answer:");
textBox = new TextBox();
radioButton = new RadioButton("answerGroup");
HorizontalPanel contentPanel = new HorizontalPanel();
contentPanel.add(label);
contentPanel.add(textBox);
contentPanel.add(radioButton);
initWidget(contentPanel);
}
public String getText() {
return textBox.getValue();
}
public boolean isSelected() {
return radioButton.getValue();
}
}
You can then add them to a panel and/or put them in a list like this:
VerticalPanel answersPanel = new VerticalPanel();
List<AnswerComposite> answerComposites = new ArrayList<AnswerComposite>();
for (int i = 0; i < getLoopCount(); i++) {
AnswerComposite answerComposite = new AnswerComposite();
answersPanel.add(answerComposite);
answerComposites.add(answersComposite);
}
Checking your widgets then becomes very easy:
answerComposites.get(i).getText();
answerComposites.get(i).isSelected();
It will probably also be convenient to add a ValueChangeHandler to your RadioButtons (see enrybo's answer).
You can add a ValueChangeHandler to your RadioButton when you are creating them.
for(int x = 0; x<getLoopCount(); x++){
answerTable.setWidget(x,0, new Label("Answer:"));
answerTable.setWidget(x,1, new TextBox());
RadioButton rb = new RadioButton("");
rb.addValueChangeHandler(new ValueChangeHandler(){
#Override
void onValueChange(ValueChangeEvent<Boolean> event){
// Do something
}
});
answerTable.setWidget(x,2, rb);
}
The ValueChangeEvent will only be fired when the RadioButton is checked. It will not fire if another RadioButton in the same group is checked.
Since you're adding the ValueChangeHandler as you're creating your RadioButton you should know what is to be done with it without having to create an ID for it.
Let me give you an adhoc answer, so don't care about the syntax but the algorithmic idea.
Extend GWT button.
abstract class MyButton
extends Button{
// provide the appropriate constructor in impl class,
// especially if using uibinder
abstract public void helloDolly(... args ...);
}
Instantiate all those buttons using MyButton.
MyButton[] buttons = {
new MyButton(){
public void helloDolly(... args ...){
Window.alert("allo allo #1");
}
},
new MyButton(){
public void helloDolly(... args ...){
Window.alert("allo allo #2");
}
},
// blah blah black sheep ....
}
Use clickEvent.getSource() when defining handler.
buttons[i].addEventHandler(
new ClickHandler(ClickEvent click){
Object src = click.getSource();
if (src !instanceOf MyButton){
throw new MyAngryException("For goodness' sake, pls use MyButton");
// or ignore
return;
}
((MyButton)src).helloDolly(... args ...);
}
)

GXT 3, editable grid, need to perform action on enter

I am new to GXT 3, and am confused by the API. Perhaps you could clarify.
In Editor Grid, how do I catch and examine keyboard keys pressed inside a cell in focus?
Create your grid and pass it to GridEditing instance:
final GridEditing<MyType> ge = new GridInlineEditing<MyType>(grid);
// note: final Grid grid = new Grid(store, cm);
// note: ColumnModel cm = new ColumnModel(configs);
// note: List> configs = new ArrayList>();
Construct your ColumnConfig
ColumnConfig<MyType, String> kanji = new ColumnConfig<MyType, String>(kfgProps.kanji());
// note: kfgProps here extends PropertyAccess
Add your editor
ge.addEditor(kanji, text);
// note: text = new TextField();
Add your DomHandler
text.addDomHandler(new KeyDownHandler() {
#Override public void onKeyDown(KeyDownEvent event) {
if (KeyCodes.KEY_ENTER == event.getNativeEvent().getKeyCode()) {
// do whatever
}
}
}, KeyDownEvent.getType());

GWT:how to get selected radio button's value

I am create dynamic number of radio buttons in my GWT
public void createTestList(ArrayList<Test> result){
for(int i =0 ; i<result.size();i++){
int id = result.get(i).getTestId();
RadioButton rd = new RadioButton("group", result.get(i).getTestType());
verticalPanel.add(rd);
}
where Test is my Entity class ..
I am getting 4 different types of radio buttons in my view , Now if i select any one of the radio button, first I need to get the id of the selected Radio button , how can this be possible ?
secondly How will i check that which one of the multiple radio button is selected ?
Thanks
You need to check public java.lang.Boolean getValue() on each radio button whether it is checked or not.
it is possible to add click handler and update selected radio button variable:
choiceItemKind = new VerticalPanel();
ArrayList<String> kinds = new ArrayList<String>();
kinds.add(...);
kinds.add(...);
choiceItemKind.clear();
ClickHandler choiceClickHandler = new ClickHandler()
{
#Override
public void onClick(ClickEvent event)
{
addItemKindSelectedLabel = ((RadioButton) event.getSource()).getText();
}
};
for (String label : kinds)
{
RadioButton radioButton = new RadioButton("kind", label);
//radioButton.setTitle("Tooltyp");
if (label.equals(addItemKindSelectedLabel))
radioButton.setValue(true);
radioButton.addClickHandler(choiceClickHandler);
choiceItemKind.add(radioButton);
}
...
addItemKindSelectedLabel = "";
...
if (!addItemKindSelectedLabel.isEmpty())
...;
upd: set selected radiobutton without rebuild:
for (int i = 0; i < choiceItemKind.getWidgetCount(); i++)
{
RadioButton radioButton = (RadioButton) choiceItemKind.getWidget(i);
radioButton.setValue(radioButton.getText().equals(addItemKindSelectedLabel));
}

trying to add some link cell in my GWT cellTable

I am trying to add a Link in my cell table (I just want the item to be underlined and mouse symbol change on hover)
and on click I just want to give a window Alert .
for that i have tried these Options : ( but no luck )
1)
final Hyperlink hyp = new Hyperlink("test", "test");
Column<EmployerJobs, Hyperlink> test = new Column<EmployerJobs, Hyperlink>(new HyperLinkCell())
{
#Override
public Hyperlink getValue(EmployerJobs object)
{
return hyp;
}
};
Problem with option 1 is , it takes me to navigation page "test", whereas I dont want to go any other page i just want a window alert.
2)
Column<EmployerJobs, SafeHtml> test = new Column<EmployerJobs, SafeHtml>(new SafeHtmlCell())
{
#Override
public SafeHtml getValue(EmployerJobs object)
{
SafeHtmlBuilder sb = new SafeHtmlBuilder();
sb.appendEscaped("test");
return sb.toSafeHtml();
}
};
problem with option 2 is I dont know what exactly to return here and its not getting underlined.
3) at last i am trying to add anchor in my celltable with a compositecell(as ideally i want three different anchors in my ONE cell)
final Anchor anc = new Anchor();
ArrayList list = new ArrayList();
list.add(anc);
CompositeCell ancCell = new CompositeCell(list);
Column testColumn1 = new Column<EmployerJobs, Anchor>(ancCell) {
#Override
public Anchor getValue(EmployerJobs object) {
return anc;
}
};
Option 3 is giving some exception .
If you can help me get working any of the above option, I'll be grateful
Thanks
You are doing it totally wrong. You need to use ActionCell for stuff like this or create your own cell. Example code:
ActionCell.Delegate<String> delegate = new ActionCell.Delegate<String>(){
public void execute(String value) { //this method will be executed as soon as someone clicks the cell
Window.alert(value);
}
};
ActionCell<String> cell = new ActionCell<String>(safeHtmlTitle,delegate){
#Override
public void render(com.google.gwt.cell.client.Cell.Context context, //we need to render link instead of default button
String value, SafeHtmlBuilder sb) {
sb.appendHtmlConstant("<a href='#'>");
sb.appendEscaped(value);
sb.appendHtmlConstant("</a>");
}
};
Column testColumn1 = new Column<EmployerJobs, String>(cell) {
#Override
public String getValue(EmployerJobs object) {
//we have to return a value which will be passed into the actioncell
return object.name;
}
};
I recommend to read official documentation for Cell Widgets, since it is pretty much everything what you need to know about cell widgets.