groovy.lang.MissingMethodException new1.EmployeeController.findByUsername() - grails

I was trying to make a signup page, which takes the username and password as from the user and stores it in my database, but the problem here is, the data is not going to the database only
you can see the image here
[https://drive.google.com/file/d/0B9gjSzsLSnClR1VvU0RUa3liRWs/view?usp=sharing][1]
save method look likes this
#Transactional
def save(){
if(params == null){
redirect(action:"index")
flash.message=''
return
}
def employee = findByUsername(params.username);
System.out.println(employee.username);
if(employee!=null){
flash.message="username already exist"
render(view:"signup")
}
else{
def newEmp = new Employee();
newEmp.username=params.username
newEmp.password=params.password
if(newEmp.save(flush:true)){
flash.message="Employee created"
render(view:"index")
}
else{
flash.message="Please enter valid data"
render(view:"signup")
}
if(newEmp.save(flush:true)) {
flash.message = "User Created. Please Login"
render(view:"index")
} else {
flash.message = "Please enter valid data";
render(view:"signup")
}
}
}
View page look like this
<form id="signupform" action="./save" method="POST" class="form-horizontal" role="form">
<g:if test="${flash.message}">
<div class="alert alert-danger" role="alert">${flash.message}</div>
</g:if>
<div class="form-group">
<label for="username" class="col-md-3 control-label">Username</label>
<div class="col-md-9">
<input type="text" class="form-control" name="username" placeholder="Username">
</div>
</div>
<div class="form-group">
<label for="password" class="col-md-3 control-label">Password</label>
<div class="col-md-9">
<input type="password" class="form-control" name="password" placeholder="Password">
</div>
</div>
<div class="form-group">
<!-- Button -->
<div class="col-md-offset-3 col-md-9 text-center">
<button id="btn-signup" type="submit" class="btn btn-info"><i class="icon-hand-right"></i>Sign Up</button>
</div>
</div>
</form>

Replace this:
def employee = findByUsername(params.username);
with:
def employee = Employee.findByUsername(params.username);
All dynamic finder methods must be called statically on the type you expect them to return

Related

How to compare emails in javascript?

I am trying to make an edit profile page in which user can update its current email or pwd by inputting current email and password and then give new ones. I am also sending whole data of user(including username and password) when he sign in through viewdata.
#{
var user = (User)ViewData["User"];
}
<div class="account-info mt-3">
<fieldset class="border border-dark p-3">
<legend class="float-none w-auto">Account Info</legend>
<div class="mb-3 simpleinfo">
<label for="email" class="form-label">Enter Your Current Email</label>
<input type="email" class="form-control" name="Username" id="prevemail"/>
</div>
<div class="mb-3 simpleinfo">
<label for="prevpwd" class="form-label">Enter Your Current Password</label>
<input type="password" class="form-control" name="Pwd" id="prevpwd"/>
<button type="button" class="btn btn-success mt-4 checkcred">Update Credentials</button>
</div>
<div class="mb-3 simpleinfo">
<label for="email" class="form-label">Enter new Email</label>
<input asp-for="Username" disabled type="email" class="form-control" id="newemail">
</div>
<div class="mb-3 simpleinfo">
<label for="newpwd" class="form-label">Enter New Password</label>
<input type="password" disabled class="form-control" asp-for="Password" id="newpwd">
</div>
</fieldset>
</div>
Now i want to compare the email that user enters and the email that is present in the user object.
here's my code for this:
<script>
$('.checkcred').click(function() {
var prevemail = $('#prevemail').val();
var prevpassword=$('#prevpwd').val();
if(prevemail==#user.Username&&prevpassword==#user.Password)
{
alert("Validated");
}
else
{
alert("not validated");
}
});
</script>
But it is giving me syntax error on Console: Invalid or unexpected token.
Please lemme know what i am doing wrong.

Edit action in controller not updating

When I edit an item and return to the index view the item doesn't show what I updated it to.
I think I know what the problem is but not sure how to fix it. In my service class I have a CreateEditItem method and when I step thru the code it hits the if condition <=0. So it acts like there is an id of 0 when I click the submit button to submit my update. I'm not sure what to do to fix this. Do I need to have a separate method for Edit? And if so what should that look like?
public bool CreateEditItem(Item item)
{
if (item.ItemId <= 0)
{
var maxId = _mockList.Max(p => p.ItemId);
item.ItemId = maxId + 1;
_mockList.Add(item);
return true;
}
var itemToEdit = _mockList.FirstOrDefault(p => p.ItemId ==
item.ItemId);
itemToEdit = item;
return true;
}
Action in Controller
[HttpPost]
public IActionResult EditItem(Item itemToEdit)
{
_itemService.CreateEditItem(itemToEdit);
return RedirectToAction(nameof(Index), new { id =
itemToEdit.ItemId });
}
View:
<div class="row">
<form asp-action="EditItem">
<div asp-validation-summary="ModelOnly" class="text-
danger"></div>
<div class="container form-group">
<div class="row">
<div class="col-md-2">As Of : <label
for="AsOf" /></div>
<div class="col-md-4"><input id="AsOf"
value="#Model.ItemToEdit.AsOf" name="AsOf" type="date" /></div>
</div>
<br />
<div class="row">
<div class="col-md-2">Title Summary : <label
for="TitleSummary" /></div>
<div class="col-md-2"><input id="TitleSummary"
value="#Model.ItemToEdit.Title" name="Title" type="text" /></div>
</div>
<br />
<br />
<div class="row">
<div class="col-md-2"><input type="submit"
value="Submit" class="btn btn-primary" /></div>
</div>
</div>
</form>
</div>
I expect when I click the submit button to submit my update it will show the updated Title and/or AsOf date.
change your method from HTTPut to HttpPost
it will work.

Not hitting controller in MVC

In my submit of my login form which is in pop-up it is not hitting the controller even though I provided the code in beginform with post method. I need to send the username and password to my controller for verification. Unable to figure out why it is not hitting.
[HttpPost]
public ActionResult LoginUser(UserInfo objUser)
{
int res = udaObj.CheckUser(objUser.UserName, objUser.Password);
if (res >= 1)
{
return RedirectToAction("Appointment", "Home");
}
else
{
//For testing purpose
return RedirectToAction("Appointment", "Home");
}
}
My view is as follows:
#using (Html.BeginForm("LoginUser", "Home", FormMethod.Post, new { id = "loginForm" }))
{
<div class="tab-pane fade active in" id="signin">
<fieldset>
<!-- Sign In Form -->
<!-- Text input-->
<div class="control-group">
<label class="control-label" for="userid">Alias:</label>
<div class="controls">
#* <input required="" id="userid" name="userid" type="text" class="form-control" placeholder="JoeSixpack" class="input-medium" required="">*#
#Html.TextBoxFor(x => x.UserName, new { #class = "form-control input-large", #placeholder = "Joek#irawath.com", #required = "" , #id="userid" })
</div>
</div>
<!-- Password input-->
<div class="control-group">
<label class="control-label" for="passwordinput">Password:</label>
<div class="controls">
#*<input required="" id="passwordinput" name="passwordinput" class="form-control" type="password" placeholder="********" class="input-medium">*#
#Html.TextBoxFor(x => x.Password, new { #class = "form-control input-large", #placeholder = "********", #required = "", #type = "password" , #id="passwordinput" })
</div>
</div>
<!-- Multiple Checkboxes (inline) -->
<div class="control-group">
<label class="control-label" for="rememberme"></label>
<div class="controls">
<label class="checkbox inline" for="rememberme-0">
<input type="checkbox" name="rememberme" id="rememberme-0" value="Remember me" style="margin-left: 0px">
Remember me
</label>
</div>
</div>
<button id="btnsignin" type="submit" name="signin" class="btn btn-success">Sign In</button>
<!-- Button -->
<div class="control-group">
<label class="control-label" for="signin"></label>
<div class="controls">
#* <button id="btnsignin" type="submit" name="signin" class="btn btn-success">Sign In</button>*#
</div>
</div>
</fieldset>
</div>
}
Check if the object UserInfo is the same model you are using in your view. Try using a FormCollection instead and check.

ASP .NET core razor view conditional display doesn't work as expected

I have a view where I conditionally iterate and print items: SPANs are not displayed (as expected).
<div>
#if (Model.SomeCondition)
{
#foreach (var x in Model.SomeData)
{
<span>#x.Title</span>
}
}
</div>
Now I'd like not to display the enclosing DIV, however it doesn't work: SPANs are still not displayed, but the DIV is. Why does this happen?
#if (Model.SomeCondition)
{
<div>
#foreach (var x in Model.SomeData)
{
<span>#x.Title</span>
}
</div>
}
This is the full view code:
#using Team.L
#using Microsoft.AspNetCore.Mvc.Localization
#inject IViewLocalizer Localizer
#model Team.ViewModels.DeptTaskGroupView
#{
var EventHandler = "Aventin." + ViewBag.AspAction + "(event)";
}
<form asp-controller="ModulesEx" asp-action="#ViewBag.AspAction" onsubmit="return false">
<div class="form-horizontal">
<input type="hidden" asp-for="Errors">
<div class="MessageBox">#Html.Raw(Utility.GetMessage(Model))</div>
<div class="form-group col-md-offset-2">
<label class="col-md-2"></label>
<div class="col-md-10">
<span data-valmsg-for="" class="text-danger" />
</div>
</div>
<div class="form-group">
<label class="col-md-2 control-label">#MyText.Department</label>
<div class="col-md-10">
<select asp-for="DepartmentID" class="form-control" asp-items="#Model.DepartmentList" onchange="#EventHandler"></select>
<span asp-validation-for="DepartmentID" class="text-danger" />
</div>
</div>
#if (Model.AssignedTaskGroup != null)
{
<div class="form-group">
<label class="col-md-2 control-label">#MyText.TaskGroup</label>
<div class="col-md-10">
#foreach (var x in Model.AssignedTaskGroup)
{
<input type="checkbox" name="selectedItems" value="#x.ID" #(Html.Raw(x.Assigned ? "checked=\"checked\"" : "")) />
#x.Title
}
</div>
</div>
}
<div class="form-horizontal">
<div class="form-group">
<div class="col-md-1 col-md-offset-2">
<input type="submit" value="#MyText.Save" class="btn btn-default" />
</div>
</div>
</div>
</div>
</form>
As written, it doesn't happen. I'm guessing you either didn't reload the page or there is code around your demonstrated code that renders a div that this div is contained in.

