Return JSON object with string values in Thymeleaf data attribute - thymeleaf

When a Java object has props with string values, the JSON does not render properly.
.html:
<div
th:if="${address}"
data-qa="js-address-info"
class="address"
th:attr='data-street-data=|{"addressLine":${address?.addressLine1} }|'
th:attr='data-zip-data=|{"zip":${address?.postalCode} }|'
></div>
.js:
const data = $('.address').data()
console.log(data)
Output:
zipData: Object { zip: 65414}
​
streetData: "{\"addressLine\": 643 Dogwood Lane }"
See that the string value doesn't have quotes around it, and the quotes that are there are escaped.
I tried wrapping the value with quotes like:
"addressLine":${""" + address?.addressLine1 + """} }
but that fails to even build.

Related

How to put multiple text parameter on the flutter (dart)?

I have code like this on the flutter, I need to put parameters data like icon and text, but I got error when put two text, how I can put two type same parameter?
new myCard(icon: Icons.home, text: 'Home', text: '234')
You cannot use the same names for multiple parameters, because they worklike variables for the constructor/method.
What you have to do is create multiple parameters for every text you need. For instance: if you need a title, create a title parameter, for a subtitle, create a subtitle parameter, instead of trying to use title twice.
Another way would be to pass an array of strings if you'll use them together, like to generate a string (check the example below). But don't use it if you want different strings in different places, it wouldn't be a good practice.
Check out this example:
void main(){
print( new Test(title: "Home", description: "The home page", textList: ["a", "list", "of", "strings"]) );
}
class Test {
String title;
String description;
List<String> textList;
Test({String this.title, String this.description,
List<String> this.textList});
#override
String toString() => "Title: " + title + "\nDescription: "
+ description + "\nText list together: " + textList.join(" ");
}
(copy and paste the code in the Dartpad if you want to test it, it simply creates and outputs a test class that receives two string parameters and a list of strings)

MissingPropertyException: No such property: * for class: java.util.LinkedHashMap$Entry

lets say i have this:
ArrayList maps = [ ]
Map map = [:]
my controller i did that:
List.each {
myList -> map = [key1:value1,key2:value2,key3:value3]
maps << map
}
return render ( template: "myTemplate" , model: [arrayList:maps])
I'm passing this arrayList of maps to my GSP and iterating through it so i assign the values of each map to elements.
i did something like this in my gsp.
<g:each in="${arrayList}" var="map">
<g:select from="${someList}" optionValue="${map.get('key1')}" optionKey="key"/>
<input type="text" id="textBox" value="${map.get('key2')}"/>
</g:each>
i am getting this error ! which says:
ERROR errors.GrailsExceptionResolver - MissingPropertyException occurred when processing request: [POST] .....
No such property: myValue for class: java.util.LinkedHashMap$Entry. Stacktrace follows:
groovy.lang.MissingPropertyException: No such property: myValue for class: java.util.LinkedHashMap$Entry
at Users_**_Projects_**_grails_app_views__myGsp_gsp.run(_myGsp.gsp:6)
at org.grails.plugins.web.rest.api.ControllersRestApi.render(ControllersRestApi.groovy:53)
at se.su.it.vfu.ConfigController$$EPLhPshc.myFunction(myController.groovy:428)
myGsp.gsp:6: is actually the "select" row provided in the gsp code
and 428 in my controller is the return render () row
myValue is actually a map value!
I am iterating through the arrayList and the first map is map1 looks like this
[key1: myValue , key2: otherValue , key3 : someOtherValue]
You have the following in your GSP:
<g:select from="${someList}" optionValue="${map.get('key1')}" optionKey="key"/>
That is going to be the problem. The value that you assign to optionValue should be the name of a property on the elements in someList. That property will be used when generating the "value" of the individual elements in the list. In your case it looks like map.get('key1') evaluates to myValue so the select tag is going to try and retrieve the value of the myValue property for each element in the list.
See http://grails.github.io/grails-doc/3.0.4/ref/Tags/select.html for more details.
I hope that helps.

Martini binding doesn't appear to be working

I'm playing around with Martini, and for some reason I can't get the contrib binding package to work.
My struct isn't having the values bound to. I've reduced the code down to it's simplest form, but it still doesn't work.
Can anyone see what I'm doing wrong?
package main
import (
"github.com/go-martini/martini"
"github.com/martini-contrib/binding"
"net/http"
)
var html string = `<form method="POST" enctype="application/x-www-form-urlencoded"><input name="un" type="text" /><input type="submit" value="Some button" /></form>`
type FormViewModel struct {
Username string `form: "un"`
}
func main() {
m := martini.Classic()
m.Get("/", func(w http.ResponseWriter) {
w.Header().Add("content-type", "text/html")
w.Write([]byte(html))
})
m.Post("/", binding.Form(FormViewModel{}), func(vm FormViewModel) string {
return "You entered: " + vm.Username
})
m.Run()
}
It is just a parsing issue in the definition of the tag associated to the field of the structure.
You need to remove the blank character after form:
If you write the structure as follows:
type FormViewModel struct {
Username string `form:"un"` // No blank after form:
}
... it should work better.
The Go language specification says:
By convention, tag strings are a concatenation of optionally space-separated key:"value" pairs. Each key is a non-empty string consisting of non-control characters other than space (U+0020 ' '), quote (U+0022 '"'), and colon (U+003A ':'). Each value is quoted using U+0022 '"' characters and Go string literal syntax.
Apparently, the parser implemented in the reflect package does not tolerate a space after the colon.

