How to change my view file to get a appropriate output? - grails

I have a controller like this :
def mytask = {
def user = User.findByLogin(params.id)
def mywork = user.schedules.daySchedules
[ mywork : mywork ]
}
Where I'm trying to find all the tasks assigned to a particular user. I have a corresponding view file :
<g:each in="${mywork}" var="tasks">
<div id = "todayswork">
${tasks.task}
</div>
<div id ="Dates">
${tasks.startTime}-
${tasks.endTime}
</div>
<hr/>
</g:each>
Logic works fine, I'm getting the output as I wanted. For example, if I go to http://localhost:8080/scheduleTest/daySchedule/mytask/anto my browser showing all the task for the user anto. But there is a problem in rendering it.
I'm getting the output as :
But I need the output something like this one:
How change my view file to get the appropriate output.
Thanks in advance.

It's hard to tell from your examples, but my guess is you need to be looping over the tasks item, which appears to be a List in a List.
This means change this:
<g:each in="${mywork}" var="tasks">
to this
<g:each in="${mywork[0]}" var="tasks">
// or
<g:each in="${mywork.tasks}" var="tasks">
Again, I'm not exactly sure where the problem is occurring, but one of those will fix it.
The reason you are getting the output is that Groovy will automatically perform a property expansion on a list if the property is not defined on that list. Example:
use(org.codehaus.groovy.runtime.TimeCategory) {
def d1 = 5.minutes.ago
def d2 = 1.week.from.now
assert [d1, d2].time == [d1.time, d2.time]
}
It's the same thing as writing list*.property, and returns a new list containing each property on the original items.

Related

RAZOR variable in variable

Hi i have a little question about razor ...
I need to send an email with multiple article bought by a client
I made a for-loop to generate one line per article.
But each line need to show different name for each product
Example if the client bought 3 articles :
Line 1 : Article_1
Line 2 : Article_2
Line 3 : Article_3
But actually my loop only shows Article_1 for each Line
![examle][1]
Anyone know how to replace the "X" according to "i" ?
#{
var i = 0;
}
<!-- SOME HTML -->
#for(i=1 ; i < Convert.ToInt32(NB_PRODUCT); i++){
<tr>
<td>TITLE_X</td>
<td>PRICE_X</td>
</tr>
}
In my database i can have a lot of products to display (each tr = 1 product)
Here an example of database
You must load the data from your database in your controller or model, into objects like lists (or arrays) first.
Then once you have a list or array you can actually go through it in the HTML.
your code should look kinda like this (note: not literally):
you should provide the code where you read your DB, so lets just asume that part
Controller:
string[] ArraywithTitles = //your DB data for Titles (the column Article1)
string[] ArraywithPrices = //your DB data for price1
ViewBag.TITLE_X = ArraywithTitles;
ViewBag.PRICE_X = ArraywithPrices;
The contents of your array should be (if you were to read them, do not set them manually):
ArraywithTitles[0] = "t-shirt";
ArraywithTitles[1] = "t-shirt";
ArraywithTitles[2] = "pants";
//View
#for(i=1 ; i < Convert.ToInt32(NB_PRODUCT); i++){
<tr>
<td>#TITLE_X[i]</td>
<td>#PRICE_X[i]</td>
</tr>
now if you want the different articles, you need to have all of them in arrays or lists
//note: you must add ifs (or a switch case) for each NB_Product case,
//this is only for when a client has 3 products
#for(i=1 ; i < Convert.ToInt32(NB_PRODUCT); i++){
<tr>
<td>#Article1[i]</td>
<td>#PRICE1[i]</td>
<td>#Article2[i]</td>
<td>#PRICE2[i]</td>
<td>#Article3[i]</td>
<td>#PRICE3[i]</td>
</tr>
if you need further assistance (or a more literal solution), you should provide your controller and model code as well.

How to show String new lines on gsp grails file?

I've stored a string in the database. When I save and retrieve the string and the result I'm getting is as following:
This is my new object
Testing multiple lines
-- Test 1
-- Test 2
-- Test 3
That is what I get from a println command when I call the save and index methods.
But when I show it on screen. It's being shown like:
This is my object Testing multiple lines -- Test 1 -- Test 2 -- Test 3
Already tried to show it like the following:
${adviceInstance.advice?.encodeAsHTML()}
But still the same thing.
Do I need to replace \n to or something like that? Is there any easier way to show it properly?
Common problems have a variety of solutions
1> could be you that you replace \n with <br>
so either in your controller/service or if you like in gsp:
${adviceInstance.advice?.replace('\n','<br>')}
2> display the content in a read-only textarea
<g:textArea name="something" readonly="true">
${adviceInstance.advice}
</g:textArea>
3> Use the <pre> tag
<pre>
${adviceInstance.advice}
</pre>
4> Use css white-space http://www.w3schools.com/cssref/pr_text_white-space.asp:
<div class="space">
</div>
//css code:
.space {
white-space:pre
}
Also make a note if you have a strict configuration for the storage of such fields that when you submit it via a form, there are additional elements I didn't delve into what it actually was, it may have actually be the return carriages or \r, anyhow explained in comments below. About the good rule to set a setter that trims the element each time it is received. i.e.:
Class Advice {
String advice
static constraints = {
advice(nullable:false, minSize:1, maxSize:255)
}
/*
* In this scenario with a a maxSize value, ensure you
* set your own setter to trim any hidden \r
* that may be posted back as part of the form request
* by end user. Trust me I got to know the hard way.
*/
void setAdvice(String adv) {
advice=adv.trim()
}
}
${raw(adviceInstance.advice?.encodeAsHTML().replace("\n", "<br>"))}
This is how i solve the problem.
Firstly make sure the string contains \n to denote line break.
For example :
String test = "This is first line. \n This is second line";
Then in gsp page use:
${raw(test?.replace("\n", "<br>"))}
The output will be as:
This is first line.
This is second line.

