Set value Entity Framework Core during OnGet - entity-framework-core

I thought this would be simple...
If I want to force a value to a column/filed before the page loads, how do I do that?
Here's the lines from the Model:
[DataType(DataType.Currency)]
[Column(TypeName = "money")]
[Display(Name = "Contract Value")]
public decimal? ContractValue { get; set; } = 0m;
[DataType(DataType.Currency)]
[Column(TypeName = "money")]
[Display(Name = "Contract Expended")]
public decimal? ContractValueExpended { get; set; } = 0m;
And, here's what I tried using Fluent API.
modelBuilder.Entity<Contract>()
.Property(e => e.ContractValue)
.HasDefaultValue(0);
modelBuilder.Entity<Contract>()
.Property(e => e.ContractValueExpended)
.HasDefaultValue(0);
My bad. Here is create.cshtml.cs
public class CreateModel : GlobalPageModel
{
private readonly TawdryIndustries.Data.CompanyContext _context;
public CreateModel(TawdryIndustries.Data.CompanyContext context)
{
_context = context;
}
public IActionResult OnGet()
{
PopulateEmployeeNamesSelectList(_context);
PopulateCustomerNamesSelectList(_context);
return Page();
}
[BindProperty]
public Contract Contract { get; set; }
public async Task<IActionResult> OnPostAsync()
{
var emptyContract = new Contract();
if (await TryUpdateModelAsync<Contract>(
emptyContract,
"Contract",
c => c.ContractID,
c => c.ContractNumber,
c => c.ContractName,
c => c.CustomerID,
c => c.ContractAwardDate,
c => c.ContractBegDate,
c => c.ContractEndDate,
c => c.ContractValue,
c => c.ContractValueExpended,
c => c.ContractManagerID))
{
_context.Contracts.Add(emptyContract);
await _context.SaveChangesAsync();
return RedirectToPage("./Index");
}
PopulateEmployeeNamesSelectList(_context, emptyContract.ContractManagerID);
PopulateCustomerNamesSelectList(_context, emptyContract.CustomerID);
return Page();
}
And, here is the razor page (create.cshtml):
#page
#model TawdryIndustries.Pages.Contracts.CreateModel
#{
ViewData["Title"] = "Create";
}
<h1>Create</h1>
<h4>Contract</h4>
<hr />
<form method="post">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<table class="table">
<tr>
<td>
<label asp-for="Contract.CustomerID" class="control-label"></label>
<select asp-for="Contract.CustomerID" class="form-control"
asp-items="#Model.CustomerNameSL">
<option value="">-- Select Customer --</option>
</select>
<span asp-validation-for="Contract.CustomerID" class="text-danger"></span>
</td>
<td>
<label asp-for="Contract.ContractNumber" class="control-label"></label>
<input asp-for="Contract.ContractNumber" class="form-control" />
<span asp-validation-for="Contract.ContractNumber" class="text-danger"></span>
</td>
<td>
<label asp-for="Contract.ContractName" class="control-label"></label>
<input asp-for="Contract.ContractName" class="form-control" />
<span asp-validation-for="Contract.ContractName" class="text-danger"></span>
</td>
</tr>
<tr>
<td>
<label asp-for="Contract.ContractAwardDate" class="control-label"></label>
<input asp-for="Contract.ContractAwardDate" class="form-control" />
<span asp-validation-for="Contract.ContractAwardDate" class="text-danger"></span>
</td>
<td>
<label asp-for="Contract.ContractBegDate" class="control-label"></label>
<input asp-for="Contract.ContractBegDate" class="form-control" />
<span asp-validation-for="Contract.ContractBegDate" class="text-danger"></span>
</td>
<td>
<label asp-for="Contract.ContractEndDate" class="control-label"></label>
<input asp-for="Contract.ContractEndDate" class="form-control" />
<span asp-validation-for="Contract.ContractEndDate" class="text-danger"></span>
</td>
</tr>
<tr>
<td>
<label asp-for="Contract.ContractValue" class="control-label"></label>
<input asp-for="Contract.ContractValue" class="form-control" />
<span asp-validation-for="Contract.ContractValue" class="text-danger"></span>
</td>
<td>
<label asp-for="Contract.ContractValueExpended" class="control-label"></label>
<input asp-for="Contract.ContractValueExpended" class="form-control" />
<span asp-validation-for="Contract.ContractValueExpended" class="text-danger"></span>
</td>
<td>
<label asp-for="Contract.ContractManagerID" class="control-label"></label>
<select asp-for="Contract.ContractManagerID" class="form-control"
asp-items="#Model.EmployeeNameSL">
<option value="">-- Select Manager --</option>
</select>
<span asp-validation-for="Contract.ContractManagerID" class="text-danger"></span>
</td>
</tr>
<tr>
<td>
<input type="submit" value="Create" class="btn btn-primary" />
</td>
</tr>
</table>
</form>
<div>
<a asp-page="Index">Back to List</a>
</div>
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
However, when the page is displayed (in create specifically), both of those fields are still blank. I want to force both fields to 0 when a new contract is created before the page loads.
For that matter, is there any way to set a value for a variable before a page loads?
In ASP.NET I would
<html>
<head></head>
<body>
<asp:textbox id="mytext" runat="server"></asp:textbox>
</body>
and:
protected void Page_Load(object sender, EventArgs e)
{
string somevar = "This is a test";
mytext.Text = somevar;
}
And the text box would contain "This is a test" when the page was displayed.
What is the equivalent in EF Core?
Thanks,
John

