Thymeleaf - if checked do something - thymeleaf

I have a simple table and I have checkbox inside that table. If checkbox is selected I want to display other features.
My code:
<table>
<tr th:each="obj,iterationStatus : ${objs}">
<td th:text="${obj.name}"></td>
<td><input type="checkbox" name="firstcheckbox"></td>
<td th:if="isChecked">
<!-- do something -->
</td>
</tr>
</table>
How I do this without using javascript and backbean?

In this case you have two options, the first option you don't want but is not a bad option is using Javascript: creating a function called isChecked.
Otherwise, you can know if a checkbox is checked with thymeleaf in the case you are in a form which calls itself. You could do something like if(firstcheckbox != null) and, of course, your checkbox would have a value <input type="checkbox" name="firstcheckbox" value="value">. Finally, you must add as attribute in your model: model.addAttribute("firstCheckbox", firstCheckbox);

Related

Pagination resets checkbox of rows

I have a GSP containing some rows with an checkbox which lets the user select several rows.
<table>
<thead>
<tr>
// Column headers
</tr>
</thead>
<tbody>
<g:each in="${itemList}" status="i"
var="instance">
<tr class="${(i % 2) == 0 ? 'even' : 'odd'}">
// Some other rows
<td>
<g:checkBox name="selected"
value="${instance.id}"
checked="false" />
</td>
</tr>
</g:each>
</tbody>
And a pagination under my table:
<div class="pagination">
<g:paginate total="${total}" params="${params}"/>
</div>
Now the problem is when I switch from Page 1 -> Page 2 -> and then back to Page 1 all the checkboxes from Page 1 are reseted.
As pagination calls the list controller method I checked the following on page switch by Watching the following in Debugger when list controller method gets called:
params.list('selected')
But unfortunately the list is empty.
Pagination does not submit a form (or at least not like you're thinking it does; I really don't remember if the underlying logic uses a form or not) so your checkboxes are not being submitted to anywhere.
You need to consider different approaches for having your form submitted so that your checkbox selections are persisted. Two approaches could be:
Write your own pagination tag that wraps g.paginate and modifies which params are sent so that your checkbox values are included.
Add ajax handling to your checkboxes so that they are submitted immediately when changed.

Capybara: Pulling in multiple Radio button options

