Menu
  • HOME
  • TAGS

GSP form parameter appended to params - need overwrite

Tag: grails,groovy,gsp

I have the following form:

<g:form controller="${controllerName}" action="${actionName}" params="${params}">
    <g:select name="publisher_status" from="${['Active']}" value="${publisher_status}" noSelection="${[null:'No Filter']}" />
    <button type="submit" class="btn btn-default btn-primary btn-sm ">Apply</button>     
</g:form>

Each time I submit this form, publisher_status value is appended to the previous one, resulting in a list like publisher_status=[null,'Active'] etc. What I really need is to overwrite the previous value, so I always have just a string. I tried the following above and below the above form, but it is not working:

  <g:set var="params" value="${params.remove('publisher_status')?params:params}"/>

Any suggestions as to how to get around this issue ?

Best How To :

You can't set params like that, but you can filter the map that you pass to g:form:

<g:form controller="${controllerName}" action="${actionName}"
        params="${params.findAll {k, v -> k != 'publisher_status'}}">

create email list of all users

groovy,jenkins,jenkins-scriptler

First of all you should know that Jenkins will not always be able to tell you whether the user exists or not. From Jenkins' javadoc: This happens, for example, when the security realm is on top of the servlet implementation, there's no way of even knowing if an user of...

set an annotation attribute from an environment variable?

spring,groovy,spring-boot

You can not use GStrings in java annotations in groovy. You have to use "proper" Strings. E.g. @Scheduled(cron = '${DB_CRON}') Note the single quotes here. If groovy sees a $ in "-quoted string, it will turn it into a GString. This can not be done with java annotations and you...

passing backbone collection to view

grails,backbone.js,handlebars