Related

How do I pass master id to detail foreign key?

I have a master-detail edit that doesn't work as it should.
TaBarHeader - master and TaBarBody - detail, have one-to-many relationship:
public partial class TaBarHeader
{
[Key]
public int Id { get; set; }
public string ListaOtf { get; set; }
public IEnumerable<TaBarBody> TaBarBodies { get; set; }
public IEnumerable<TaBarTelegrama> TaBarTelegramas { get; set; }
}
public partial class TaBarBody
{
[Key]
public int Id { get; set; }
public string Codstatie1 { get; set; }
public int BarHeaderId { get; set; }
[ForeignKey("BarHeaderId")]
public TaBarHeader BarHeaderFk { get; set; }
}
HeaderTelegrama/Details.cshtml:
#model TraficAlert.Models.ViewModels.HeaderTelegramaViewModel
<dt class="col-sm-2">
#Html.DisplayNameFor(model => model.TaBarHeader.ListaOtf)
</dt>
<dd class="col-sm-10">
#Html.DisplayFor(model => model.TaBarHeader.ListaOtf)
</dd>
(...)
<th>
#Html.DisplayNameFor(model => model.TaBarBody.Codstatie1)
</th>
#foreach (var item in Model.TaBarHeader.TaBarBodies)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Codstatie1)
</td>
<a asp-controller="BodyTelegrama" asp-action="Edit" asp-route-id="#item.Id">Edit</a>
BodyTelegrama/Edit.cshtml:
#model TraficAlert.Models.ViewModels.BodyTelegramaViewModel
#{
ViewData["Title"] = "Edit";
}
<h1>Edit</h1>
<h4>TaBarBody</h4>
<hr />
<div class="row">
<div class="col-md-4">
<form asp-action="Edit">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="#Model.TaBarBody.Codstatie1" class="control-label">Cod Statie 1</label>
<input asp-for="#Model.TaBarBody.Codstatie1" class="form-control" />
<span asp-validation-for="#Model.TaBarBody.Codstatie1" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="#Model.TaBarBody.Codstatie2" class="control-label">Cod Statie 2</label>
<input asp-for="#Model.TaBarBody.Codstatie2" class="form-control" />
<span asp-validation-for="#Model.TaBarBody.Codstatie2" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="#Model.TaBarBody.DtIniP" class="control-label">Data Ini P</label>
<input asp-for="#Model.TaBarBody.DtIniP" class="form-control" />
<span asp-validation-for="#Model.TaBarBody.DtIniP" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="#Model.TaBarBody.DtFinP" class="control-label">Data Fin P</label>
<input asp-for="#Model.TaBarBody.DtFinP" class="form-control" />
<span asp-validation-for="#Model.TaBarBody.DtFinP" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="#Model.TaBarBody.DtIniR" class="control-label">Data Ini R</label>
<input asp-for="#Model.TaBarBody.DtIniR" class="form-control" />
<span asp-validation-for="#Model.TaBarBody.DtFinP" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="#Model.TaBarBody.DtFinR" class="control-label">Data Fin R</label>
<input asp-for="#Model.TaBarBody.DtFinR" class="form-control" />
<span asp-validation-for="#Model.TaBarBody.DtFinR" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="#Model.TaBarBody.KmIni" class="control-label">Km Ini</label>
<input asp-for="#Model.TaBarBody.KmIni" class="form-control" />
<span asp-validation-for="#Model.TaBarBody.KmIni" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="#Model.TaBarBody.KmFin" class="control-label">Km Fin</label>
<input asp-for="#Model.TaBarBody.KmFin" class="form-control" />
<span asp-validation-for="#Model.TaBarBody.KmFin" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="#Model.TaBarBody.LiniaFir" class="control-label">Linia Fir</label>
<input asp-for="#Model.TaBarBody.LiniaFir" class="form-control" />
<span asp-validation-for="#Model.TaBarBody.LiniaFir" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="#Model.TaBarBody.NomImpactId" class="control-label">Impact</label>
<select asp-for="#Model.TaBarBody.NomImpactId" class="form-control" asp-items="ViewBag.NomImpactId"></select>
</div>
<div class="form-group">
<label asp-for="#Model.TaBarBody.NomAnulatId" class="control-label">Anulat</label>
<select asp-for="#Model.TaBarBody.NomAnulatId" class="form-control" asp-items="ViewBag.NomAnulatId"></select>
</div>
<div class="form-group">
<label asp-for="#Model.TaBarBody.MotivAnulare" class="control-label">Motiv Anulare</label>
<input asp-for="#Model.TaBarBody.MotivAnulare" class="form-control" />
<span asp-validation-for="#Model.TaBarBody.MotivAnulare" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="#Model.TaBarBody.Ruta" class="control-label">Ruta</label>
<input asp-for="#Model.TaBarBody.Ruta" class="form-control" />
<span asp-validation-for="#Model.TaBarBody.Ruta" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" asp-route-id="#ViewBag.TelegramaId" value="Save" />
</div>
</form>
</div>
</div>
<div>
<a asp-action="Index">Back to List</a>
</div>
BodyTelegramaController:
// GET
public IActionResult Edit(int id, int HeaderTelegramaId)
{
BodyTelegramaViewModel bodyTelegramaViewModel = new BodyTelegramaViewModel();
bodyTelegramaViewModel.TaBarBody = new TaBarBody();
bodyTelegramaViewModel.TaBarBody.BarHeaderFk = new TaBarHeader();
bodyTelegramaViewModel.TaBarBody = _unitofwork.BarBody.DetailsBarB(id);
bodyTelegramaViewModel.TaBarBody.BarHeaderFk = _unitofwork.BarHeader.DetailsBarHB(id);
ViewData["TelegramaId"] = HeaderTelegramaId;
if (bodyTelegramaViewModel.TaBarBody == null)
{
return NotFound();
}
ViewData["NomImpactId"] = new SelectList(_unitofwork.NomImpact.GetAll(), "Id", "Nume");
ViewData["NomAnulatId"] = new SelectList(_unitofwork.NomAnulat.GetAll(), "Id", "Nume");
return View(bodyTelegramaViewModel);
}
// POST
public IActionResult Edit(int id, BodyTelegramaViewModel bodyTelegramaViewModel)
{
if (id != bodyTelegramaViewModel.TaBarBody.Id)
{
return NotFound();
}
if (ModelState.IsValid)
{
try
{
bodyTelegramaViewModel.TaBarBody.BarHeaderId = id;
_unitofwork.BarBody.Update(bodyTelegramaViewModel.TaBarBody);
_unitofwork.Save();
}
catch (DbUpdateConcurrencyException)
{
if (!TaBarBodyExists(bodyTelegramaViewModel.TaBarBody.Id))
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToAction("Index");
}
return View(bodyTelegramaViewModel);
}
Everytime I edit a record, my foreign key - BarHeaderId - change its value to 0.
I have tried bodyTelegramaViewModel.TaBarBody.BarHeaderId = bodyTelegramaViewModel.TaBarHeader.Id; but I get the error 'Object reference not set to an instance of an object.'
How can I get the TaBarHeader.Id value and put it in TaBarBody.BarHeaderId?
Update:
ViewModels:
public class HeaderTelegramaViewModel
{
public TaBarHeader TaBarHeader { get; set; }
public IEnumerable<TaBarHeader> taBarHeader { get; set; }
public TaBarBody TaBarBody { get; set; }
public IEnumerable<TaBarBody> taBarBody { get; set; }
}
public class BodyTelegramaViewModel
{
public TaBarBody TaBarBody { get; set; }
public IEnumerable<TaBarBody> taBarBody { get; set; }
}
HeaderTelegramaController:
public IActionResult Details(int id)
{
HeaderTelegramaViewModel headerTelegramaViewModel = new HeaderTelegramaViewModel();
headerTelegramaViewModel.TaBarHeader = _unitofwork.BarHeaderRepository.DetailsBarHB(id);
if (headerTelegramaViewModel == null)
{
return NotFound();
}
return View(headerTelegramaViewModel);
}
BodyTelegramaController:
// GET
public IActionResult Edit(int id)
{
BodyTelegramaViewModel bodyTelegramaViewModel = new BodyTelegramaViewModel();
bodyTelegramaViewModel.TaBarBody = new TaBarBody();
bodyTelegramaViewModel.TaBarBody.BarHeaderFk = new TaBarHeader();
bodyTelegramaViewModel.TaBarBody = _unitofwork.BarBodyRepository.DetailsBarB(id);
bodyTelegramaViewModel.TaBarBody.BarHeaderFk = _unitofwork.BarHeaderRepository.DetailsBarHB(id);
return View(bodyTelegramaViewModel);
}
These are the methods DetailsBarB() and DetailsBarHB():
public TaBarBody DetailsBarB(int id)
{
return _db.TaBarBodies
.Include(t => t.BarHeaderFk)
.FirstOrDefault(m => m.Id == id);
}
public TaBarHeader DetailsBarHB(int id)
{
return _db.TaBarHeaders
.Include(x => x.TaBarBodies).ThenInclude(x => x.BarHeaderFk.CategoriaFk)
.FirstOrDefault(m => m.Id == id);
}
You can do following changes to get the TaBarHeader id.
In your Details View,change it to:
<a asp-controller="BodyTelegrama" asp-action="Edit" asp-route-id="#item.Id" asp-route-HeaderTelegramaId="#Model.TaBarHeader.Id">Edit</a>
In your Edit action,change it to:
public IActionResult Edit(int id,int HeaderTelegramaId)
{
BodyTelegramaViewModel bodyTelegramaViewModel = new BodyTelegramaViewModel();
bodyTelegramaViewModel.TaBarBody = new TaBarBody();
bodyTelegramaViewModel.TaBarBody.BarHeaderFk = new TaBarHeader();
bodyTelegramaViewModel.TaBarBody = _unitofwork.BarBodyRepository.DetailsBarB(id);
bodyTelegramaViewModel.TaBarBody.BarHeaderFk = _unitofwork.BarHeaderRepository.DetailsBarHB(id);
ViewData["TelegramaId"] = HeaderTelegramaId;
return View(bodyTelegramaViewModel);
}
[HttpPost]
public IActionResult Edit(int id, BodyTelegramaViewModel bodyTelegramaViewModel)
{
bodyTelegramaViewModel.TaBarBody.BarHeaderId = id;
_unitofwork.BarBodyRepository.Update(bodyTelegramaViewModel.TaBarBody);
_unitofwork.Save();
return View(bodyTelegramaViewModel);
}
Then in your Edit View,change it to:
<form asp-action="Edit">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<input type="hidden" asp-for="#Model.TaBarBody.Id" />
<label asp-for="#Model.TaBarBody.Codstatie1" class="control-label">Cod Statie 1</label>
<input asp-for="#Model.TaBarBody.Codstatie1" class="form-control" />
<span asp-validation-for="#Model.TaBarBody.Codstatie1" class="text-danger"></span>
</div>
<div>
<input type="submit" asp-route-id="#ViewBag.TelegramaId" value="Save"/>
</div>
</form>
Then in your Edit post action,the id will be the TaBarHeader.Id.
Test Result:

PartialView on each list items

I have a in item list in each row has an edit button, which is supposed to open a partial view with the elements data to edit.
In the loop I use to fill tge datatable, I also create the partial views for each row element.
When I click the buton it always opens the first element partial view, even if I press the Nth element.
How do I get the code to open the corresponding partial view?
Code:
<table class="table table-hover" id="tabela_rota">
<thead>
<tr>
<th>
</th>
<th>
Cliente
</th>
<th>
Rota
</th>
<th>
Distância Ideal
</th>
<th>
Ativa
</th>
<th></th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<partial>
#{await Html.RenderPartialAsync("Edit", item);}
</partial>
<tr>
<td width="15">
</td>
<td width="15%">
#Html.DisplayFor(modelItem => item.id_cliente)
</td>
<td width="25%">
#Html.DisplayFor(modelItem => item.nome)
</td>
<td width="15%">
#Html.DisplayFor(modelItem => item.distancia_ideal)
</td>
<td width="10%">
#Html.DisplayFor(modelItem => item.activa)
</td>
<td>
<button type="button" class="btn btn-outline-primary" onclick="openNavEdit()">
Editar
</button>
<button type="button" class="btn btn-outline-danger">Delete</button>
</td>
</tr>
}
</tbody>
</table>
JS Function:
function openNavEdit() {
document.getElementById("mySidepanelEdit").style.width = "350px";
}
View:
#model GestaoCircuitos.Models.Rota
#{
ViewData["Title"] = "Editar";
}
<div id="mySidepanelEdit" class="sidepanel">
<div id="top_title">
<h6 id="nova_rota">Editar Rota</h6>
<button class="closebtn" onclick="closeNavEdit()">×</button>
</div>
<div class="row form-row-rotas">
<div class="col-12">
<form asp-action="Edit" class="form-rotas">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<input type="hidden" asp-for="id" />
<div class="form-label-group">
<input id="nome" class="form-control" placeholder="Nome" />
<label asp-for="nome" class="control-label">Nome</label>
<span asp-validation-for="nome" class="text-danger"></span>
</div>
<div class="form-label-group">
<input type="text" asp-for="distancia_ideal" class="form-control" placeholder="Distância ideal" />
<label asp-for="distancia_ideal" class="control-label">Distância ideal</label>
<span asp-validation-for="distancia_ideal" class="text-danger"></span>
</div>
<div class="form-group form-check">
<label class="form-check-label">
<input class="form-check-input" asp-for="activa" /> Ativa
</label>
</div>
<div class="form-group">
<input type="submit" value="Editar" class="btn btn-primary" />
</div>
</form>
</div>
</div>
</div>
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
It's because you're opening based on ID. An ID attribute needs to be unique throughout a document. If you select on an ID, you'll only get the first element.
You'll have to give each edit modal either a unique ID or a class to select from. Try this:
#model GestaoCircuitos.Models.Rota
#{
ViewData["Title"] = "Editar";
}
<div id="sidepanel-edit-#(item.id)" class=" sidepanel">
<div id="top_title">
<h6 id="nova_rota">Editar Rota</h6>
<button class="closebtn" onclick="closeNavEdit(#(item.id))">×</button>
</div>
<div class="row form-row-rotas">
<div class="col-12">
<form asp-action="Edit" class="form-rotas">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<input type="hidden" asp-for="id" />
<div class="form-label-group">
<input id="nome" class="form-control" placeholder="Nome" />
<label asp-for="nome" class="control-label">Nome</label>
<span asp-validation-for="nome" class="text-danger"></span>
</div>
<div class="form-label-group">
<input type="text" asp-for="distancia_ideal" class="form-control" placeholder="Distância ideal" />
<label asp-for="distancia_ideal" class="control-label">Distância ideal</label>
<span asp-validation-for="distancia_ideal" class="text-danger"></span>
</div>
<div class="form-group form-check">
<label class="form-check-label">
<input class="form-check-input" asp-for="activa" /> Ativa
</label>
</div>
<div class="form-group">
<input type="submit" value="Editar" class="btn btn-primary" />
</div>
</form>
</div>
</div>
</div>
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
Above, we add a unique id for each edit edit form. Then we can reference those unique id attributes in the main template:
<table class="table table-hover" id="tabela_rota">
<thead>
<tr>
<th>
</th>
<th>
Cliente
</th>
<th>
Rota
</th>
<th>
Distância Ideal
</th>
<th>
Ativa
</th>
<th></th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<partial>
#{await Html.RenderPartialAsync("Edit", item);}
</partial>
<tr>
<td width="15">
</td>
<td width="15%">
#Html.DisplayFor(modelItem => item.id_cliente)
</td>
<td width="25%">
#Html.DisplayFor(modelItem => item.nome)
</td>
<td width="15%">
#Html.DisplayFor(modelItem => item.distancia_ideal)
</td>
<td width="10%">
#Html.DisplayFor(modelItem => item.activa)
</td>
<td>
<button type="button" class="btn btn-outline-primary" onclick="openNavEdit(#(item.id)">
Editar
</button>
<button type="button" class="btn btn-outline-danger">Delete</button>
</td>
</tr>
}
</tbody>
</table>
and your Javascript would look like:
function openNavEdit(id) {
document.getElementById("sidepanel-edit-" + id).style.width = "350px";
}
function closeNavEdit(id) {
document.getElementById("sidepanel-edit-" + id).style.width = "0";
}
Something to note, I'm assuming your model has an id attribute.