How to render files (called in one method) after a form is called and validated from a different method?

We are displaying the files in the gsp. The files are being pulled from the back end in the following way:
View
<table>
<tr>
<th>Attachment:
<td>
<g:each in="${lstAttachment}" var="nonOracleAttachmentItem">
<g:link id="${nonOracleAttachmentItem.Id}" action="nonOracleAttachment" params="[nonOracleAttachmentItemId: nonOracleAttachmentItem.Id,nonOracleAttachmentItemName: nonOracleAttachmentItem.Name]">${nonOracleAttachmentItem.Name}</g:link><br/>
</g:each>
</td>
</tr>
</table>
Controller
def show(){
def strAttachmentsName = null;
def boolAttachment = objChangeControl.Attachment__c
def strOrcAttachmentName = objChangeControl.Attachment_Name__c
if(strOrcAttachmentName !=null){
def lstOracleAttachment = salesforceService.getSObjectList(SFDC_ORG, "SELECT Id,Name from Attachment where ParentId='${idG}' AND Name='$strOrcAttachmentName'")
def lstAttachment = salesforceService.getSObjectList(SFDC_ORG, "SELECT Id,Name from Attachment where ParentId='${idG}' AND Name != '$strOrcAttachmentName'")
def oracleAttachmentId = lstOracleAttachment[0].Id
def oracleAttachmentName = lstOracleAttachment[0].Name
[oracleAttachmentId:oracleAttachmentId, oracleAttachmentName: oracleAttachmentName,lstAttachment:lstAttachment,grcInstance: objGRCChangeControl,updatedRAIInstance: objUpdatedRAI, strConfigurationOwner:strConfigurationOwner,strGRCStatusCustomSetting:strGRCStatusCustomSetting,sfUserName: session["${SFDC_ORG}UserName"],sfUserId:sfUserId]
}else{
def lstAttachment = salesforceService.getSObjectList(SFDC_ORG, "SELECT Id,Name from Attachment where ParentId='${idG}'")
[lstAttachment:lstAttachment,grcInstance: objGRCChangeControl,updatedRAIInstance: objUpdatedRAI, strConfigurationOwner:strConfigurationOwner,strGRCStatusCustomSetting:strGRCStatusCustomSetting,sfUserName: session["${SFDC_ORG}UserName"],sfUserId:sfUserId]
}
}
This is all good except when a field in the form fails validation and we need to retain all the field values along with the files that were originally displayed. Here's the catch block (inside the method called after pressing the 'Submit' button) which displays the error and also renders the values entered by the user prior to the validation error. How can I render the files as well?
def submitGRCRecord(){
try{
......
}
catch (Exception e){
render(action:"show",model:[sfUserName: session["${SFDC_ORG}UserName"], sfUserId: session["${SFDC_ORG}UserId"],encodedId:encodedIdParam,grcInstance: getGRCRecord(),inputITGNumber:inputITGNumber,inputJustification:inputJustification,attmtChecked: 'true',lstAttachment:params['lstAttachment']])
}
Sorry if this is very basic info but following’s the summary of this use case and solution for future reference:
User receives an email with a link/URL to the form where they need to provide certain information. The URL would always be in following format:
E.g.:
https://testchain.tstrandomurl.com/Folder1/show?encodedId=qwerty12345
The form would display some existing information from a record in database. The record id (unique identifier) is extracted from the encodedId in the URL. The existing ‘information’ includes, but is not limited to, bunch of files that needs to be displayed as a downloadable link.
Additionally, the form also has couple of fields which requires user inputs Explanation of Changes: - a long text field and Additional Related Attachments:- file upload placeholder.
Explanation of Changes has 256 character limits. This same record could be accessed multiple times and every time user needed to enter new Explanation of Changes it would count against the total character limit which incorporated previous input as well. So when the total character limit is reached, an standard error message was sent back to the view using flash.message. Additionally we had another check to cross check file name of Additional Related Attachment against pre-existing files in database.
While sending the error message after the form input validation, all the original value (except the uploaded file) needed to be retained in the form.
This was achieved by using chain method with action, params, and model like this: chain(action:'show',params:[encodedId:encodedIdParam],model: [UserName: session["${ORG}UserName"], UserId: session["${ORG}UserId"] ,inputExplainChanges:inputExplainChanges])
Using chain method to call 'show' method which originally displayed the files in the form and retain user input via model:[..] the issue was resolved.

Why value is viewing with [] in grails view

I am calling an action by remoteFunction for showing some value in some field.The value is viewing but with in []. I have no idea why it is behaving like this. Can anyone please help me on this please ? I am using grails 2.1.0. here are my attempts below :
my remoteFunction >>
<g:remoteFunction action="setValueForDetails" params="'procurementMasterId='+procurementMasterId" update="changedValue"/>
my action in controller >>
def setValueForDetails(){
def otmIFQDetailsByProcurementMaster
if(params.procurementMasterId != null && params.procurementMasterId != "" && params.procurementMasterId != "null"){
otmIFQDetailsByProcurementMaster = commonService.getOtmIFQDetailsValueByProcurementMaster(Long.parseLong(params.procurementMasterId))
}
render (template: 'ifqDetails', model: [otmIFQDetailsByProcurementMaster: otmIFQDetailsByProcurementMaster])
}
my field where I want to set the value in template >>
<g:textField id="PROCUREMENT_TYPE" name="PROCUREMENT_TYPE.id" readonly="" value="${otmIFQDetailsByProcurementMaster?.PROCUREMENT_TYPE}" class="form-control" />
I guess the 'PROCUREMENT_TYPE" is an Array of enums due to spelling, and displaying. So if You want to 'print' value without square brackets, You should change value to (if You want only first result):
value="${otmIFQDetailsByProcurementMaster?.PROCUREMENT_TYPE[0]}"
or if You want to should more than one element from list:
value="${otmIFQDetailsByProcurementMaster?.PROCUREMENT_TYPE.toString().replace('[', '').replace(']', '')}"
or simply iterate through the elements of PROCUREMENT_TYPE and show as many textfield as many PROCUREMENT_TYPE values You have.

How to display extra fields in article with K2

currently I've got Jreviews installed and I'd like to replace it by K2 to list specialized shops with addresses, phones, maps, opening hours ...
With K2 I guess I'll need to define extra custom fields to hold those specific information. No problem.
But, how may I configure things to have those fields displayed in the detailed article/items for a specific shop ?
Many thanks,
Tibi.
// In the item template you can skip this first line...
$this->item->extra_fields = K2ModelItem::getItemExtraFields($this->item->extra_fields);
$extraFlds = array();
if ( $this->item->extra_fields ){
foreach ( $this->item->extra_fields as $key=>$extraField ){
$extraFlds[ $extraField->name ] = $extraField->value;
}
}
Then you can access your extra fields in the associate array like $extraFlds['my field']
After a lot of tries here what i used and worked for me
<?php
// if form is empty show default form
$k2obj = new K2ModelItem();
$fields = $k2obj->getItemExtraFields($this->item->extra_fields, $this->item);
//echo $this->item->extraFields->State->name;
echo $this->item->extraFields->FIELD_ALIAS->value;
?>
This is working and noted its all pegged to instantiating the class.
Note: I am using this in the k2 item i version 2.6.7 Joomla 2.5.14
if you want show custum field in k2 table list go to:
components\com_k2\templates\default\category_item.php
and edit file near line 136 like this:
<?php foreach ($this->item->extra_fields as $key=>$extraField):
**if(strpos($extraField->name,"/")){**
?>
<li class="<?php echo ($key%2) ? "odd" : "even"; ?> type<?php echo ucfirst($extraField->type); ?> group<?php echo $extraField->group; ?>">
<span class="catItemExtraFieldsLabel"><?php echo $extraField->name; ?></span>
<span class="catItemExtraFieldsValue"><?php echo $extraField->value; ?></span>
</li>
<?php **}** endforeach; ?>
i do that in my site: www.joomir.com
The problem is that $this->item->extra_fields is actually a JSON string retrieved from the database, so you have to decode it first. It's structure is rather complicated (and unfortunately each field is labelled by it's id, it's name doesn't appear at all), you'll see it if you execute:
print_r($this->item->extra_fields);`
If you want to call field values by it's field name I'd do it like this:
if ($this->item->params->get('itemExtraFields')) {
$item_extra_fields = json_decode($this->item->extra_fields);
$put_your_extra_field1_name_here = $item_extra_fields[1]->value;
$put_your_extra_field2_name_here = $item_extra_fields[2]->value;
$put_your_extra_field3_name_here = $item_extra_fields[3]->value;
$put_your_extra_field4_name_here = $item_extra_fields[4]->value;
}
Notice that this is useful if the extra field you need is text, but it can be an array or whatever so you might have to code a little bit more. Hope this is useful!
In K2 you set the parameters for how an item displays at the category level. There is an option to display the extra fields in both Item view options in category listings as well as the Item view options.
By default, the built in K2 template will display the extra fields under a heading "Additional Information" with an unordered list of field name and values. You can override that template and make the extra fields display any way you like.

Resources