playframework call Model method from view javascript
-
27-10-2019 - |
Question
Like in play tutorial for the Tags Set (customize crud field); i want to add a new functionality when user selects a tag then javascript should get current user (models.user) and call a method user.doSomething(). is this possible to do in a CRUD custom field ? (like in tutorial for yabe tags?).
is there a way I can make a custom CRUD field as a list of checkboxes and when user check some checkboxes then i should write code (maybe javascript) that gets current logged in user and then call a method on that user Model?
thanks.
Solution
Here is the example from the play tutorial (customize crud field). i suppose that you want to execute an action when a tag is clicked. that can be done simply as shown below
#{crud.form}
#{crud.custom 'tags'}
<label for="tags">
&{'tags'}
</label>
(...)
<div class="tags-list">
#{list items:models.Tag.findAll(), as:'tag'}
<span id="${tag.id}" onclick="toggle(this)" class="tag ${object.tags.contains(tag) ? 'selected' : ''}">
/**** ADD An ACTION CALL HERE ******/
<a href="@{Application.getConnected().doSomething()}">${tag}</a>
/**** END *****/
</span>
<input id="h${tag.id}" type="hidden" name="${fieldName}"
value="${object.tags.contains(tag) ? tag.id : ''}" />
#{/list}
</div>
#{/crud.custom}
#{/crud.form}
you have to implement the method getConnected() by your self in you controller (maybe Application.java). supposing that you use the Secure Module it will be something like
void getConnected(){
if(Security.isConnected()) {
User user = User.find("byEmail", Security.connected()).first();
renderArgs.put("user", user);
}
}