Form fill in play framework scala doesn't work

I'm creating an application with list of employees. An admin can see the list of employees and change their data. When he clicks "change" button, html form should be filled with chosen employee data so he could change it. I used standard mechanism in play framework but it doesn't work. I was debugging it and everything looks ok (employee data is set to form) but it doesn't display on my html form... I have no idea why...
def loadEmployee(id: Int) = Action { implicit request =>
val loadedEmployee = EmployeeService.getEmployee(id)
val employee = Await.result(loadedEmployee, Duration(5, SECONDS)).get
val employees = Await.result(EmployeeService.listAllEmployees, Duration(5, SECONDS))
val form = EmployeeForm.form.fill(EmployeeFormData(employee.name, employee.additionalInformation, employee.resume))
Ok(views.html.index(form,employees))
}
View file:
#(employeeForm: Form[models.EmployeeFormData],employees : Seq[models.Employee])
#main() {
<form id="employee-data-form" role="form" action='#routes.ApplicationController.addInformation()' method="post" class="form-horizontal" align="center" autocomplete="off">
<fieldset class="employee-fieldset">
<div class="employee-form">
<label class="form-title" style="color: #F8741B; font-size: 22px;font-weight: bold; text-decoration:none">title</label>
</div>
<br/>
<table align="center" cellspacing="20">
<tr>
<td align="left">
<div class="employee-form" id="name_field_label">
<div class="controls col-xs-offset-3 col-xs-9">
<div class="input-group">
<span class="input-group-addon"><span class="glyphicon glyphicon-employee"></span></span>
<strong>name</strong> :
</div>
</div>
</div>
</td>
<td align="center">
<div class="employee-form" id="name_field_value">
<div class="controls col-xs-offset-3 col-xs-9">
<div class="input-group">
<span class="input-group-addon"><span class="glyphicon glyphicon-employee"></span></span>
<input type="text" id="name" name="name" value="" placeholder="First Name" class="form-control input-lg" required>
</div>
</div>
</div>
</td>
</tr>
<tr>
<td align="left">
<div class="employee-form" id="additionalInformation_field_label">
<div class="controls col-xs-offset-3 col-xs-9">
<div class="input-group">
<span class="input-group-addon"><span class="glyphicon glyphicon-employee"></span></span>
<strong>Additional information</strong> :
</div>
</div>
</div>
</td>
<td align="center">
<div class="employee-form" id="additionalInformation_field_value">
<div class="controls col-xs-offset-3 col-xs-9">
<div class="input-group">
<span class="input-group-addon"><span class="glyphicon glyphicon-employee"></span></span>
<textarea rows="4" cols="50" id="additionalInformation" name="additionalInformation" value="" class="form-control input-lg" required></textarea>
</div>
</div>
</div>
</td>
</tr>
<tr>
<td align="left">
<div class="employee-form" id="resume_field_label">
<div class="controls col-xs-offset-3 col-xs-9">
<div class="input-group">
<span class="input-group-addon"><span class="glyphicon glyphicon-employee"></span></span>
<strong>resume</strong> :
</div>
</div>
</div>
</td>
<td align="center">
<div class="employee-form" id="resume_field_value">
<div class="controls col-xs-offset-3 col-xs-9">
<div class="input-group">
<span class="input-group-addon"><span class="glyphicon glyphicon-employee"></span></span>
<textarea rows="4" cols="50" id="resume" name="resume" class="form-control input-lg" required></textarea>
</div>
</div>
</div>
</td>
</tr>
</table>
<br/>
<div class="form-actions controls ynt-btn-xlarge">
<button type="submit" class="btn btn-primary ynt-btn-orange">Add</button>
</div>
</fieldset>
</form>
<div class="employee-display" >
<fieldset>
<legend align="center"><h3>Registered Employees</h3></legend>
<table cellspacing="20">
<tr>
<th>employeeid</th>
<th>firstname</th>
<th>lastname</th>
<th>resume</th>
</tr>
#for(employee <- employees){
<tr>
<td>#employee.id</td>
<td>#employee.name</td>
<td>#employee.additionalInformation</td>
<td>#employee.resume</td>
<td>delete</td>
<td>loadEmployee</td>
</tr>
}
</table>
</fieldset>
</div>
}
Your controller code looks OK - you're filling a Form[EmployeeFormData] and passing it to your template. The trouble is, you never use your employeeForm inside the template - there's no way that form can be populated.
If you read up on the Play documentation for showing forms in a view template you'll see that there is a whole family of helpers available for this purpose. In many cases, they are almost as easy to write as the "plain HTML" version such as you've used. Here's an example:
Where you had:
<div class="input-group">
<span class="input-group-addon"><span class="glyphicon glyphicon-employee"></span></span>
<input type="text" id="name" name="name" value="" placeholder="First Name" class="form-control input-lg" required>
</div>
You will need:
<div class="input-group">
<span class="input-group-addon"><span class="glyphicon glyphicon-employee"></span></span>
#helper.inputText(
employeeForm("name"),
'id -> "name",
'placeholder -> "First Name",
'class -> "form-control input-lg",
'required -> "true"
)
</div>
Notice how you can pass any number of arbitrary arguments into the generated HTML by prefixing with the ' character. This can be very handy, for example if you would like to set extra data- attributes on the input.

