Get value of hidden field in form - spring-boot

Here is my login form with hidden field name "callbackUrl". How can i get the value of this hidden field in controller? User's attributes are username and password. callbackUrl is not.
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<link href="/resources/css/bootstrap.min.css" rel="stylesheet">
<link href="/resources/css/common.css" rel="stylesheet">
<title>Authentication Service</title>
</head>
<body>
<form method="POST" action="/login" modelAttribute="userFormLogin" class="form-signin">
<h2 class="form-heading">Log in</h2>
<input name="username" type="text" class="form-control" placeholder="Username"
autofocus="true"/>
<input name="password" type="password" class="form-control" placeholder="Password"/>
<input name="callbackUrl" type= "hidden" id="callbackUrl">
<h2>${error}</h2>
<br/>
<button class="btn btn-lg btn-primary btn-block" type="submit">Log In</button>
<h4 class="text-center">Create an account</h4>
</form>
</body>
<script>
var url_string = window.location.href; //window.location.href
var url = new URL(url_string);
var c = url.searchParams.get("callbackUrl");
console.log(c);
document.getElementById("callbackUrl").value = c;
</script>
</html>

add #RequestParam("callbackUrl") String callBackUrl to the method in your controller.
Like so:
public String myMethod(#RequestParam("callbackUrl") String callBackUrl, …) {
System.out.println(callBackUrl); //this will print the url to console
}

Related

Preserve values in modified object Thymeleaf

I'm creating an Object in GET method and initialize it with nulls. Then I set some values and send it to the POST method, but after this process all of values that I set earlier are nulls. How could I repair it? I've tried to use hidden fields, but it didn't help.
HTML code:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head>
<link rel="stylesheet" th:href="#{/styles.css}" />
</head>
<body>
<form method="POST" th:action="#{sendorder}" th:object="${details}">
<label for="name">Name: </label>
<input type="text" th:field="*{name}"/>
<br/>
<input type="hidden" th:field="*{order}" id="order"><label for="surname">Surname: </label>
<input type="text" th:field="*{surname}"/>
<br/><label for="room">Room: </label>
<input type="text" th:field="*{room}"/>
<br/>
<br/>
<h2>Please, choose your company:</h2>
<select th:field="*{company}">
<option th:each="i : ${companies}" th:value="${i.id}" th:text="${i.name}">
</option>
</select>
</div>
</div>
<input type="submit" value="Submit Order"/>
</form>
</body>
</html>

ErrorException Array to string conversion

i am facing ErrorException Array to string conversion, I am new in laravel. please help me in detail if you can,please help me in detail if you can please help me in detail if you can please help me in detail if you can please help me in detail if you can please help me in detail if you can please help me in detail if you can please help me in detail if you can
This is my code
<?php
namespace App\Http\Controllers;
use Redirect,Response;
use Illuminate\Http\Request;
use App\Models\Test;
use File;
class JsonController extends Controller
{
public function index()
{
return view('json_form');
}
public function download(Request $request)
{
$data = $request->only('name','email','mobile_number');
$test['token'] = time();
$test['data'] = json_encode($data);
Test::insert($test);
$fileName = $test['token']. '_datafile.json';
File::put(public_path('/upload/json/'.$fileName),$test);
//return download(public_path('/upload/jsonfile/'.$fileName));
$headers = [ 'Content-Type' => 'application/json', ];
return response()->download($test, 'filename.json', $headers);
//return response()->download(public_path('file_path/from_public_dir.pdf'));
}
}
This is my jeson.blade.php
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="csrf-token" content="{{ csrf_token() }}">
<title>Laravel Store Data To Json Format In Database - Tutsmake.com</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" />
<style>
.error{ color:red; }
</style>
</head>
<body>
<div class="container">
<h2 style="margin-top: 10px;">Laravel Store Data To Json Format In Database - Tutsmake.com</h2>
<br>
<br>
#if ($message = Session::get('success'))
<div class="alert alert-success alert-block">
<button type="button" class="close" data-dismiss="alert">×</button>
<strong>{{ $message }}</strong>
</div>
<br>
#endif
<form id="laravel_json" method="post" action="json-file-download">
#csrf
<div class="form-group">
<label for="formGroupExampleInput">Name</label>
<input type="text" name="name" class="form-control" id="formGroupExampleInput" placeholder="Please enter name">
</div>
<div class="form-group">
<label for="email">Email Id</label>
<input type="text" name="email" class="form-control" id="email" placeholder="Please enter email id">
</div>
<div class="form-group">
<label for="mobile_number">Mobile Number</label>
<input type="text" name="mobile_number" class="form-control" id="mobile_number" placeholder="Please enter mobile number">
</div>
<div class="form-group">
<button type="submit" class="btn btn-success">Submit</button>
</div>
</form>
</div>
</body>
</html>

How to submit Laravel VueJS dynamic form data?