How to use custom validator in Grails

I'm new in Grails. I would like to use custom validator for matching two passwords during registration in my application. Unfortunetly doesn't work it.
Account.groovy
#Validateable
class Account {
String login
String password
String confirm
String passwordHashed
char active
static transients = ['password', 'confirm']
static belongsTo = Employee
static hasMany = [role:Role]
static constraints = {
login unique:true, blank: false
active nullable: true
password blank: false, size: 5..15, validator:{ val, obj ->
if(obj.password != obj.confirm ){
return ['dontmatch']
}
}
}
static mapping = {
id generator: 'increment'
}
}
AuthenticationController.groovy
class AuthenticationController {
def signUp(Account accountInstance){
if(accountInstance!= null){
if (accountInstance.hasErrors()) {
respond accountInstance.errors, view:'signUp'
return
}
else{
accountInstance.save(flush: true)
}
}
}
}
signUp.gsp
<%# page import="com.sarna.entity.Account"%>
<%# page import="com.sarna.entity.Employee"%>
<!DOCTYPE html>
<html>
<head>
<meta name="layout" content="bootstrap-main" />
<title>SARNA</title>
</head>
<body>
<br />
<div class="container">
<div style="margin-top: 50px"
class="mainbox col-md-6 col-md-offset-3 col-sm-8 col-sm-offset-2">
<div class="panel panel-info">
<div class="panel-heading">
<div class="panel-title">Sign Up</div>
<div
style="float: right; font-size: 85%; position: relative; top: -10px">
<a id="signinlink"
href="${createLink(uri: '/authentication/signIn') }">Sign In</a>
</div>
</div>
<div class="panel-body">
<g:form class="form-horizontal" role="form"
url="[resource: accountInstance]"
method="POST" controller="Authentication">
<g:hasErrors bean="${accountInstance}">
<div class="alert alert-danger">
<g:renderErrors bean="${accountInstance}" />
</div>
</g:hasErrors>
<div class="form-group">
<label for="email" class="col-md-3 control-label">Email</label>
<div class="col-md-9">
<input type="text" class="form-control" name="email"
placeholder="Email Address">
</div>
</div>
<div class="form-group">
<label for="icode" class="col-md-3 control-label">Login</label>
<div class="col-md-9">
<g:textField type="text" class="form-control" name="login"
required="" value="${accountInstance?.login }"
placeholder="Login" />
</div>
</div>
<div class="form-group">
<label for="password" class="col-md-3 control-label">Password</label>
<div class="col-md-9">
<g:passwordField name="password"
class="form-control ${hasErrors(bean:accountInstance,field:'password','errors')}"
placeholder="Password" />
</div>
</div>
<div class="form-group">
<label for="icode" class="col-md-3 control-label">Confirm</label>
<div class="col-md-9">
<g:passwordField
class="form-control ${hasErrors(bean:accountInstance,field:'password','errors')}"
name="confirm" placeholder="Confirm Password" />
</div>
</div>
<div class="form-group">
<!-- Button -->
<div class="col-md-offset-3 col-md-9">
<g:actionSubmit action="signUp"
class="btn btn-lg btn-success btn-block" value="Sign Up" />
</div>
</div>
</g:form>
</div>
</div>
</div>
</div>
</body>
</html>
messages.properties
account.password.dontmatch=Podane hasła muszą się zgadzać
I don't understand it. I enter two different passwords and I click signUp button, I don't see errors messages which should be display when validation failed. Could you help me?
The call of validate() is missing:
if (!accountInstance.validate() || accountInstance.hasErrors()) {
...
}
Match the actual value from the validator with the confirm property from the actual object.
password blank: false, size: 5..15, validator:{ val, obj ->
if( obj.confirm && val != obj.confirm ) { // val is password
return ['dontmatch']
}
}
I think instead of the respond in the controller you want
render (view: "signUp", model: [accountInstance: accountInstance])
Your view expects an accountInstance object in the view model to render the errors, so you have to provide it.
You can also just do
return [accountInstance: accountInstance]
If there is a gsp that has the same name as the current action grails will automatically render it.

Resources