Array validation for table inputs in laravel 5.1

I am trying to give a validation for array inputs using table ,if the inputs are empty it should suppose to give a validation for each input box border as red color.
My table code is like we can add multiple no of rows by click add button like
My table view
My validations are coming like as in the below image shown
My current validation output
and i want validation something like as below using $errors and has-feedback in bootstrap laravel
My desired output
table view code:
<form action="{{ url('/executor/event') }}" method="post" enctype="multipart/form-data">
<input type="hidden" name="_token" value="{{{ csrf_token() }}}" />
<table class="table table-bordered table-striped-col nomargin" id="table-data">
<tr align="center">
<td>Event Name</td>
<td>Event Code</td>
<td>Event Date</td>
<td>City</td>
<td>Country</td>
</tr>
<tr>
#if(null != old('eventname'))
#for($i=0;$i<count(old('eventname'));$i++)
<td>
<div class="form-group has-feedback {{ $errors->has('eventname'.$i) ? 'has-error' : '' }}" id="">
<input type="text" class="form-control " autocomplete="off" name="eventname[]" value="{{old('eventname'.$i)}}">
#if ($errors->has('eventname'.$i))
<p class="help-block"><span class="glyphicon glyphicon-exclamation-sign" aria-hidden="true"></span>
{{ $errors->first('eventname'.$i) }}</p>
#endif
</div>
</td>
#endfor
#else
<td>
<div class="form-group has-feedback {{ $errors->has('eventname') ? 'has-error' : '' }}" id="">
<input type="text" class="form-control " autocomplete="off" name="eventname[]" >
#if ($errors->has('eventname'))
<p class="help-block"><span class="glyphicon glyphicon-exclamation-sign" aria-hidden="true"></span>
{{ $errors->first('eventname') }}</p>
#endif
</div>
</td>
#endif
<td>
<input type="text" class="form-control" autocomplete="off" name="eventcode[]" >
</td>
<td>
<input type="text" class="form-control dob" autocomplete="off" name="date[]" >
</td>
<td>
<input type="text" class="form-control" autocomplete="off" name="city[]" >
</td>
<td>
<input type="text" class="form-control" autocomplete="off" name="country[]" >
</td>
<td>
<input type="button" value="+" class="add btn btn-success">
<input type="button" value="-" class="delete btn btn-danger">
</td>
</tr>
</table>
</br>
<center> <button type="submit" class="btn btn-primary" name="submit">Submit</button></center>
</form>
my controller is like below:
public function postEvent( EventRequest $request ) {
$data = Input::get();
for($i = 0; $i < count($data['eventname']); $i++) {
$c= new Event();
$c->event = $data['eventname'][$i];
$c->eventcode = $data['eventcode'][$i];
$c->date = $data['date'][$i];
$c->city = $data['city'][$i];
$c->country = $data['country'][$i];
$c->save();
}
$request->session()->flash('alert-success', 'Event was successful added!');
return redirect('executor/all');
}
and then my validation code in EventRequest.php
public function rules()
{
foreach($this->request->get('eventname') as $key => $val)
{
$rules['eventname.'.$key] = 'required';
}
return $rules;
}
I am using has-feedback error code inside my table for the first input .But still the validations are coming in the same way i could not able to find what was the mistake in my code.
Any help would be appreciated.
Thank you

