GWT - Two Question on Hyperlink - Manage its History token parameter + insert it in a span - gwt

I need to manage a Hyperlink object in GWT. What i need is :
1 - add it into a span (like InlineLabel)
I tried Hyperlink affitta_3_span_1=new Hyperlink(result.get(i)[0], "");, but it create somethings like this :
<div class="affitta_3_span_1">
t1
</div>
in fact i need this :
<span class="affitta_3_span_1">
t1
</span>
2 - manage Hyperlink History token
I put my internal links such Hyperlink affitta_3_span_1=new Hyperlink(result.get(i)[1], "article/"+result.get(i)[0]) but i don't know how to get the parameter on token when they call the onValueChange() function. How can I do it?
Cheers

Use an Anchor. The output is just an <a> tag that has no <div> or <span> around it, but if you need a <span> you can add it with an HTML panel.
To set a URL that history can access, just put a # at the beginning. Something like
myAnchor.setText(result.get(i)[1]);
myAnchor.setUrl("#article/"+result.get(i)[0]);
Now, when you click myAnchor, onValueChange will be passed the token "article/whatever". The unfortunate side effect is that your urls look like http://example.com/#article/whatever, but that's the only way to get the token to the History object with just GWT.

For the first question, use an Anchor since it's inlined.
For the second one, you need to 'listen' to history change events by extending ValueChangeHandler and calling History.addValueChangeHandler(this); in your class. For example,
class MyClass implements ValueChangeHandler<String> {
public MyClass {
...
History.addValueChangeHandler(this);
}
#Override
public void onValueChange(ValueChangeEvent<String> event) {
String token = event.getValue();
if (token.equals("foo")) {
// go to one page
} else if token.equals("bar")) {
// go to another page
}
}
}

If you only need a ClickHandler on your link and no history support, you can use the Anchor widget, which is based on an <a> tag that has display: inline by default.

Related

How to render a template from controller within template -- Java, Play 2.1

Is it possible to call a controller method to render a template within a template?
Or is that totally the wrong aproach?
In the div container there is only a sting displayed but not the redered html from my productTable template.
The displayed string inside the <div class="products">:
SimpleResult(200, Map(Content-Type -> text/html; charset=utf-8))
Template:
#categories.map {cat =>
<div>some html</div>
<div class="products">#controller.Products.getByCatergoyId(cat.id)</div>
}
Controller:
public static Result getByCatergoyId(Long catId) {
List<Product> products = Product.find.where().eq("category.id", catId).findList();
return ok(views.html.display.productTable.render(products));
}
If you want to get the code from the productTable view your method shouldn't return a Result but just a String containing rendered code.... aaaannnyyyyway , there is definitely much better way for rendering sub-templates in Play, check the Tags section of the documentation it does exactly what you want directly from the view, of course you will need to pass a product object to it.
Just create tags package in your view package and add there your sub-template (responsible for rendering only pat of page) it behaves exactly the same as common template.

In a GWT HTML widget displaying complex HTML, how do I add an event handler for specific subelements?

I'm optimizing a GWT application that previously used a variety of nested panels to work with DIVs and Spans. I generate the entire table as a single SafeHtml object and then assigning it into a single SafeHtml widget.
I now want to be able to track mouseover/mouseout events at the level of the specific 'cell' spans rather than the entire table, but I'm not sure how to do this.
If I add a handler to the HTML widget itself, I'll get events sourced at various elements.
Since 2.0 there is quite a simple way to do it.
For example if you HTML code is contained in some kind of widget (HTMLPanel or HTML), you can calladdDomHandler(<handler>,<eventtyoe>) on that widget, so you will receive events from inner html.
For example if you have a bunch of anchors inside HTMLPanel and you want to know which one was clicked you can do something like this:
panel.addDomHandler(new ClickHandler() {
#Override
public void onClick(ClickEvent event) {
Element element= event.getNativeEvent().getEventTarget().cast();
if(element.getTagName().equals("A")) {
AnchorElement anchor = element.cast();
Window.alert("Anchor with href " + anchor.getHref() + " was clicked");
}
}
}, ClickEvent.getType());
Since you want to track mouseover/out events you will have to use 2 different dom handlers, find out cell you need when event is fired and then change its state.
The way to approach this is:
Find the element you need with one of the DOM methods, like DOM.getElementById(..) or any other means. View Widget.getElement() etc.
Call DOOM.sinkEvents(element,eventBits) or DOM.sinkBitlessEvent(element,eventName) and pass the required events you want to sink in form of a bitmask, like Event.MOUSEEVENTS or using a named event like click or touchstart if using the second method.
set and EventListener on the element, by calling DOM.setEventListerner(element,eventListener) like so:
DOM.setEventListener( element, new EventListener()
{
#Override
public void onBrowserEvent( Event event )
{
if ("click".event.getType()) {
// ..do stuff..
}
}
} );
Only events you've specified in step 2 will be fired to your EventListener, so you need to only handle those.