How to change the value of an input element generated by a html helper in ASP MVC

I am trapped in an everlasting loop to find the solution for this problem.
I am generating an advance link using a custom html helper to add new children for a parent object. Here is the html helper I use:
public static IHtmlString AddLink<TModel>(this HtmlHelper<TModel> htmlHelper, string linkText, string containerElement, string counterElement, string collectionProperty, Type nestedType, string productId)
{
var ticks = DateTime.UtcNow.Ticks;
var nestedObject = Activator.CreateInstance(nestedType);
var partial = htmlHelper.EditorFor(x => nestedObject).ToHtmlString().JsEncode();
partial = partial.Replace("id=\\\"nestedObject", "id=\\\"" + collectionProperty + "_" + ticks + "_");
partial = partial.Replace("name=\\\"nestedObject", "name=\\\"" + collectionProperty + "[" + ticks + "]");
var js = string.Format("javascript:addNestedForm('{0}','{1}','{2}','{3}');return false;", containerElement, counterElement, ticks, partial);
TagBuilder tb = new TagBuilder("a");
tb.Attributes.Add("href", "#");
tb.Attributes.Add("onclick", js);
tb.InnerHtml = linkText;
var tag = tb.ToString(TagRenderMode.Normal);
return MvcHtmlString.Create(tag);
}
I use this function using a loop in the view. Shortly, the view code is like this:
#Html.AddLink("Add More Part", "#parts", ".part", "Parts", typeof(percobaan2.Models.Part), Convert.ToString(Model.Id))
So when the link generated from the code above is clicked, html elements are appended to the parent element. Here are the generated html tags:
<input data-val="true" id="Parts_1__Id" name="Parts[1].Id" type="hidden" value="33">
<input data-val="true" id="Parts_1__ProductId" name="Parts[1].ProductId" type="hidden" value="0">
And here is what I need:
I need to loop for each input element that is created, to look for the name or id with ProductId (in the code above it is the second input element), then after I find it, I need to change its value into the value of productId from the html helper parameter (in the code above, the value is 0, and for example I want to make it 22 because the productId parameter in the Html helper is 22).
UPDATED
Here is the JS code for addNestedForm function:
function addNestedForm(container, counter, ticks, content) {
var nextIndex = $(counter).length;
var pattern = new RegExp(ticks, "gi");
content = content.replace(pattern, nextIndex);
$(container).append(content);
}

JSON made with .to_json (of a collection) in Rails model not readable jquery

I fetched the results of a query in the model. Next i right away added a .to_json and assumed I will get a correct JSON object. But JQuery was not able to parse the json
def self.get_all_specials(year)
data_array=AttributeCalendarAnnual.find(:all, :conditions=>["created_at between ? and ?",Date.civil(Date.today.year), Date.civil(Date.today.next_year.year)], :order=>["created_at asc"])
return data_array.to_json
end
But the result I get is not a valid JSON it seems.
EDIT
The output :
[{"created_at":"2012-01-17T17:38:27Z","id":1,"in_market_end_date":"2012-01-31T23:59:59Z","in_market_start_date":"2012-01-18T00:00:00Z","initiative_id":1,"is_mail_count_selected":true,"is_mailer_selected":true,"is_market_selected":true,"is_offer_selected":true,"mail_count":1,"mailer_start_date":"2012-01-25T00:00:00Z","offer_selection_end_date":"2012-01-12T23:59:59Z","offer_selection_start_date":"2012-01-09T00:00:00Z","updated_at":"2012-01-17T17:38:27Z"},{"created_at":"2012-01-17T20:21:37Z","id":2,"in_market_end_date":"2012-01-28T23:59:59Z","in_market_start_date":"2012-01-24T00:00:00Z","initiative_id":3,"is_mail_count_selected":true,"is_mailer_selected":true,"is_market_selected":true,"is_offer_selected":true,"mail_count":5,"mailer_start_date":"2012-01-30T00:00:00Z","offer_selection_end_date":"2012-01-21T23:59:59Z","offer_selection_start_date":"2012-01-09T00:00:00Z","updated_at":"2012-01-17T20:21:37Z"}]
if you are simply outputting the escaped object to your page and hoping JS will parse it this will not work because it will be interpreted as a string. Instead try feeding the string into a function like this:
function parseJSON(txt, escape) {
if (escape === true) {
txt = unescape(txt);
}
return new Function("return " + txt)();
}
var result = parseJSON(someString);

Resources