I got a question here regarding Wicket and jQuery. I got a WebPage which is rendered and shown by Wicket. Within this page I got one "draggable" and one "droppable" component, in which the user should be able to move components. This is realized via jQuery. Additionally I got a "Save" button at the end of the WebPage, which should save the new values (if there are any), which means: the newly dropped items. But if I click on "Save" I don't see the newly dropped objects within Wicket, I still just see the objects which have been in the "droppable" area from the beginning on. Here some Code snippets:
HTML:
<div class="container">
<div id="user">
<h1 class="ui-widget-header">Benutzer</h1>
<div class="ui-widget-content" id="userList">
<input type="text" placeholder="Benutzername" id="userNameSearch" />
<ul class="list-group">
<li class="list-group-item" wicket:id="userList"><span
wicket:id="user" id="user"></span><span style="visibility: hidden;" wicket:id="userId" id="userId"></span></li>
</ul>
</div>
</div>
<div id="project">
<h1 class="ui-widget-header">Benutzer im Projekt</h1>
<div class="ui-widget-content" id="project">
<ul class="list-group">
<li class="placeholder list-group-item"><span>Benutzer
in dieses Feld ziehen.</span></li>
<li class="list-group-item" wicket:id="usersInProjectList"><span
wicket:id="userInProject"></span><span style="visibility: hidden;" wicket:id="userInProjectId"></span></li>
</ul>
</div>
</div>
<button id="save" wicket:id="save">Speichern</button>
</div>
<script>
$(function() {
$("#userList li").draggable({
appendTo : "body",
helper : "clone"
});
$("#project ul")
.droppable(
{
activeClass : "ui-state-default",
hoverClass : "ui-state-hover",
accept : ":not(.ui-sortable-helper)",
drop : function(event, ui) {
$(this).find(".placeholder").remove();
var userName = ui.draggable.find("#user").text();
var userId = ui.draggable.find("#userId").text();
$("<li class=\"list-group-item new-project-member\" wicket:id=\"usersInProjectList\"><span wicket:id=\"userInProject\">"+userName+"</span><span style=\"visibility:hidden;\" wicket:id=\"userInProjectId\">"+userId+"</span></li>")
.appendTo(this);
$(ui.draggable).remove();
}
}).sortable({
items : "li:not(.placeholder)",
sort : function() {
// gets added unintentionally by droppable interacting with sortable
// using connectWithSortable fixes this, but doesn't allow you to customize active/hoverClass options
$(this).removeClass("ui-state-default");
}
});
$('#userNameSearch')
.keyup(
function() {
var valThis = $(this).val().toLowerCase();
if (valThis == "") {
$('#userList li').show();
} else {
$('#userList li')
.each(
function() {
var text = $(this)
.text()
.toLowerCase();
(text.indexOf(valThis) >= 0) ? $(
this).show()
: $(this)
.hide();
});
}
;
});
});
</script>
Java Code (Wicket):
ListView userListView = new ListView("userList", finalUserList) {
protected void populateItem(ListItem item) {
User user = (User) item.getModelObject();
item.add(new Label("user", user.getLastname()+", "+user.getFirstname()));
item.add(new Label("userId", user.getId()));
}
};
ListView usersInProjectListView = new ListView("usersInProjectList", usersInProjectList) {
protected void populateItem(ListItem item) {
User user = (User) item.getModelObject();
item.add(new Label("userInProject", user.getLastname()+", "+user.getFirstname()));
item.add(new Label("userInProjectId", user.getId()));
}
};
usersInProjectListView.setOutputMarkupId(true);
add(new AjaxLink<Void>("save")
{
#Override
public void onClick(AjaxRequestTarget target)
{
System.out.println(target.getPage().get("usersInProjectList"));
//window.close(target);
}
});
add(userListView);
add(usersInProjectListView);
You could somehow get the changes from the client to the server, for example using Ajax. You can fire a callback function that can be added via AbstractAjaxBehaviour (see detail here), or maybe switch to wicket-dnd
Related
I am implementing a messanger using Jax-Rs. I have a client application which use the implemented API. within the database message_id,message,date, sender fields are stored. I need to display these values within a div of jsp page of the client application.
client.jsp
<form action="ClientServlet" method ="post" onclick="onTechIdChange();"></form>
<div id="uploadSuggest" class="center-block">
<div id="suggestHeading" class="row">
<h4 class="textTitle center-block"> Messages </h4>
</div>
<div class="row">
<div class="col-md-8">
<a id="btn_padding" href="#download" class="btn btn-image pull-left" onclick="onTechIdChange();">Create Profile</a>
<p> </p>
</div>
</div>
</div>
</div>
</section>
<script>
function onTechIdChange() {
var urlPath = "http://localhost:8081/messanger/webapi/messages" ;
$.ajax({
url : urlPath,
dataType : "json",
cache: false,
type : 'GET',
success : function(result) {
var details = result[0];
var name;
for(name in details)
{
dispatchEvent(event)
}
alert(details.sender);
},
error : function(jqXHR, exception) {
alert('An error occurred at the server');
}
});
function display(msg) {
var p = document.createElement('p');
p.innerHTML = msg;
document.body.appendChild(p);
}
}
</script>
Through this code nothing is displayed in the div. But values are printed in the tomcat console which ensures that all the methods within API are working properly. Do you have any idea? Thank you in advance
UPDATE
I Updated the javascript code snippet. But nothing is displayed inside the <p> tag
var urlPath = "http://localhost:8081/messanger/webapi/messages" ;
$.ajax({
url : urlPath,
dataType : "json",
cache: false,
type : 'GET',
success : function(result) {
var details = result[0];
var name;
for(name in details.sender)
{
display(name);
}
alert(details.sender);
},
error : function(jqXHR, exception) {
alert('An error occurred at the server');
}
});
function display(msg) {
var p = document.createElement('p');
p.innerHTML = msg;
document.body.appendChild(p);
}
}
This is the section with the <p>
<form action="ClientServlet" method ="post" onclick="onTechIdChange();"></form>
<div id="uploadSuggest" class="center-block">
<div id="suggestHeading" class="row">
<h4 class="textTitle center-block"> Messages </h4>
</div>
<div class="row">
<div class="col-md-8">
<a id="btn_padding" href="#download" class="btn btn-image pull-left" onclick="onTechIdChange();">Create Profile</a>
<p> </p>
</div>
</div>
</div>
</div>
</section>
If somebody knows a tutorial regarding this can you upload a link?
I think you are not calling the display function that add the values to the DOM.
for(name in details){
display(name)
}
Also I am not sure that your parser is correct
success : function(result) {
var details = result[0]; -- Extract the first value of response
var name;
for(name in details) --- should be an array as well
{
dispatchEvent(event) -- I think here you need to call print function
}
alert(details.sender); -- If details.sender have the details probably the
iteration should be for(name in details.sender)
},
Also I reconsider the use of $.ajax, probably use $.get is better and also, use jsp I dont think is needed use a simple html with a javascript.
I сreated a jsp page with the table. I would like to refresh table after click the button using Jquery.
But in result i see two views at the same time. How to avoid this problem ?
My Controller
#Controller
#RequestMapping("/")
public class HelloController {
private final Logger log = LoggerFactory.getLogger(getClass());
#Autowired
private UserServiceDao userServiceDao;
#RequestMapping(method = RequestMethod.GET)
public String printWelcome(ModelMap model) {
model.addAttribute("Message","first");
model.addAttribute("list",userServiceDao.findAll());
log.trace("NUMBER:::::::::::::::::::::"+userServiceDao.findAll().size());
return "main";
}
#RequestMapping("/table")
public ModelAndView renderTable(HttpServletRequest request) {
String name = request.getParameter("nameSearch");
log.trace("1: "+name);
List<User> people = userServiceDao.find(name);
log.trace("2: "+people.size());
return new ModelAndView("main", "list", people);
}
}
MY view with the Jquery script
<body>
<div class="sear">
<input class=" int datasearch" type="search" value="an" id="dataSearch">
<input class="int search" type="button" value="Search" id="search">
<input class="int create" type="button" id="err" value="Create user">
</div>
<h1>List of users: </h1>
<div class="table" >
<c:forEach var="item" items="${list}">
<div class="row" >
<div id="tabl" class="cell" style="width:300px;"><c:out value="${item.name}"/>></div>
<div class="cell" style="width:100px;" ><input class="delete" type="button" value="Delete user"></div>
<div class="cell"><input class="edit" type="button" value="Edit user"></div>
</div>
</c:forEach>
</div>
<script type="text/javascript">
$('#err').click(function(){
window.location.href='/registration';
})
$('#search').click(function(){
$(function() {
var myTableContainer = $("#tabl");
var renderTable = function(container) {
var data = $('#dataSearch').val();
var postReqData = {}; // Create an empty object
postReqData['nameSearch'] = data;
$.get("/table",postReqData, function(data) {
container.empty().html(data);
})
};
/* This is called on document ready */
renderTable(myTableContainer);
/* Use the same renderTable function when the refresh button is clicked */
$("#search").click(function() {
renderTable(myTableContainer);
});
})
})
Ok, this might be a bit too long for comments.
Your main problem is that both #RequestMapping(method = RequestMethod.GET) and #RequestMapping("/table") render the same view.
That is: the view containing all your search inputs, <c:forEach> table and javascript.
So when you do the search and when the ajax call returns, you replace contents of div#tabl with all those search inputs, <c:forEach> and javascript.
You end up with two pieces of everything nested in the wrong way.
My advice would be to do one RequestMapping that renders the basic jsp, and the other one that renders only the search results (or even returns json and render it as html in javascript).
I have this practice project that I am working on, but I cant get my UI Boostratp modal working. Using example from the site https://github.com/angular-ui/bootstrap/tree/master/src/modal I have been trying to implement this feature but without success.
I believe that this is because of that I do not have the knowledge to integrate demo code to my MVC style project (I have separate app.js, controller, and service files), and this one file example is rather confusing to me.
My folder/file structure:
Now, I have tried various things, including making a separate controller, and separate view for modal content (that's why I have bookDetailes.html and bookDetailesConreoller.js files but they are currently out of order - not connected in app.js's stat provider and their code is under comment). This is where I am:
A have a list of basic book details retrieved from data base and printed out in book.html view via data-ng-repeat. In every repeat I have an Action button that is supposed to open modal for editing or deleting that entry.
Here is my book.html file where I have nested the demo markup code from UI Bootsratp site:
<h4 class="text-center"><strong>Book Collection</strong></h4>
<br>
<table class="table table-hover">
<thead>
<tr>
<th>ID</th>
<th>Image</th>
<th>Title</th>
<th>Author</th>
<th>Year</th>
<th>Publisher</th>
<th>City of Publishing</th>
<th>Genre</th>
<th>Action
<th>
</tr>
</thead>
<tbody data-ng-init="init()">
<tr data-ng-repeat="book in books">
<td>{{book.id}}</td>
<td>{{book.image}}</td>
<td>{{book.title}}</td>
<td>{{book.author}}</td>
<td>{{book.yearOfPublishing}}</td>
<td>{{book.publisher}}</td>
<td>{{book.cityOfPublishing}}</td>
<td>{{book.genre}}</td>
<td><a class="btn btn-default" data-toggle="modal" data-ng-click="open()">Action</a></td>
</tr>
</tbody>
</table>
<div>
<script type="text/ng-template" id="myModalContent.html">
<div class="modal-header">
<h3 class="modal-title">I'm a modal!</h3>
</div>
<div class="modal-body">
<ul>
<li ng-repeat="item in items">
<a ng-click="selected.item = item">{{ item }}</a>
</li>
</ul>
Selected: <b>{{ selected.item }}</b>
</div>
<div class="modal-footer">
<button class="btn btn-primary" ng-click="ok()">OK</button>
<button class="btn btn-warning" ng-click="cancel()">Cancel</button>
</div>
</script>
</div>
As you can see, this last part after table tag is supposed to be modal markup taht is called when Action button is pressed and command "open()" i passed to bookController.js via data-ng-click.
My bookControler.js:
collectionsApp.controller('bookController', function($scope, bookService,
$state) {
var books = [];
$scope.save = function() {
bookService.save($scope.book, onSaveDelete);
}
$scope._delete = function(id) {
for (book in books) {
if (book.id === id) {
bookService._delete(book, onSaveDelete);
}
}
}
$scope.edit = function(id) {
for (book in books) {
if (book.id === id) {
$scope.book;
}
}
}
$scope.init = function() {
bookService.list(onInit);
}
// <-- Beginning of the modal controller code I inserted (and adopted) from the example:
$scope.items = [ 'item1', 'item2', 'item3' ];
$scope.open = function(size) {
modalInstance = $modal.open({
templateUrl : 'myModalContent.html',
controller : ModalInstanceCtrl,
size : size,
resolve : {
items : function() {
return $scope.items;
}
}
});
modalInstance.result.then(function(selectedItem) {
$scope.selected = selectedItem;
}, function() {
$log.info('Modal dismissed at: ' + new Date());
});
};
var ModalInstanceCtrl = function($scope, $modalInstance, items) {
$scope.items = items;
$scope.selected = {
item : $scope.items[0]
};
$scope.ok = function() {
$modalInstance.close($scope.selected.item);
};
$scope.cancel = function() {
$modalInstance.dismiss('cancel');
};
};
// <-- Ending of the modal code I have inserted from the example.
onSaveDelete = function(response) {
if (response.data.status === 'success') {
$scope.init();
} else {
alert("DEBUG ALERT: SAVE/DELETE FAIL");
}
};
onInit = function(response) {
$scope.books = response.data;
books = response.data;
};
});
Now, like this, code is working in the seance that data-ng-repeat is working and I get list of database entries on page load. But when I click on the Action button i get this error message in the console:
But when I add $modal to may code like this:
collectionsApp.controller('bookController', function($scope, bookService,
$state, $modal) {
var books = [];
...
I get this error on page load:
Can someone help me understand and implement modals to my project? Thanks in advance... ;)
Add this,
angular.module('Urapp', ['ui.bootstrap']);
I have a slight problem with my jQuery and I can't quite figure out where my problems lies, so if anyone could give me a hand with it is greatly appreciated.
I am using a jQuery function that when my #add div gets clicked, a JavaBean is called which adds the current page to the session user and when the #remove div gets clicked, a similar process is carried out that removes the current page from the user.
My problems starts when I try to check with the collection whether the current page is already associated with the user and if so display the #remove div and otherwise display the #add div.
Below is my script:
<script>
$(document).ready(function() {
$("#viewshow-text").load(function(){
if(${userShowDetails}) { <%-- this var can either be true or false depending on whether the page is associated with the user or not --%>
$('#removeshow').show(),
$('#addshow').hide();
} else {
$('#addshow').show(),
$('#removeshow').hide();
}
});
$("#add").click(function() {
$.post("addshow", {
item : "${param.show}"
}, function(data, status) {
}, function() {
<%-- hide a div and display the other --%>
$this.find('#addshow').hide(),
$this.find('#removeshow').show();
});
});
$("#remove").click(function() {
$.post("removeshow", {
item : "${param.show}"
}, function(data, status) {
}, function() {
$this.find('#removeshow').hide(),
$this.find('#addshow').show();
});
});
});
</script>
My div elements in question are as follows:
<div class="viewshow-text">
<c:if test="${!empty USER}"> <%-- only display if a user is logged in --%>
<div id="addshow" class="viewshow-button viewshowAdd-button">
<a id="add" href="#">Add to calendar</a>
</div>
<div id="removeshow" class="viewshow-button viewshowRemove-button">
<a id="remove" href="#">Remove from calendar</a>
</div>
</c:if>
</div>
I have no issues with my JavaBean properties as I double checked and they are displaying the contents expected:
$(document).ready(function() {
$(if(false) {
$('#removeshow').show(),
$('#addshow').hide();
} else {
$('#addshow').show(),
$('#removeshow').hide();
});
When the page is not in the user list.
Here try this,
<script>
$(document).ready(function() {
if(${userShowDetails}) {
$('#removeshow').show(),
$('#addshow').hide();
} else {
$('#addshow').show(),
$('#removeshow').hide();
};
$("#add").click(function() {
$.post("addshow", {
item : "${param.show}"
}).done(function(data) {
$('#addshow').hide(),
$('#removeshow').show();
});
});
$("#remove").click(function() {
$.post("removeshow", {
item : "${param.show}"
}).done(function(data) {
$('#removeshow').hide(),
$('#addshow').show();
});
});
});
</script>
I render a TextField. It's value is populated by script, not the user. I need to get that value from Java but I get null by doing textField.getInput();
Any ideas how to get that value and use it in Java code?
I had the same problem a few month ago. One problem is, that setting the input value via javascript doesn't fire the "onChange" event which you could easily use to get the value.
The solution I implemented might not be the easiest one, but it's working:
put a form with a hidden ajax submit link around your input
when you fill your input with javascript, use javascript also to do a form submit
html:
<html xmlns:wicket="http://wicket.apache.org">
<body>
<div>
<a href="#" onclick="document.getElementById('input').value = 'test'; document.getElementById('myForm').submit();">fill
input</a>
<form wicket:id="form" id="myForm">
<input type="text" wicket:id="input" id="input">
<a style="visibility: hidden;" wicket:id="submit">submit</a>
</form>
<p> Output:
<wicket:container wicket:id="output"></wicket:container>
</p>
</div>
</body>
</html>
and the corresponding java:
public class HomePage extends WebPage {
private String inputValue;
public HomePage(final PageParameters parameters) {
super(parameters);
final Label output = new Label("output", new PropertyModel<String>(
this, "inputValue"));
output.setOutputMarkupId(true);
add(output);
Form form = new Form("form");
form.add(new AjaxSubmitLink("submit") {
#Override
protected void onAfterSubmit(AjaxRequestTarget target, Form<?> form) {
super.onAfterSubmit(target, form);
target.add(output);
}
});
add(form);
form.add(new TextField<String>("input", new PropertyModel<String>(this,
"inputValue")));
}
}
Explanation:
The TextField gets an AjaxFormSubmitBehaviour with a custom event.
This event can be triggered by javascript. I use jQuery, as it is provided by Wicket anyway.
See the code:
public class Example extends WebPage
{
public Example(PageParameters pp)
{
super(pp);
final Model<String> m = new Model<String>("");
Form<Void> f = new Form<Void> ("form");
TextField<String> textField = new TextField<String>("textField", m, String.class);
textField.setOutputMarkupId( true );
textField.setMarkupId( "myuniqueid" );
textField.add( new AjaxFormSubmitBehavior("customevent")
{
protected void onSubmit(AjaxRequestTarget target)
{
System.out.println("Model value:"+m.getObject());
target.add( this.getComponent() );
}
} );
f.add(textField);
add(f);
}
}
HTML
<!DOCTYPE html>
<html xmlns:wicket="http://wicket.apache.org">
<head>
<meta charset="utf-8" />
</head>
<body>
<a href="#" onclick="$('#myuniqueid').val('test'); $('#myuniqueid').trigger('customevent');">fill
input</a>
<form wicket:id="form">
<input wicket:id="textField"></input>
</form>
</body>
</html>