calling a child page component from parent page component in wicket

I have a problem which I tried to explained in the Image.I hope that will help all to understand what I need.
My Base Page is like this (menuNavPanel is the tree panel):
<div class="colContainer">
<div class="leftColumn" >
<div wicket:id="menuNavPanel"></div>
</div>
<div class="rightColumn">
<wicket:child/>
</div>
</div>
And Ny BIA Page which is a child of Base Page is like this:
<wicket:extend>
<div wicket:id="bodyPanel"></div>
</wicket:extend>
in my Tree Panel, when I click on a node the code is this:
#Override
protected void onNodeLinkClicked(AjaxRequestTarget target, TreeNode node) {
super.onNodeLinkClicked(target, node);
DefaultMutableTreeNode treeNode = (DefaultMutableTreeNode)node;
Unit unitObject =(Unit) treeNode.getUserObject();
// I want to call bodyPanel fo child page passing the unitObject param
}
Now, How can I call bodyPanel fo child page passing the unitObject param from the tree panel of the parent page?
Am I been able to express my problem? Hoping to get some help :)
Instead of doing the override method, upgrade to Wicket 1.5 and utilize the new event bus to communicate between your components. You can create a custom, type-safe, event that is specific to your component's use case: for example "ItemAddedToShoppingCart" or "GlobalThermoNuclearWarStarted".
The linked article in the 1.5 migration guide provides enough information on how to set up things.
I'm not sure I understand que question correctly. Your BasePage defines a left column with the TreePanel and lets subclasses expand themselves inside the right column div. You usually put a BodyPanel inside BasePages's subclasses. And now you want to invoke a BodyPanel's method on some event on the TreePanel.
You could do it with an overridable method on BasePage, which would be called in TreePanel through getPage(). Your child pages would override that method, and its implementation would call the BodyPanel they're holding.
public class BasePage ... {
// Hook
public void treePanelSelected(Object someObject) { }
...
}
public class ChildPage extends BasePage ... {
BodyPanel bodyPanel;
#Override
public void treePanelSelected(Object someObject) {
bodyPanel.selectionChanged/(someObject);
}
...
}
public class TreePanel ... {
...
#Override
protected void onNodeLinkClicked(AjaxRequestTarget target, TreeNode node) {
super.onNodeLinkClicked(target, node);
DefaultMutableTreeNode treeNode = (DefaultMutableTreeNode)node;
Unit unitObject =(Unit) treeNode.getUserObject();
((BasePage)getPage()).treePanelSelected(unitObject);
}
}
From my ignorance on your specific needs and details of implementation, I don't see why is subclassing the BasePage necessary. You could add the BodyPanel right there in the BasePage and control it from the same class.
Thanks all, After reviewing all the nice options I finally opted out for the event bus way defined by martijn. What I did is I have created an event payload and connected the panels for the talking. I also needed to pass the selected Id / entity to the receiving panel.
Is there a way to set a compound property model of the receiving panel according to the model of the tree element so that I don't need to do the model manually ?
I did like this for the time being:
public class TreeNodeClickUpdate {
private final AjaxRequestTarget target;
private final long selectedId;
/**
* Constructor
*
* #param target
* #param selectedId
*/
public TreeNodeClickUpdate(AjaxRequestTarget target, long selectedId)
{
this.target = target;
this.selectedId = selectedId;
}
/** #return ajax request target */
public AjaxRequestTarget getTarget()
{
return target;
}
public long getSelectedId() {
return selectedId;
}
}
On the sender side I've done like this:
send(getPage(), Broadcast.BREADTH,
new TreeNodeClickUpdate(target, unitObject.getId()));
And on the receiving end I got it like this:
#Override
public void onEvent(IEvent<?> event) {
super.onEvent(event);
if (event.getPayload() instanceof TreeNodeClickUpdate)
{
TreeNodeClickUpdate update = (TreeNodeClickUpdate)event.getPayload();
setSelectedId(update.getSelectedId()); //sets to id field of panel
update.getTarget().add(this);
}
}
and for just as an example in my receiving panel, to get the value I have created a label like this:
label = new Label("label",new PropertyModel<BiaHomePanel>(this,"selectedId"));
Later, in reality I want to get information from the entity and show in form. Is there a nice way to pass models in a better way or I should pass as a parameter in event payload.
There are two ways to do this. One is cleaner, but requires more code. The other is quick and dirty.
Method 1: (Good)
Since your parent page is being extended, you can provide an abstract method in the parent like
protected abstract WebMarkupContainer getBodyPanel();
that is implemented in your child page and returns the appropriate panel. Then, you can call that method from the panel in your parent page. This is similar to the overrideable method suggested by the other user.
Method 2: (Bad)
The Wicket Component Hierarchy is shared between the parent and child pages. So, if you make sure that your bodyPanel has a unique wicketId and is added directly to the root of the page, you can probably just call
get("bodyPanelId");
and it will return the proper panel.
When I was facing the problem, I thought of two ways to solve this (pre 1.5):
a) implement a variation of the observer pattern to notify other component of events like outlined here: Realising complex cross-component ajax actions in wicket - The observer way
b) using wicket visitors to traverse the component tree doing the same.
I decided to go for variant a) but this introduces coupling from your component to your page-implementation which leads to problems when testing panels on their own. So maybe b) might be the better idea but since my application is running quite smoothly with a) implemented and the next big step will be switching over to 1.5 and the event bus, I haven't yet tried b).