I am new to Vue.js. I am trying to make a form dynamic (only a certain part of the form dynamic.). A user can have multiple guarantors. So I made the Guarantor form Dynamic with VueJS. When I submit the form and return the request, I see only the last array. Its always the last array, all others are lost.
This is the blade file.
<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="{{ asset('css/app.css')}}">
<title>Laravel</title>
</head>
<body>
<div id="app">
<div class="container pt-5">
<form action="{{ route('submit.store')}}" method="post">
#csrf
<div class="card-body">
<h4 class="card-title">User Detail</h4>
<input type="text" class="form-control mb-1" name="user_name" id="user_name" placeholder="Name" />
<input type="email" class="form-control mb-1" name="user_email" id="user_email"
placeholder="Email" />
<textarea name="about" class="form-control" id="about" cols="30" rows="10"
placeholder="About"></textarea>
</div>
<dynamic-form></dynamic-form>
</form>
</div>
</div>
<script src="{{ asset('js/app.js') }}"></script>
</body>
</html>
And this is how the VueComponent looks.
<template>
<div>
<button class="btn btn-success mb-3" #click.prevent="addNewUser">Add User</button>
<div class="card mb-3" v-for="(user, index) in users" :key="index">
<div class="card-body">
<span class="float-right" style="cursor:pointer" #click.prevent="removeForm(index)" >X</span>
<h4 class="card-title">Guarantor No: {{ index }}</h4>
<input type="text" class="form-control mb-1" name="name" id="name" placeholder="Name" v-model="user.name" />
<input type="email" class="form-control mb-1" name="email" id="email" placeholder="Email" v-model="user.email"/>
<textarea name="about" class="form-control" id="about" cols="30" rows="10" placeholder="About" v-model="user.about"></textarea>
</div>
</div>
<input type="submit" class="btn btn-primary" value="submit">
</div>
</template>
<script>
export default {
name: 'dynamic-form',
data() {
return{
users: [
{
name: '',
email: '',
about: ''
}
]
}
},
methods: {
addNewUser: function() {
this.users.push({
name: '',
email: '',
about: ''
});
},
removeForm: function(index) {
this.users.splice(index, 1);
}
}
}
</script>
How can I tackle this problem?
In PHP, values with the same name attribute value will get overwritten. (See the "How do I get all the results from a select multiple HTML tag?" section here).
You can create arrays of values by adding a bracket to the name. For example, if you made the name of the "name" input name[], name will be an array of names in PHP.
In your case, you could use this format: name="guarantors[][name]". That way you will get an array in PHP under the key guarantors (e.g. $request->guarantors) and each of the values in guarantors will be an array with the values name, email, etc.

How to fill List<string> field in Thymeleaf + Spring

here is my form
<!--destinationList List-->
<div class="form-group">
<div class="col-sm-3">
<label for="Destination">Destination</label>
</div>
<div class="col-sm-9">
<input type="text" class="form-control" th:field="*{destinationList[0]}" />
<input type="text" class="form-control" th:field="*{destinationList[1]}" />
<input type="text" class="form-control" th:field="*{destinationList[2]}" />
<input type="text" class="form-control" th:field="*{destinationList[3]}" />
</div>
</div>
<div class="form-group">
<div class="col-sm-9">
<button type="submit" class="btn btn-primary btn-block">Calculate</button>
</div>
</div>
</form>
And I'm going to fill following model
public class PriceSearchDTO {
private List<String> destinationList;
public List<String> getDestinationList() {
return destinationList;
}
public void setDestinationList(List<String> destinationList) {
this.destinationList = destinationList;
}
}
I can do this. But I hard coded number of input fields in the list as above in the view. I need to genarate them dynamically and make the number of element in the list is airbitary.
Try this:
<div class="col-sm-9">
<input type="text" class="form-control" th:each="destination : ${destinationList}" th:field="*{destination}" />
</div>
You are using Iteration in Thymeleaf. In fact, there is a quite complete set of objects that are considered iterable by a th:each attribute.
Like this :
<!DOCTYPE html SYSTEM "http://www.thymeleaf.org/dtd/xhtml1-strict-thymeleaf-4.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head>
<title>Good Thymes Virtual Grocery</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" type="text/css" media="all"
href="../../../css/gtvg.css" th:href="#{/css/gtvg.css}" />
</head>
<body>
<h1>Product list</h1>
<table>
<tr>
<th>NAME</th>
<th>PRICE</th>
<th>IN STOCK</th>
</tr>
<tr th:each="destination: ${destinations}">
<td th:text="${destination}">Onions</td>
</tr>
</table>
<p>
Return to home
</p>
</body>
</html>
And Controller in Spring framework.
#RequestMapping(value = "/")
public ModelAndView showView(ModelAndView mav) {
List<String> destinations = new ArrayList<String>();
destinations.add("elementA");
destinations.add("elementB");
destinations.add("elementC");
mav.addObject("destinations", destinations);
mav.setViewName("/viewName");
return mav;
}

