cannot set readonly property:params - grails

i'm trying to save a picture and return it's visit-url,but system throw a exception about params: 'cannot set readonly property: params'
def upload() {
def attachmentInstance = new Attachment(utype:params.type, udata:params.data)
if (!attachmentInstance.save(flush: true)) {
render(view: "create", model: [attachmentInstance: attachmentInstance])
return
}
def subMap = [url:"${createLink(controller:'attachment', action:'renderImg', params:'[id:${attachmentInstance.id}]')}", width:0, height:0]
def jsonMap = [id:attachmentInstance.id, type:"image", thumbnail:"", data:subMap]
def result = [result:jsonMap]
render result as JSON
}

It looks a little over-complex, can you try:
def subMap = [url:createLink(controller:'attachment', action:'renderImg', params:[id:attachmentInstance.id]), width:0, height:0]

Related

Map single controller to multiple methods/action

My Controller name is ...Login...
and method/action names like....HomeContent.....automotive...etc
I am also posting my controller code here..
class LoginController {
def dataSource;
static allowedMethod = [userLogin:"POST",HomeContent:"GET",Disclaimer:"GET",FAQ:"GET",OurTeam:"GET",ourPortfolio:"GET",privacyPolicy:"GET",beautyTips:"GET",dietNutrition:"GET",healthFitness:"GET",yoga:"GET",mentalStress:"GET",automotive:"GET",digitalMarketing:"GET",ecommerce:"GET",education:"GET",finance:"GET",foodAndBeverage:"GET",marketUpdates:"GET",realState:"GET",coWorkingSpaces:"GET",homeRemodeling:"GET",scienceAndTechnology:"GET",sportsMania:"GET",travelAndTourism:"GET",boxOffice:"GET",dayToDayNewsUpdates:"GET",mediaGossip:"GET",poertyZone:"GET",lifestyleMagazine:"GET",becomeAContributor:"GET"]
def HomeContent()
{
def query ="SELECT id,post_title,post_date,post_content FROM wp_posts where post_status='publish' and post_type='post' ORDER BY post_date DESC limit 10"
def db = new Sql(dataSource)
def json = db.rows(query)
render json as JSON
}
// About Us section starts here
def Disclaimer()
{
def query = "select distinct id,post_title,post_date,post_content from wp_posts where post_title='disclaimer' and post_status='publish'"
def db = new Sql(dataSource)
def json = db.rows(query)
render json as JSON
}
def FAQ()
{
def query = "select distinct id,post_title,post_date,post_content from wp_posts where post_title='FAQ' and post_status='publish'"
def db = new Sql(dataSource)
def json = db.rows(query)
render json as JSON
}
and my URLMapping code here..
class UrlMappings {
static mappings = {
"/Login"(controller:"Login",action:"HomeContent")
"/"(view:"/index")
"500"(view:'/error')
}
}
Add generic support to UrlMappings, assuming that's all you want:
//inside static mappings:
"/$controller/$action?"{ }

How to enter a hard-coded value to the database?

I have a few fields in my User.groovy model class
fName
lName
userName
pwd
yourTel
The user will be entering the first 4 fields shown above. The 5th field yourTel will be hardcoded.
def create() {
[userInstance: new User(params)]
}
How can I do it ?
This is what I already tried:
def create() {
userInstance.yourTel = "2323232"
params = userInstance.yourTe
[userInstance: new User(params)]
}
SAVE
def save() {
def userInstance = new User(params)
if (!userInstance.save(flush: true)) {
render(view: "create", model: [userInstance: userInstance])
return
}else {
def userRole = Role.findOrSaveWhere(authority:'ROLE_USER')
if(!userInstance.authorities.contains(userRole)){
UserRole.create(userInstance, userRole, true)
}
redirect(controller:"login", action : "auth")
}
}
MODEL
static constraints = {
...
yourTel blank:true , nullable: false
Your approach works too with a bit of tweak:
def create() {
def instance = new User(params)
instance.yourTel="2323232"
[userInstance: instance]
}
The [userInstance: instance] the left is the key that will be used by your models, the right hand side is what you are passing to it. Here you first create the new User(params) then bind it with params and then you can tweak it and pass it back to your model.
def save() {
def userInstance = new User(params)
// set the yourTel to some value
userInstance.yourTel="2323232"
if (!userInstance.save(flush: true)) {
render(view: "create", model: [userInstance: userInstance])
params is a map, so put your data like
params.yourTel="2323232"
or
params.put("yourTel","2323232")
Now your code becomes:
def create() {
params.yourTel="2323232"
[userInstance: new User(params)]
}

Deserialize a JSON object with support for embedded associations

Is there an easy way to deserialize a JSON string to a domain class with support of embedded association; belongsTo and hasMany
{
name: "Customer",
contact: {
name: "Contact"
}
}
class Customer {
name
Contact contact
}
class Contact {
String name
static belongsTo = [customer:Customer]
}
in my controller I would like to do the following
def save() {
def customer = new Customer(request.JSON)
customer.save();
}
Now i'm forced to do
def save() {
def contact = new Contact(request.JSON.contact);
def customer = new Customer(request.JSON);
customer.contact = contact;
customer.save();
}
Have you tried using JsonSlurper?
Example usage:
def slurper = new JsonSlurper()
def result = slurper.parseText('{"person":{"name":"Guillaume","age":33,"pets":["dog","cat"]}}')
assert result.person.name == "Guillaume"
assert result.person.age == 33
assert result.person.pets.size() == 2
assert result.person.pets[0] == "dog"
assert result.person.pets[1] == "cat"
Ref: http://groovy.codehaus.org/gapi/groovy/json/JsonSlurper.html
you can try this
Test test
def result = new JsonSlurper().parseTest('yourString')
test = result
Try this will work.

Grails controllers repeated code for all actions

Imagine this controller:
class exampleController{
def action1 = {}
def action2 = {}
def action3 = {}
def action4 = {}
def action5 = {}
}
I want to be able to return in all the action in this controller the same params. Imagining this:
def user = session.user
[user: user]
Is there any way of doing this, besides writing all the same code on all the actions? The session.user return params is just an example. I don't wanna really return it.
A simple solution is to put this code in a method and call it from each action
class exampleController{
def action1 = {getModel()}
def action2 = {getModel()}
def action3 = {getModel()}
def action4 = {getModel()}
def action5 = {getModel()}
private getModel() {
def user = session.user
[user: user]
}
}
While this does involve some amount of repetition (invocation of the same method), it's a lot more obvious what's happening here. When debugging/testing a controller it's easy to forget about filters and interceptors, which can often lead to questions like
what the #**% is going on here?
Use a filter - http://grails.org/doc/latest/guide/6.%20The%20Web%20Layer.html#6.6%20Filters - or an after interceptor - http://grails.org/doc/latest/guide/6.%20The%20Web%20Layer.html#6.1.5%20Controller%20Interceptors
I have a similar case, and I was modified the grails scaffolding for the controller's generator.
class MyClassController {
def list = {
...
}
def show = {
def eInstance = beanIfExist()
...
}
def edit = {
def eInstance = beanIfExist()
...
}
def update = {
def eInstance = beanIfExist()
...
}
def delete = {
def eInstance = beanIfExist()
...
}
def beanIfExist = {
def beanInstance = MyClass.get(params.id)
if (beanInstance) {
return beanInstance
} else {
flash.message = "Error, invalid record."
redirect(action: "list")
return null
}
}
}
It is my suggestion, now if do you need another that sent a data to view then you can use interceptors.

grails question (sample 1 of Grails To Action book) problem with Controller and Service

I'm doing Grails To Action sample for chapter one. Every was just fine until I started to work with Services. When I run the app I have the following error:
groovy.lang.MissingPropertyException: No such property: quoteService for class: qotd.QuoteController
at qotd.QuoteController$_closure3.doCall(QuoteController.groovy:14)
at qotd.QuoteController$_closure3.doCall(QuoteController.groovy)
at java.lang.Thread.run(Thread.java:619)
Here is my groovie QuoteService class, which has an error within the definition of GetStaticQuote (ERROR: Groovy:unable to resolve class Quote)
package qotd
class QuoteService {
boolean transactional = false
def getRandomQuote() {
def allQuotes = Quote.list()
def randomQuote = null
if (allQuotes.size() > 0) {
def randomIdx = new Random().nextInt(allQuotes.size())
randomQuote = allQuotes[randomIdx]
} else {
randomQuote = getStaticQuote()
}
return randomQuote
}
def getStaticQuote() {
return new Quote(author: "Anonymous",content: "Real Programmers Don't eat quiche")
}
}
Eclipse show me an error flag on the definition of getStaticQuote:
ERROR: Groovy:unable to resolve class Quote
Any Clues?
Controller groovie class
package qotd
class QuoteController {
def index = {
redirect(action: random)
}
def home = {
render "<h1>Real Programmers do not each quiche!</h1>"
}
def random = {
def randomQuote = quoteService.getRandomQuote()
[ quote : randomQuote ]
}
def ajaxRandom = {
def randomQuote = quoteService.getRandomQuote()
render "<q>${randomQuote.content}</q>" +
"<p>${randomQuote.author}</p>"
}
}
Quote Class:
package qotd
class Quote {
String content
String author
Date created = new Date()
static constraints = {
author(blank:false)
content(maxSize:1000, blank:false)
}
}
I'm doing the samples using STS. Any advice?
Regards,
Francisco
do
def quoteService
at the top of your controller and it will be injected into the controller automatically
groovy.lang.MissingPropertyException: No such property: quoteService for class: qotd.QuoteController
I dont code in grails but it appears as though you need to declare quoteService somewhere in the controller.
I did
def quoteService = new QuoteService()
and it solved my problem

Resources