Grails controller not getting current value of a dropdown in a controller - grails

I have a dropdown (g:select) in my view that displays a list from a domain class. I want to println whatever value that is in it whenever a save button is clicked. Below is the script in the view
<g:select params="[tablename: storehouseInstance?.tablename]" name="tablename" from="${Warehouse.list()}" optionKey="id" optionValue="${Warehouse.list()}" value="tablename"
noSelection="['':'Choose Table']"
onchange="${remoteFunction (
controller: 'warehouse',
action: 'updateSelect',
params: "'warehouse.id=' + this.value + storehouseInstance?.tablename" ,
param: "this.value",
update: [success:'fieldSelection'] //update: 'fieldselection'
)}"/>
And in my controller i have:
def save() {
println("params are "+ params)
println("Saving table name: " + params.tablename)
}
I am getting tablename to be '1' instead of the value that should be something like 'MYTESTVALUE'
Any help please.

Assuming the warehouse's name property is name, try this instead:
<g:select params="[tablename: storehouseInstance?.tablename]"
name="tablename"
from="${Warehouse.list()}"
optionKey="name" // I changed this line
optionValue="name" // I changed this line too
value="tablename"
noSelection="['':'Choose Table']"
onchange="${remoteFunction (
controller: 'warehouse',
action: 'updateSelect',
params: "'warehouse.id=' + this.value + storehouseInstance?.tablename" ,
param: "this.value",
update: [success:'fieldSelection']
)}"/>
In a g:select the parameter that is sent to the server is defined by optionKey and the value that is displayed in the dropdown is defined by optionValue
Aside
From an MVC purity point-of-view, you shouldn't be doing queries in GSPs, e.g. Warehouse.list(). Instead you should retrieve the data you need in a service/contoller and pass it via the model to the view (GSP).

Related

limit select on certain Domain Class Items

My Domain Classes simplified look like this:
class ScheduleTimeExp{
Data date
}
class ScheduleAction{
ScheduleTimeExp scheduleTimeExp
}
I have a select box in my gsp:
<g:select id="scheduleTimeExp" name="scheduleTimeExp.id" from="${tao.marketing.ScheduleTimeExp.list()}" optionKey="id" required="" value="${tao.marketing.ScheduleAction?.scheduleTimeExp?.id}" class="many-to-one"/>
Rather that letting the user select from all ScheduleTimeExp
from="${tao.marketing.ScheduleTimeExp.list()}"
I would like to show only those ScheduleTimeExp where a relation between ScheduleTimeExp and ScheduleAction does not exist for any other ScheduleAction. In other words only those time expressions which have not yet been selected in another ScheduleAction.
To enforce logic from presentation separation, you want to fill the list inside controller action:
def dataSource
def someAction() {
final Sql sql = new Sql( dataSource )
def scheduleTimeExps = sql.rows( 'select ste.id, ste.date from Schedule_Time_Exp ste where ste.id not in (select sa.Schedule_Time_Exp_id from Schedule_Action sa)' ).collect{ it as ScheduleTimeExp }
[ ..., scheduleTimeExps:scheduleTimeExps ]
}
Note: make sure the case and naming of the tables and columns are correct
and then in gsp:
<g:select .. from="${scheduleTimeExps}"/>

VB.NET MVC Get vs Post how do i design my page

I have a VB.NET mvc view form that has 3 parameters and 2 buttons and I not sure how to design my page.
Button 1 is essentially a GET - suppose to run a sql query and return a dataset (multiple tables).
Button 2 is essentially a PUT - suppose to run a sql update statement (multiple updates).
CustomModel includes my 3 parameters as Properties and I have included the Required Attribute on all.
How do I design so that the Required attributes are respected.
I.e. my ViewInfo method is being reached even if the parameter inputs are blank.
Do I declare ViewInfo with the HttpGet and my UpdateInfo with HttpPut attribute. Do I need the parameter declarations in my ViewInfo method?
Is my #Html.BeginForm(...) declaration correct?
VB.NET Model class:
Public Class CustomModel
<Required(ErrorMessage:="Parameter 1 is required"),
Display(Name:="Parameter 1:")>
Public Property Parameter1 As String
<Required(ErrorMessage:="Parameter 2 is required"),
Display(Name:="Parameter 2:")>
Public Property Parameter2 As String
<Required(ErrorMessage:="Parameter 3 is required"),
Display(Name:="Parameter 3:")>
Public Property Parameter3 As Integer
Public Sub New(Parameter1 As String, Parameter2 As String, Parameter3 As Integer)
Me.Parameter1 = Parameter1
Me.Parameter2 = Parameter2
Me.Parameter3 = Parameter3
End Sub
Public Property Info As DataSet = New DataSet
End Class
VB.NET Controller:
Function Index() As ActionResult
ViewBag.ShowView = False
Return View()
End Function
Function ViewInfo(Parameter1 As String, Parameter2 As String, Parameter3 As Integer)
Dim result As New CustomModel(Parameter1, Parameter2, Parameter3)
If ModelState.IsValid Then
result.Info = GetInfo(Parameter1, Parameter2, Parameter3)
End If
ViewBag.ShowView = True
Return View("Index", result)
End Function
Function UpdateInfo(Parameter1 As String, Parameter2 As String, Parameter3 As Integer)
Dim result As New CustomModel(Parameter1, Parameter2, Parameter3)
If ModelState.IsValid Then
result.Info = UpdateInfo(Parameter1, Parameter2, Parameter3)
End If
ViewBag.ShowView = True
Return View("Index", result)
End Function
HTML View
#ModelType CustomModel
...
#Using (Html.BeginForm("ViewInfo", "Home", Nothing, FormMethod.Post))
...
#Html.LabelFor(...)
#Html.TextBoxFor(...)
...
<button type=button>View</button>
<button type=submit>Update</button>
End Using
Output:
#If ViewBag.Show Then
// Multiple WebGrid calls ???
End If
I found a solution to get me on my way finally.
I did not realise the default layout page behind the scenes does not include the validation javascript file so I had to add to my specific view file:
#Section scripts
#Scripts.Render("~/bundles/jqueryval")
End Section
Is there something you have to do so that this file is automatically brought in or is what I have done is correct you have to manually include it in either the layout or the specific view where you need it?