jquery-validate rule (required) is not working

I am trying to use jquery-validate plugin to validate a form inside a bootstrap-dialog. The "required" rule doesn't prevent me from submitting a form with an empty text field. However, "digits" rule works so that means validation is initialized properly. What am I missing here? Thanks.
Here's how I display the bootstrap-dialog and how I initialize validation.
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>App Title</title>
<link type="text/css" rel="stylesheet" href="<c:url value="/css/bootstrap/3.0.3/bootstrap.min.css" />"></link>
<script src="<c:url value="/js/jquery/1.10.2/jquery-1.10.2.min.js" />"></script>
<script src="<c:url value="/js/jquery-ui/1.10.4/jquery-ui.min.js" />"></script>
<script src="<c:url value="/js/bootstrap/3.0.3/bootstrap.min.js" />"></script>
<script src="<c:url value="/js/bootstrap-dialog//bootstrap-dialog.min.js" />"></script>
<link type="text/css" rel="stylesheet" href="<c:url value="/css/style.css" />"></link>
<link type="text/css" rel="stylesheet" href="<c:url value="/css/jquery-ui/1.10.4/jquery-ui.min.css" />"></link>
<link type="text/css" rel="stylesheet" href="<c:url value="/css/bootstrap-dialog/bootstrap-dialog.min.css" />"></link>
<script src="<c:url value="/js/jquery-validation/1.11.1/jquery.validate.min.js" />"></script>
<script type="text/javascript">
function wireValidationEvent($form)
{
$form.validate({
errorElement: 'span',
errorClass: 'help-block',
wrapper: "div",
rules: {
name: {
required: true
}
},
messages: {
name: {
required: "Please enter the name properly."
}
},
highlight: function (element) {
$(element).closest('.form-group').addClass('has-error');
},
success: function (element) {
$(element).closest('.form-group').removeClass('has-error');
}
});
}
function showModalDialog(url)
{
var get = $.get(url, '');
get.done(function(data) {
// Note that data contains just a form without any button.
// The form is dynamically injected into the body of the modal dialog. That's why wireValidationEvent() is called each time when a form is injected.
// When Save button is clicked, the form will be submitted using jquery.
BootstrapDialog.show({
title: 'Update Form',
closable: true,
autodestroy: true,
onshow: function(dialogRef){
var $body = dialogRef.getModalBody();
$body.append(data.trim());
var $formObj = $body.find('#formOfReligion');
if ($formObj)
{
// TODO bug: required validation rule doesn't work here
wireValidationEvent($formObj);
}
else
{
alert('formOfReligion is missing');
}
},
buttons: [{
label: 'Save',
action: function(dialog) {
var formObj = $('#formOfReligion');
if (formObj && formObj.length > 0)
{
var form = formObj[0];
var post = $.post(form.action, formObj.serialize());
post.done(function( data ) {
// succeeded
dialog.close();
$('#frmQuery').submit();
});
post.fail(function( data ) {
// failed
});
}
}
}, {
label: 'Cancel',
action: function(dialog) {
dialog.close();
}
}]
});
});
return true;
}
</script>
Here's what the modal dialog looks like.
<div class="modal-backdrop fade in"></div>
<div id="bea044b7-a0cb-48df-8b57-6cbdedac9bdf" class="modal fade bootstrap-dialog type-primary size-normal in" tabindex="-1" style="display: block;" aria-hidden="false">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<div class="bootstrap-dialog-header">
<div class="bootstrap-dialog-title">Update Form</div>
<div class="bootstrap-dialog-close-button" style="display: block;">
<button class="close">×</button>
</div>
</div>
</div>
<div class="modal-body">
<div class="bootstrap-dialog-body">
<div class="bootstrap-dialog-message"></div>
</div>
<form id="formOfReligion" class="form-horizontal" role="form" method="POST" action="/prs/protected/test" novalidate="novalidate">
<fieldset>
<div class="form-group">
<div>
<label class="control-label" for="name">Name</label>
</div>
<div>
<input id="id" type="hidden" value="6" name="id">
<input id="name" class="form-control" type="text" value="test" autofocus="autofocus" name="name">
</div>
</div>
</fieldset>
</form>
</div>
<div class="modal-footer">
<div class="bootstrap-dialog-footer">
<div class="bootstrap-dialog-footer-buttons">
<button id="667d578f-490e-4d08-a8c1-1013b60c3394" class="btn btn-default">Save</button>
<button id="8b647389-edce-4f64-af8e-64521e865dcf" class="btn btn-default">Cancel</button>
</div>
</div>
<input id="id" type="hidden" value="6" name="id">
<input id="name" class="form-control" type="text" value="test" autofocus="autofocus" name="name">
You have a hard-coded value of "test" on the input so the required rule is already satisfied without the user having to enter anything.
BTW: I don't think you have a good naming system here: id="id", name="id", id="name", and name="name". It's not semantic, not scalable, and potentially confusing.

Resources