The reason you don't see any items is that the items aren't actually in the collection until after the view is rendered. Look at these two lines of code: var priceView = new PriceView({collection: prices}); prices.fetch(); The first line renders the view (since you're calling render from within initialize). However,...

Intercepting login calls with Spring-Security-Rest plugin in Grails

rest,grails,spring-security

Yes, you can provide a custom bean that implements the RestAuthenticationSuccessHandler. Take a look at the API documentation for the class to see what you need to implement. Then it's as simple as overriding the bean in your application context: // Resources.groovy restAuthenticationSuccessHandler(MyCustomRestAuthenticationSuccessHandler) { renderer = ref('accessTokenJsonRenderer') } It might...

Grails 3.0.2 missing generate-views

java,grails,command-line,ide,ggts

The reason is that dynamic scaffolding is not yet implemented in Grails 3.x.

Grails 2.3.9 - Error: ClassNotFoundException: grails.plugin.spock.test.GrailsSpecTestType

grails,grails-plugin,spock,grails-2.3

for Grails 2.2+ try this code in your BuildConfig: grails.project.dependency.resolution = { repositories { grailsCentral() mavenCentral() } dependencies { test "org.spockframework:spock-grails-support:0.7-groovy-2.0" } plugins { test(":spock:0.7") { exclude "spock-grails-support" } } } for more info just check out: https://grails.org/plugin/spock...

Model to LazyMap

dictionary,groovy,deserialization

You can use jackson-databind. E.g. @Grab('com.fasterxml.jackson.core:jackson-databind:2.5.4') import com.fasterxml.jackson.databind.ObjectMapper class AccessCredentials { String userName = 'Between The Buried And Me' String password = 'Alaska' LoginOptions loginOptions = new LoginOptions() } class LoginOptions { String partnerId = 'Colors' String applicationId = 'The Great Misdirect' } def mapper = new ObjectMapper() assert mapper.convertValue(new...

grails 3.0.1 scaffolded view does not show domain relationship

grails,scaffolding

What you are seeing is this issue https://github.com/grails3-plugins/fields/issues/1 which when resolved will fix this problem.

grails DataSource.groovy refer bean for decoding password

grails

I don't think this will be possible. The reason for this is the lifecycle (startup) of a Spring/Grails application requires that the DataSource be parsed while setting up the Spring application context. As such, making reference to a bean in the application context isn't going to be valid because the...

Groovy - timestamp from minutes

oracle,grails,groovy,timestamp

I assume you want to use the current day offset with the number of minutes given for your timestamp. Since a new Date or Timestamp will be initialized to the current time and date, you can use that and override the minute field with the values from your array. Values...

Grails: Carry forward params on hyperlink is clicked

grails,redirect,controller

If you look to the redirected URL, you will realize that params are carry forwarded correctly. 11 the only params you have in your delete action and that is forwarded to list action (.../list/11) after successful delete. The issue is that you are not passing max and offset with delete...

grails one to many with additional column

grails,relationship,one-to-many

I've solved this issue with the following code. I hope that someone gives me a comment about it. receiptInstance.healthServices.collect().each { //I've tried to use receiptInstance.healthServices.clear() //but Set remains with all items //delete item from Set receiptInstance.healthServices.remove(it) //delete item from DB it.delete() } //save with flush to commit the delete if...

Use data-* attribute in grails g.link generated in tagLib

grails

Just put quotes around your data attributes : out << g.link(controller: "calendar", action: "info", params: [id: cal_id], "data-info": "abc") { "click me " } ...

Intellij IDEA long processing for grails app with warning “too much output to process”

grails,intellij-idea,jvm

I think this is the problem of using a wrong JDK for your project. And it mainly arises incompatible version like the latest versions namely 1.8.45 etc. Can you please try with some older JDK like 1.8.25 and let us know if it works? I earlier had such an issue...

using classes in jenkins job dsl

groovy,jenkins,jenkins-job-dsl

When using println in scripts (in your example, in the runIt function), Groovy sends the call to a out variable defined in the script's binding or to System.out.println if the variable is not set. The Job DSL plugin sets this variable so that the output goes to the build log....

[B cannot be cast to java.sql.Blob

grails,gorm

static mapping = { xmlSubmission sqlType: 'blob' } ...

sonar maven analysis only picks .java file

maven,groovy,sonarqube,sonarqube-5.0

Since it was a multi module project, I had to include the properties sonar.sources and sonar.tests in all the module's pom.xml file. <properties> <sonar.sources>src/main</sonar.sources> <sonar.tests>src/test</sonar.tests> </properties> ...

Restrict allowed httpMethods using enum

rest,groovy,enums

Is that what you're looking for: public enum HttpMethod { POST, DELETE, GET, PUT, HEAD, TRACE, CONNECT, PATCH } class EntityQuery { String field1 String field2 } def createEntity(HttpMethod h, EntityQuery q) { if(!(h in [HttpMethod.POST, HttpMethod.GET])) { throw new Exception('Only POST and GET methods allowed') } } createEntity(HttpMethod.PUT, new...

alert grails pagination current offset value

grails,pagination

You can try "${params.offset ?: 0}" and pass this to controller, like <g:link controller="someCtrl" action="someActn" params="[offset: params.offset ?: 0]"></g:link> ...

Get just content of soap response in Groovy

xml,soap,groovy

SO you could do this: import groovy.xml.* def xml = '''<?xml version="1.0" encoding="utf-8"?> |<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> | <soap:Body> | <GetHTMLResponse xmlns="http://www.webserviceX.NET"> | <GetHTMLResult> | TEST | </GetHTMLResult> | </GetHTMLResponse> | </soap:Body> |</soap:Envelope>'''.stripMargin() def result = XmlUtil.serialize(new...

Error when using angular with Grails

angularjs,grails

The error that you get says: Failed to instantiate module myApp due to: {1} Which basically means angular could not create an instance of myApp. You might want at a minimum level to have this code: var myApp = angular.module('myApp',[]); function MyCtrl($scope) { } and in your HTML: <html ng-app="myApp">...

Cron expression must consist of 6 fields (found 1 in “#{systemEnvironment['db_cron']}”)

spring,groovy,cron,spring-el

You should set env variable like you do: export db_cron="0 19 21 * * *" then restart your ide if you are using or restart your terminal session. @Scheduled(cron = "${db_cron}") def void schedule() { ... } I tried it and here is my screenshot. Everything works as expected......

Grails logging auto inject

grails,logback

add the @Slf4j annotation on your class. This local transform adds a logging ability to your program using LogBack logging. Every method call on a unbound variable named log will be mapped to a call to the logger. For this a log field will be inserted in the class. If...

Class fields as method parameters

oop,groovy

Assuming your EntityQuery.groovy ( model )looks like : private String typeName private Order order Assuming you have Order.groovy ( model ) that looks like : private String fieldName; private String orderType; private String orderName; use these model chain as a parameter, I think that is still strongly-typed (correct me). Your...

Hibernate proxies - classes with unusual names

grails

Yes, that is an instance of a Proxy class.

Spock's @Narrative and @Title annotations

groovy,spock

Title is expected to be a single line (short description) Narrative should be full paragraphs (using a Groovy multi-line string) They are mostly used in big projects where Narrative text could be read by business analysts, project managers e.t.c. As Opal said these will be more useful once some reporting...

How to get testStep responseAsXml in groovyScript

groovy,soapui

If you want to get the response from com.eviware.soapui.impl.wsdl.teststeps.WsdlTestRequestStep, a possible way is first get the testStep from this class using getTestStep() method. This method returns a object of class com.eviware.soapui.model.testsuite.TestStep, from this object you can get the testSteps properties like request, response, endpoint... using getPropertyValue(java.lang.string) method. So in your...

Spock Framework: problems with spying

java,unit-testing,groovy,spock,spock-spy

It should be: @Grab('org.spockframework:spock-core:0.7-groovy-2.0') @Grab('cglib:cglib-nodep:3.1') import spock.lang.* class CallingClassTest extends Specification { def "check that functionTwo calls functionOne"() { def c = Spy(CallingClass) when: def s = c.functionTwo() then: 1 * c.functionOne() >> "mocked function return" s == "some string mocked function return" } } public class CallingClass { public...

unable to resolve class org.apache.commons.net.ftp in grails

grails,apache-commons

In Grails you rarely add jar files to the project, you normally add dependencies. In your case you should add this line to the BuildConfig.groovy (section grails.project.dependency.resolution.plugins) compile 'commons-net:commons-net:3.3' ...

Grails JAX-RS Calling a class in src/groovy giving error - Message: No signature of method: is applicable for argument types

grails,groovy,jax-rs

either use new ValidateToken.validate(... or make your validate method static. this is actually what the error is stating: No signature of method: static ....ValidateToken.validate() is applicable for argument types: () values: []` ...

Execute controller function in Grails via Ajax

javascript,jquery,ajax,grails,gsp

Right click on the page,Inspect Element and see if there are any errors in console. Also, you should specify URL this way: url: '${createLink(controller: 'region', action: 'categoryChanged')}', ...

Grails 3.0 Searchable plugin

maven,grails

The page you took the instructions from contains the following disclaimer: This portal is for Grails 1.x and 2.x plugins. Grails 3 plugins are available in Bintray https://bintray.com/grails/plugins There currenly is no version of this plugin for grails 3.x...

Render a controller into a String

grails,grails-2.0

You can use grails include tag for this def html= g.include(controller: 'myController', action: 'myAction', params: [what:'ever']) ...

How to declare javascript asset in the view to be rendered within the footer using Grails Asset Pipeline

grails,grails-plugin

The most simple way is using site mesh. In your layout you need to put <g:pageProperty name="page.script"/> At the end of the body. Then in the page you will do something like this: <content tag="script"> <script type="application/javascript"> ... your code here ... </script> </content> Notice that the content tag (script)...

Grails: Do addTo* and removeFrom* require a call to save?

grails,gorm,grails-2.0,grails-domain-class

Neither needs a call to save() in most contexts. What you're seeing in the "some examples" link is a save to the main domain object Author, which gets persisted first, and then the other properties will make it in the database with a proper id to link back to. For...

Special Groovy magic re property access and collections / iterables?

groovy

That's the GPath expression documented (ish) here, and yes, it only works for properties. (There's an old blog post by Ted Naleid here about digging in to how it worked in 2008) For methods, you need to use *. or .collect() See also: Groovy spread-dot operator Better docs link (as...

Grails: Carry forward params on g:actionSubmit is clicked

grails,gsp

I don't think that you can pass params with actionSubmit in this way. You can use params attribute of g:form tag, like <g:form params="${params}"> ... </g:form> or <g:form params="[offset: params.offset, max: params.max]"> ... </g:form> ...

Decode base64 image in Grails [duplicate]

grails,groovy

Base64 uses Ascii characters to send binary files, so to retrieve your image, you basically have to decode the Base64 string back to a byte array and save it to a file. String encoded = 'iVBORw0KGgoAAAANSUhEUg' // You complete String encoded.replaceAll("\r", "") encoded.replaceAll("\n", "") byte[] decoded = encoded.decodeBase64() new File("file/path").withOutputStream...

groovy/XML: Replace a node by another one

xml,groovy,xml-parsing,xmlslurper

Here you go: import groovy.xml.* def xml = '''<myXml> <myNode> <Name>name1</Name> <Name>name2</Name> <Name>name3</Name> </myNode> </myXml>''' def namelist = ['name4','name5','name6','name7'] def slurped = new XmlSlurper().parseText(xml) slurped.myNode.replaceNode { myNode { namelist.collect { n -> Name "$n" } } } new StreamingMarkupBuilder().bind { mkp.yield slurped }.toString() The node was in fact replaced but...

How does the Groovy compiler work?

groovy

Groovy parses the source code with antlr via the groovy grammar description, then generates bytecode using asm It does not require javac...

File upload with grails and jquery

jquery,grails

Use below function to send files with ajax on form submit at view end function formSubmit(){ var formData=new FormData($('form#create-form')[0]); $.ajax({url: 'createAttachment', type:'POST', data: formData, processData: false,contentType: false,dataType: 'script',success:function(result){ }}); return false } at controller side use below code to access file objects def createAttachment = { List attachmentsFiles=[] request.fileNames.each {...

Log Grails Pre 3.0 startup time

grails

You could try: grails -Dgrails.script.profile=true Although it may require not using forked mode. Otherwise you will need to configure logging with time stamps for the org.codehaus.groovy.grails package....

Grails 2.4.4 spring security role doesn't apply to user

java,spring,grails,spring-security,spring-annotations

The spring Security has an default UserDetailsService, which assigned the Roles to an User. You could debug it to see what going wrong. Or You create your own: https://grails-plugins.github.io/grails-spring-security-core/guide/userDetailsService.html HTH...

Groovy: run SQL SELECT LIKE from file with params

sql,select,groovy

try this SELECT * FROM [db].[dbo].[TABLE] WHERE [ID] LIKE '%'+convert(varchar(50),:id)+'%' ...

Confused about the invokeMethod method in the Groovy MOP

groovy,mop

In short you are not using the standard meta class, so you don't get the standard Groovy MOP. Car.metaClass.invokeMethod = { will let Car have an ExpandoMetaClass as meta class. This meta class uses the invokeMethod you give in as open block (like you do) to intercept calls. This is...

Write Spock test cases for Spring boot application

java,spring,groovy,spock

Yes, you can write spock test cases for your spring application. Look at the official documentation for an example of Spock testing with Spring Boot 35.3.1 Using Spock to test Spring Boot applications A simple google search reveals a basic example of Using Spock to test Spring classes. Spock relies...

Encryption of strings using AES 128 in Java/grails

java,grails,encryption,aes

cipher.init method call is missed in your code. Check the below code. public byte[] encrypt(byte[] data, byte[] key) { Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key, "AES")); return cipher.doFinal(data); } For decrypt have to change mode to Cipher.DECRYPT_MODE...