Submit PartialView

I have a masterpage that render's the following PartialView:
<% Html.RenderPartial("AddPage); %>
AddPage Controller looks like this:
public class PagController : Controller
{
[HttpGet]
public PartialViewResult AddPage()
{
return PartialView();
}
[HttpPost]
public PartialViewResult AddPage(FormCollection forms)
{
//some logic here
// some view data here
return PartialView();
}
}
And the view looks like this:
<% using (Html.BeginForm("AddPage", "Page", FormMethod.Post, new { ID = "PageManager" })){%>
<%= Html.TextBox("txtAddPage") %>
<input type="submit" value="AddPage" />
<%} %>
My issue is, that when i hit submit i get redirect to : http://localhost:1234/Page/AddPage, when instead i just want the partialview to be submitted, and return some basic view data if needed, as well as stay on the same page.
Am i having a blonde moment here? cause i know i have done this before
EDIT - This partial view is rendered in multiple pages, not just one.
Fullpage postback solution
This is a bit tricky since you have to know where to go back. I suggest you change your view and add two additional hidden fields (or one and parse its value - as you wish) and store current controller/action values in it.
You can then use this data in POST action to return a RedirectResult like:
return RedirectToAction("action_from_field", "controller_from_field");
Ajax postback solution
You can always submit your data using Ajax in which case your postback URL can be anything you want. In your case it should be to the current page URL. Edit: And Ajax would be the preferred solution in your particular case.
If you want to submit and only reload part of your page, you'll need to use AJAX. The most basic way to do this would be to render the partial view in an UpdatePanel.

Adding a click handler for an html element?

I have a page pregenerated for me using html, it looks like a scrollable list of divs, something like:
<html>
<div id="a">
<div>Item A</div>
</div>
<div id="b">
<div>Item B</div>
</div>
</html>
I'd like to grab them in my entry point method, and add a click handler to each. I can't figure out how to do that. I have something like:
public void onModuleLoaded() {
RootPanel rp1 = RootPanel.get("a");
rp1.addClickHandler(...); // can't do this.
}
how can I listen for a click on one of those items in GWT? Is there a way I can just install a global click handler and just watch for the ID of clicked items and filter on that? I don't necessarily need to add a click handler for each element (and I think the docs recommend against this if you have many elements which require click handlers),
Thanks
Thanks
I haven't tested this, but the general idea is right, and easy enough to extend for more than one target element. You might like to store the elements returned by DOM.getElementById() beforehand to keep things fast. Bear in mind that onPreviewNativeEvent() will be called for every user event, so keep it light.
Event.addNativePreviewHandler(new NativePreviewHandler() {
public void onPreviewNativeEvent(NativePreviewEvent event) {
if (Event.as(event).getTypeInt() == Event.ONCLICK &&
DOM.isOrHasChild(DOM.getElementById("A"), Element.as(event.getEventTarget()))) {
// Element 'A' was clicked.
}
}
}
The problem using wrap() is that if the parent element is already a widget, the wrapping is not allowed. You can still do it and will work, but if you run the application in development mode the assertion will fail, stopping the application.
The right (but tedious and in my opinion incomplete) way is something like
Element elem = DOM.getElementById(“billing-component”);
DOM.sinkEvents(elem, Event.ONCLICK | Event.ONMOUSEOUT | Event.ONMOUSEOVER);
DOM.setEventListener(elem, new EventListener() {
#Override
public void onBrowserEvent(Event event) {
if (Event.ONCLICK == event.getTypeInt()) {
…
}
}
});
I know doesn't look nice, and actually it isn't because you can only attach a single listener to the element and have to check for the event type.