How can we get GroovyfirstRowResult to just list values, and not the column headers and without flower braces when shown in .gsp view?

In the groovy Controller Code I call the function:
def wiki =
{
def currentNode = params.nodePath
def conceptName = nodeService.retrieveConceptName (currentNode);
render (template:'wiki', model:[conceptName : conceptName])
}
In the service class I define the function retrieveConceptName:
def retrieveConceptName(currentNode)
{
groovy.sql.Sql sql = new groovy.sql.Sql(dataSource);
def row= sql.firstRow(" SELECT cname FROM Person WHERE FULLNAME= ?",[currentNode]);
return row;
}
In my output(wiki template(gsp view)) I get flowerbrackets along with field header , How to get only value of column and not the flower braces or field header?
You haven't shown the GSP code that displays the row, but I guess it looks like either ${it} or ${row}. If so, replace it with either
${it.cname} or ${row.cname}

Grails remote field - paramName and params together

I noticed something when I was attempting this today:
<g:remoteField action="getReportsToResults" update="reportsToResultsDiv" paramName="search" name="reportsToResults" value="" />
I have this section of code where my remoteField is updating a div that contains a selection box. It works, but I want to limit the results passed to the div based on a domain instance attribute value (company ID). I have the instance variable (contactInstance.company).
When I try to add the params to that code, the value of search goes to '+this.value+', instead of the actual value of the text field. How does that happen and how do I pass both the field value and another parameter?
<g:remoteField action="getReportsToResults" update="reportsToResultsDiv" paramName="search" params="[company:contactInstance.company]" name="reportsToResults" value="" />
The error your are getting is because remoteFeild does not accept params as its parameters and when you use the keyword params it confuses the code (take a look at remotefield sourcecode). If you need to pass a parameter I would suggest to put them in Id and pass it to your controller.
for example :
<g:remoteField action="getReportsToResults" update="reportsToResultsDiv" paramName="search" params="[company:contactInstance.company]" name="reportsToResults" value="" id = "123"/>
RemoteField params are:
name (required) - the name of the field
value (optional) - The initial value of the field
paramName (optional) - The name of the parameter send to the server
action (optional) - the name of the action to use in the link, if not specified the default action will be linked
controller (optional) - the name of the controller to use in the link, if not specified the current controller will be linked
id (optional) - The id to use in the link
update (optional) - Either a map containing the elements to update for 'success' or 'failure' states, or a string with the element to update in which cause failure events would be ignored
before (optional) - The javascript function to call before the remote function call
after (optional) - The javascript function to call after the remote function call
asynchronous (optional) - Whether to do the call asynchronously or not (defaults to true)
method (optional) - The method to use the execute the call (defaults to "post")
source code from 1.3.7
def remoteField = { attrs, body ->
def paramName = attrs.paramName ? attrs.remove('paramName') : 'value'
def value = attrs.remove('value')
if (!value) value = ''
out << "<input type=\"text\" name=\"${attrs.remove('name')}\" value=\"${value}\" onkeyup=\""
if (attrs.params) {
if (attrs.params instanceof Map) {
attrs.params[paramName] = new JavascriptValue('this.value')
}
else {
attrs.params += "+'${paramName}='+this.value"
}
}
else {
attrs.params = "'${paramName}='+this.value"
}
out << remoteFunction(attrs)
attrs.remove('params')
out << "\""
attrs.remove('url')
attrs.each { k,v->
out << " $k=\"$v\""
}
out <<" />"
}

how to access dynamically created radiobuttons in mvc3

foreach (var qList in Model) {
#Html.RadioButton("InputAnswer[" + index + "]", "Yes", false,
new { onclick = "LoadQuestion('" + qList.ID + "','Yes')" })<label>Yes</label>
#Html.RadioButton("InputAnswer[" + index + "]", "No", false,
new { onclick = "LoadQuestion('" + qList.ID + "','No')" })<label>No</label>
}
Based on the model it will create 1 , 2 , 3 or 4 set's of radio buttons as ( Yes & No). I need to get the input from the radio button's ( Yes or No ) and i need to display child controls dynamically.
Need Help: Please provide me some help. It would be great if you could suggest me how to take up this task from controller -> model -> view.
The easiest way is to just pass
LoadQuestion(this)
in the LoadQuestion javascript call. That will give you a reference to the current radiobutton that was clicked. Then you can use that reference to interrogate the radiobutton for information (id, value, checked, etc...) That should then allow you to toggle other values based on the state of the radiobutton.

Resources