Im running into an issue, and I think the issue is with how my page.all is pulling radio button questions in.
So here is the HTML for the table itself (Multiple questions with 5 radio button choices a piece):
<table class="table table-striped table-stuff table-collapsible">
<colgroup>
<thead>
<tbody>
<input id="0_answer_question_id" value="9966" name="response[answers][0][answer_id]" type="hidden">
<tr>
<td class="heading">
<td class="option">
<div class="radio-inline radio-inline--empty">
<input id="question_1_1" value="1" name="response[answers_attributes][0][answer_opinion]" type="radio">
<label for="question_1_1">Strongly Disagree</label>
</div>
</td>
<td class="option">
<td class="option">
<td class="option">
<td class="option">
</tr>
<input id="response_1_question_id" value="9966" name="response[answers_attributes][1][answer_question_id]" type="hidden">
<tr>
<input id="response_1_id" value="<a number>" name="response[answers_attributes][1][id]" type="hidden">
<Same as above repeated 5 times with numbers changed>
</tbody>
</table>
Im using:
page.all('table.table-stuff tbody tr', minimum: 6).each do |row|
row.all("td label").sample.trigger('click')
end
To get each row and select one from it. HOWEVER, I notice "sometimes" a row will not have one selected. My theory is the "heading" (which has a <label> itself is accepting one of the clicks perhaps? (since from my understanding of how page.all works it's grabbing every tbody tr within the table...but is maybe grabbing the heading too? (since it contains a td label?)
Also when a table is named something like table table-striped table-stuff table-collapsible...how can you tell what the actual table "name" is? (I didn't write this website, just doing tests for it). When putting it in the page.all('table.<etc>')?
If the heading td (it's not expanded in your example) also contains a label element (so it would be included in the results of your all call) then you just need to change the CSS selector so it wouldn't be included - something like
row.all("td.option label").sample.trigger('click') # only choose labels contined in tds with the class of 'option'
or
row.all("td:not(.heading) label").sample.trigger('click') # choose labels contained in tds without the class of 'heading'
On your second question about table names, I don't really understand what you're asking. Tables don't have name attributes, they could have an id attribute or a caption containing some text which could then be used to find them with capybara via find(:table, 'id or caption text') or within_table('id or caption text') { code to execute within scope of the table }. Rather, you seem to be talking about the classes on the element which are specified in a CSS selector with '.'. Therefore a CSS selector to match a table element with all the classes you listed would be - 'table.table.table-striped.table-stuff.table-collapsible'
Note: If you're sure there's always only 5 choices you could add the :count option to your find to make sure your selector is only finding those items
row.all("td.option label", count: 5).sample.trigger('click')

Struts2 based quiz application using DB for getting questions and storing results

jsp file
<s:iterator value="questions" status="status">
<table border="3px" bgcolor="yellow">
<tr bgcolor="white" >
<td nowrap><s:property value="QuestionNumber"/></td>
<td nowrap><s:property value="Question"/></td>
</tr>
<tr>
<td nowrap><input type="radio" name="<s:property value="QuestionNumber"/>" value="1"/><s:property value="Option1"/></td>
<td nowrap><input type="radio" name="<s:property value="QuestionNumber"/>" value="2"/><s:property value="Option2"/></td>
</tr>
<tr>
<td nowrap><input type="radio" name="<s:property value="QuestionNumber"/>" value="3"/><s:property value="Option3"/></td>
<td nowrap><input type="radio" name="<s:property value="QuestionNumber"/>" value="4"/><s:property value="Option4"/></td>
</tr>
</table>
<s:hidden> </s:hidden>
</s:iterator>
<s:hidden id="answers" value="answers"/>
<s:submit name="submit" onclick="submitform()"/>
</s:form>
property values are being populated from DB using the Action class.
My problem is that i want to collect the list answers for a quiz and get it to the java classes for evaluation of score. Im not able to get any idea as how to do it
My DB has Questions table with the list of questions with options and correct answer.
I have a Question Bean Object.
You have an Action with a private List<Question> questions;, with Getter and Setter.
You populate your JSP reading the list from the Getter.
You can post that list back from the JSP to the Action's Setter by using OGNL for keeping informations on lines detail.
To do this, use Struts tags (<s:radio instead of <radio ) and set a name including the index of the line.
For example, with a textfield, instead of
<s:iterator value="questions" status="status">
<s:textfield name="question" />
</s:iterator>
use something like (untested, maybe some adjustments needed)
<s:iterator value="questions" status="status">
<s:textfield name="questions[%{#status.index}].question" />
</s:iterator>
Just adapt this for your radio case,
and in the Action you will receive your List fully populated.
(You can even validate a list posted like this usign Visitor validator: not your case, but it's worth knowing).
there are many ways to do this. the easiest way is to implement ParameterAware, checkout the link ParameterAware, then you can get all your parameters like this: (I'm assuming, QuestionNumber is a parameter of your bean question)
String param1 = parameters.get(question.getQuestionNumber);
you can put this line in a loop, so you can get all your parameters...

grails select with remoteFunction, can it update a g:textField?

I need to update the value of a textField, using a value on the server, based on the value the user chooses in a g:select. In code:
<g:select name="description" from="${momentum.MoneyTransType.prodList}" value="${moneyInstance?.description}"
noSelection="['':'-Select Description-']" onChange="${remoteFunction(action:'setHowMuch', update:[success:'howMuch', failure:'failure'],
params:'\'selection=\' + this.value', options=[asynchronous:false])}"/>
<g:textField id="howMuch" name="howMuch" value="${moneyInstance?.howMuch}"/>
It's not working. If I give the "update:[success:" a div id, all is good, but that's not what I want. I need to allow the user to enter in a free flow description (which I'll have in another textfield), and a free flow amount. I guess I could hide a div and then listen for changes to that div via jQuery, and then update the amount textField. Should I be able to update a textField using the remoteFunction "update" capability or using another grails capability?
Strangely, putting in a temporary 'toHide' div with a jQuery change function isn't working to update the textField, i.e. the following alert, etc, isn't firing:
$('#toHide').change(function() {
alert(" I got changed, value:");
$("#howMuch").text($(this).val());
});
Well, after writing all the below, I reread your question and see you stated you know it works with a div. So the rest of my answer might not be helpful, but what's wrong with using a div? An empty div won't display anything, so you don't need to hide it. So FWIW:
Put your <g:textField ...> in a template.
Add a div where where you want the template to be rendered. In other
words, replace the current <g:textField ..> with <div id=updateme name=updateme></div>
In your setHowMuch action, render the template.
For example, I do:
In view:
<g:select class='setTagtypeValue-class'
name='tagtype-${i}-header'
from="${org.maflt.ibidem.Tagtype.list(sort:'tagtype').groupBy{it.tagtype}.keySet()}"
value="${setTagtypeValue?.tagtype?.tagtype}"
valueMessagePrefix="tagtype"
noSelection="${['null':'Select One...']}"
onchange="${remoteFunction(action:'options', update:'tagtype-options-${i}',
params:'\'tagtype=\' + this.value +\'&i=${i}\'' )}" />
Controller action:
def options = {
def i = params.i ?: 0
def tagtypes = Tagtype.findAllByTagtype(params.tagtype)
render(template:"tagtypeList", model:[tagtypes:tagtypes,i:i])
}
tagypeList Template:
<table>
<tr>
<th></th>
<th><g:message code="tagtype.lookup"
default="Lookup Table" /></th>
<th><g:message code="tagtype.regexpression"
default="Field Rule" /></th>
<th><g:message code="tagtype.uicomponent"
default="UI Component" /></th>
</tr>
<g:each in="${tagtypes}" var="tagtype" status="j">
<tr>
<td><g:radio name="setTagtypesList[${i}].tagtype.id" value="${tagtype.id}"
checked="${(setTagtypeValue?.tagtype?.id == tagtype.id ||
(!setTagtypeValue?.tagtype?.id && j==0))}"></g:radio></td>
<td>${tagtype.lookupTable}</td>
<td>${tagtype.regexpression}</td>
<td><g:message code="${'uicomponent.' + tagtype.uicomponent.id}"
default="${tagtype.uicomponent.uicomponent}" />
</td>
</tr>
</g:each>
</table>
This code is from the metadataset (called field set in the UI) screen in http://www.maflt.org/products/Ibidem.

How do I save a composite field value in Grails GSP?

I have a composite domain object as follows:
class Person
{
static embedded = ['forSale']
Boolean isSelling
House forSale
}
class House
{
Integer numBedrooms
}
I have a select control for the numBedrooms as follows:
<tr class="prop">
<td valign="top" class="name">
<label for="numBedrooms"><g:message code="person.numBedrooms.label" default="Num Bedrooms" /></label>
</td>
<td valign="top" class="value ${hasErrors(bean: personInstance, field: 'forSale.numBedrooms', 'errors')}">
<g:select name="numBedrooms" value="${fieldValue(bean: personInstance, field: 'forSale.numBedrooms')}"
noSelection="${['null':'Select a number...']}"
from="${1..6}"
/>
</td>
</tr>
Notice that I am using forSale.numBedrooms in the fieldValue on the select. I haven't been able to produce scaffolded code for this to take a look at how it is supposed to be done because the create view which gets generated by create-views contains no references to the fields in the forSale House object.
I also haven't been able to turn up any exampes of composite fields being accessed via GSP, so this is a bit of a guess. In any case the GSP page renders without errors, although that may be because I haven't been able to save any data.
I send the value of numBedrooms back as part of a URl query string...
&numBedrooms=2
When I do this the save code in my controller is failing silently - at least nothing ever gets written to the database. I have switched on debug logging for pretty much everything but I get no messages in the log which suggest anything is wrong, although something obviously is.
If I remove the numBedrooms parameter from the query string then my save proceeds as normal, so I am guessing it is something to do with resolving numBedrooms.
Any clue what I am doing wrong and what I can do to track down my problem?
What I do is generate-all for the House Domain then copy and paste the GSP code and remove the files once I am done. I have also found it smarter to create templates to edit the House domain in the case where I am using the House domain later on.
For you GSP you need something like this (Notice the name attribute)
<tr class="prop">
<td valign="top" class="name">
<label for="forSale.numBedrooms"><g:message code="house.numBedrooms.label" default="Num Bedrooms" /></label>
</td>
<td valign="top" class="value ${hasErrors(bean: personInstance.forSale, field: 'numBedrooms', 'errors')}">
<g:select name="forSale.numBedrooms" value="${fieldValue(bean: personInstance.forSale, field: 'numBedrooms')}"
noSelection="${['null':'Select a number...']}"
from="${1..6}"
/>
</td>
</tr>
In your param string you need *forSale*.numBedrooms=2. this code will work with person.properties = params or new Person(params).
The embedded "instruction" only tells Hibernate to include the parameters in the same table they are still seperate Domain classes. It will probably generate a table for the domain even though you may never use it.
Hope this helps.

Resources