In Thymeleaf with multiple actions and multiple forms are possible?

Hi i am new in thymeleaf + spring and i start learn it.
and wanted to integrate these 2 form in one page .
that means now 2 forms are in 2 different pages and the th:action are different ..
here i want these 2 forms work in one page
i tried that with a page with 2 forms and 2 actions but that caught error..
Create Standard Code
<form action="#" th:action="#{/saveStandard.html}" th:object="${standard}">
<table>
<h1>Create Standard</h1>
<tr>
<td>Standard Name:</td>
<td><input type="text" placeholder="Enter Standard Name" required="required"
th:field="*{standardName}"/></td>
</tr>
<tr>
<td><input type="submit" value="Create" name="save" /></td>
</tr>
</table>
</form>
Create Division Code
<form action="#" th:action="#{/saveDivision.html}"
th:object="${division}">
<table>
<td>Division Name:</td>
<tr>
<td><input type="text" placeholder="Enter Division Name" required="required"
th:field="*{divisionName}" />
</td>
</tr>
<td><input type="submit" class="btn btn-primary" value="Create"
name="save" /></td>
</table>
</form>
these are controllers..
#RequestMapping(value = Array("/saveStandard.html"), params = Array({ "save" }))
def saveStandard(standard: Standard): String = {
standard.setCreatedDate(new java.sql.Date(new java.util.Date().getTime))
standardService.addStandard(standard)
"redirect:/school/CreateStandard.html"
}
#RequestMapping(value = Array("/saveDivision.html"), params = Array({ "save" }))
def saveDivision(division: Division): String = {
division.setCreatedDate(new java.sql.Date(new java.util.Date().getTime))
divisionService.addDivision(division)
"redirect:/school/CreateDivision.html"
}
if you knew about this question please share your answer here..
and Thanks...
Hi It is posible here a example
HTML Example
<section id="registration" class="section">
<div class="container tagline">
<em>Register User</em><br />
<form method="post" th:action="#{/user/register}" th:object="${newUser}">
<div>
<label for="givenName">Id</label>
<input id="id" placeholder="Enter Id" type="text" th:field="*{id}" />
<p th:if="${#fields.hasErrors('id')}" th:text="${#strings.listJoin(#fields.errors('id'), ', ')}">
</p>
</div>
<div>
<label for="givenName">Name</label>
<input id="name" placeholder="Enter Name" type="text" th:field="*{name}" />
<p th:if="${#fields.hasErrors('name')}"
th:text="${#strings.listJoin(#fields.errors('name'), ', ')}"></p>
</div>
<div>
<label for="email">Email</label>
<input id="email" placeholder="Enter the Email" type="text" th:field="*{email}" />
<p th:if="${#fields.hasErrors('email')}"
th:text="${#strings.listJoin(#fields.errors('email'), ', ')}"></p>
</div>
<button type="submit">Create user</button>
</form>
</div>
</section>
<div>
<form method="get" th:action="#{/user/searchById}" th:object="${searchUser}">
<input id="id" placeholder="Search by id" type="text" th:field="*{id}" size="10" >
<button type="submit" >search</button>
</form>
<form method="get" th:action="#{/user/searchByName}" th:object="${searchUser}">
<input id="id" placeholder="Search by Name" type="text" th:field="*{name}" size="10" >
<button type="submit" >search</button>
</form>
<form method="get" th:action="#{/user/searchByEmail}" th:object="${searchUser}">
<input id="id" placeholder="Search by Email" type="text" th:field="*{email}" size="10" >
<button type="submit" >search</button>
</form>
</div>
Spring
#Controller
#RequestMapping("/user")
public class User {
BookingFacadeUserImp userService = new BookingFacadeUserImp();
#GetMapping()
public ModelAndView init() {
return getModelView().addObject("users", getUsersByName("", 100, 0));
}
#PostMapping("/register")
public ModelAndView saveUser(#Valid #ModelAttribute("newUser") UserDTO user, BindingResult result)
throws NumberFormatException, ParseException {
System.out.println("Register: " + user);
userService.createUser(user);
return getModelView().addObject("users", getUsersByName("", 100, 0));
}
#GetMapping("/delete/{id}")
public ModelAndView delete(#PathVariable long id) {
userService.deleteUser(id);
return init();
}
#PostMapping("/update")
public ModelAndView updateUser(#ModelAttribute("updateUser") UserDTO user) {
userService.updateUser(user);
return init();
}
#GetMapping("/searchById")
public ModelAndView searchById(#ModelAttribute("searchUser") UserDTO user) {
if (user.getId() > 0)
return getModelView().addObject("users", getUsersById(user.getId()));
else
return init();
}
#GetMapping("/searchByName")
public ModelAndView searchByName(#ModelAttribute("searchUser") UserDTO user) {
if (!user.getName().equals(""))
return getModelView().addObject("users", getUsersByName(user.getName(),100,0));
else
return init();
}
public ModelAndView getModelView() {
ModelAndView model = new ModelAndView("user");
model.addObject("newUser", new UserDTO());
model.addObject("searchUser", new UserDTO());
return model;
}
public List<UserDTO> getUsersById(long id) {
List<UserDTO> list = new ArrayList<UserDTO>();
list.add((UserDTO) userService.getUserById(id));
return list;
}
public List<com.example.demo.task1.model.User> getUsersByName(String name, int pageSiza, int pageNum) {
return userService.getUsersByName(name, pageSiza, pageNum);
}
public List<com.example.demo.task1.model.User> getUsersByEmail(String email) {
return (List<com.example.demo.task1.model.User>) userService.getUserByEmail(email);
}
}