Im generating a table and form to edit each field but when I try to edit it, the data displayed in the input fields is incorrect.
HTML
<form (ngSubmit)="onEditSubmit()">
<span>What the form gets</span>
<div *ngFor="let k of keys; let i = index" class="form-group row">
<span>{{k|uppercase}}</span>
<div class="col-md-9">
<input [(ngModel)]="updateModels[keys[i]]" type="text" name="text-input" class="form-control" placeholder="{{k}}" />
</div>
</div>
<button>Submit</button>
</form>
JS
public data: any = [{id: 1, code1: "VALUE1", code2: "VALUE2", code3: "VALUE3"},{id: 2, code1: "TEST1", code2: "TEST2", code3: "TEST3"}];
public keys: any = ["code1","code2","code3"];
public activeRoleId = '';
public updateModels: any = {};
public toEditData: any = "";
public editedData: any = "";
constructor() {
}
onEditSubmit() {
this.editedData = this.updateModels;
}
/*CLick on element actions*/
editElement(item): void {
for (let i = 0; i < this.keys.length; i++) {
this.updateModels[this.keys[i]] = item[this.keys[i]];
}
console.log(this.updateModels);
this.toEditData = this.updateModels;
this.activeRoleId = item.id;
}
Plunker
This error is caused because of you are using a form. If you'd remove the form tags, this would work as you want. BUT, since you are using a form, each name-attribute has to be unique, so that these fields are evaluated as separate form fields.
So the solution for your problem is quite simple, just assign an unique name to your fields, you can make use of the index, so change:
name="text-input"
for example to the following:
name="text-input{{i}}"
Then it works like a charm! :) Here's the forked
Plunker
Related
I'm trying to display an edit form with current value from the database.
Here's the Controlller.
public function edit(PenerimaanHadiahSponsor $id)
{
$collection = PenerimaanHadiahSponsor::find($id);
$dataanak = Anak::find($id);
$datatp = TipeHadiahSponsor::find($id);
// dd($dataanak);
return view('sponsor.penerimaan.updatetrx', compact('collection', 'dataanak', 'datatp'));
}
For now, I try to iterate the $datanak collection, but it returns that property [id] does not exist on the collection.
Here's the blade view file
<div class="mb-3">
<label class="form-label" for="basic-form-gender">Pilih Anak</label>
<select class="form-select" id="basic-form-gender" aria-label="Default select example" name="id_anak">
<option selected="selected">Pilih Anak yg Dapat Hadiah</option>
#foreach ($dataanak as $dtanak)
<option value="{{ $dtanak -> id }}">{{ $dtanak -> fullname }}</option>
#endforeach
</select>
</div>
I expect that it could return this data because it has relation with my curent model table which named penerimaan_data_sponsors
https://cdn.discordapp.com/attachments/856336794068189208/1051057589376532580/image.png
When I try to dd($dataanak) with this method:
$dataanak = Anak::where('id', 1)->get();
It returns the collection using id = 1, but when I used the current data id which is 12, it's returns blank array. Because the current data I want to edit had id 12.
https://cdn.discordapp.com/attachments/856336794068189208/1051058294464188456/image.png
the fix was this. I removed the model 'PenerimaanHadiahSponsor' from edit function.
public function edit($id)
{
$collection = PenerimaanHadiahSponsor::find($id);
$dataanak = Anak::find($id);
$datatp = TipeHadiahSponsor::find($id);
dd($dataanak->fullname);
// return view('sponsor.penerimaan.updatetrx', compact('collection', 'dataanak', 'datatp'));
}
<thymeleaf.version>3.0.9.RELEASE</thymeleaf.version>
<thymeleaf-layout-dialect.version>2.2.2</thymeleaf-layout-dialect.version>
Springboot
How to construct expression for th:action "action url" in form? Url depends on "name" variable.
I'm trying like this, but it's not working:
<form method="get"
th:action="#{'/' + {baseUrl}(baseUrl=${#strings.isEmpty(name) ? '' : 'user/find/'})}">
<input type="text" th:value="${name}"/>
<button type="submit">Find</button>
<button type="button"
th:classappend="${#strings.isEmpty(name)}?'hidden':''"
onclick="clearSearch()">X</button>
</form>
and I tried this, doesn't work too:
<form th:with="baseUrl=(${#strings.isEmpty(name) ? '/' : '/user/find/'})"
th:action="#{${baseUrl}}" method="get">
Oh sorry. I realized Thymeleaf is not for dynamically handling input field.
I just write a JS code.
$(document).ready(function () {
var searchForm = $(this).find('#searchForm');
searchForm.on('click', '#searchButton', function (event) {
var form = $('#searchForm');
var name = $('#searchInputName').val();
var addUrl = (name === '') ? '/' : '/user/find/';
form.attr('action', addUrl);
});
});
after that I realized I can realize it simpler in my controller :)
#GetMapping("/user/find/")
public String getNextPage(Model model, Pageable pageable,
#RequestParam(name = "name") String name) {
if (name.isEmpty()) return "redirect:/";
....
}
You can write dynamic url like below
th:action="#{${#strings.isEmpty(name) ? '/' : '/user/find'}}"
If you want you can add dynamic value to your urls like below
th:action="#{${#strings.isEmpty(name) ? '/' : '/user/find' + name}}"
I have a question for which I couldn't find an answer anywhere in the web. I have a lift-based web application written on Scala. There is a form in my application which is driven by a snippet. I use Mapper for my models, and I use override def validations ... to define model's validation parameters. The template code looks like this:
<form class="lift:GroupManager.addGroup?form=POST&action=add">
<div class="row collapse" style="width: 30em">
<div class="small-8 columns">
<span class="group-name prefix radius"></span>
</div>
<div class="small-4 columns">
<span class="submit button small postfix radius">Add New Group</span>
</div>
</div>
</span>
</form>
The snippet code:
def addGroup = {
object groupName extends RequestVar[String]("")
def doAddGroup() = {
val group = Group.create.createdAt(new java.util.Date).groupName(groupName.is)
group.validate match {
case Nil => {
group.save
S.notice("Group '" + group.groupName.is + "' has been added successfully")
}
case errors:List[FieldError] => {
S.error(errors)
}
}
}
".group-name" #> SHtml.text(groupName.is, groupName(_), "id" -> "group-name") &
".submit" #> SHtml.submit("Add group", doAddGroup)
}
The model's validations override:
object groupName extends MappedString(this, 700) {
override def dbColumnName = "group_name"
override def dbNotNull_? = true
override def validations = valMinLen(1, S.?("Group name should not be empty!")) _ ::
valMaxLen(700, S.?("Group name should not be more than 700 characters long!")) _ ::
valUnique(S.?("Group name should be unique!")) _ ::
super.validations
}
Now everything is perfect except the fact that when invalid data is provided, S.error is used to inform user about problems. What I want to do is to highlight the form element (by applying class="error") in which the data is invalid and add a <span> element with the error message in front of the form element. Is there a simple way to do that with Lift framework? Or I should just traverse through errors:List[FieldError] and fetch field information from that array, which does not seem too elegant to me?
I have no previous experience with FubuMVC HtmlTags library, and I simply got stuck when trying to accomplish a simple nested structure like this:
<ul>
<li>text</li>
<li>text
<ul>
<li>subtext</li>
<li>subtext</li>
</ul>
</li>
<li>text</li>
</ul>
Here's how I have it when building the string:
public static HtmlString ChildNodesRecursive(DocumentNode documentNode)
{
var tag="";
if (documentNode.Children.Count > 0)
{
tag = "<ul>";
foreach (var c in documentNode.Children)
{
tag += "<li>" + c.Name;
tag += ChildNodesRecursive(c);
tag += "</li>";
}
tag += "</ul>";
}
return new HtmlString(tag);
}
Works fine, but I like to use HtmlTags library (outside of FubuMvc, with the HtmlTags separate Nuget).
Edit : I got inspiration from both answers and came up with what I needed. So here's the code I ended up using.
public static HtmlTags.HtmlTag ChildNodesRecursiveHtmlTag(DocumentNode documentNode)
{
var ul = new HtmlTags.HtmlTag("ul");
foreach (var c in documentNode.Children)
{
var li = new HtmlTags.HtmlTag("li");
li.Add("a").Attr("href",c.ContextFullPath).Text(c.Name);
if (c.Children.Count > 0)
{
li.Children.Add(ChildNodesRecursiveHtmlTag(c));
}
ul.Children.Add(li);
}
return ul;
}
I can give you an example which may make things clearer to you:
var ul = new HtmlTag("span").AddClass("form_input");
ul.Modify(t =>
{
foreach (var value in choice)
{
t.Add("input")
.Attr("type", "radio")
.Attr("name", request.Accessor.Name)
.Attr("value", value)
.Add("span")
.AddClass("fixed-width")
.Text(value);
}
});
Gives you something like
<span class="form-input">
<input type="radio" name="bla" value="foo" />
<span class="fixed-width">foo</span>
...etc...
</span>
You can carry on nesting tags with modify and filling in the lambda. I think you will find that what you want to do is possible with the bits of syntax shown.
This code:
var root = new HtmlTags.HtmlTag("ul");
root.Add("li").Text("item1");
var child = root.Add("ul");
child.Add("li").Text("item2");
return root.ToPrettyString();
produces the following output:
<ul>
<li>item1</li><ul>
<li>item2</li>
</ul>
</ul>
In the MVC RC 2 docs, we find:
Expression-based helpers that render input elements generate correct name attributes when the expression contains an array or collection index. For example, the value of the name attribute rendered by Html.EditorFor(m => m.Orders[i]) for the first order in a list would be Orders[0].
Anyone care to link an example of the C# view code (using a List where the result can bind back to the Model upon post)?
Just as a reference, I use the following code to verify the model binds correctly round trip. It simply shows view that allows change, then displays a view with the edited data upon form submission.
[HandleError]
public class HomeController : Controller
{
public ActionResult Index()
{
var myStudents = new List<Student>();
myStudents.Add(new Student { Name = "Harry" });
myStudents.Add(new Student { Name = "Tom" });
myStudents.Add(new Student { Name = "Richard" });
var myClass = new Classroom {Students = myStudents};
return View(myClass); // EditorFor()
}
[HttpPost]
public ActionResult Index( Classroom myClass)
{
return View("IndexPost", myClass); // DisplayFor()
}
This code:
<% for (int count = 0; count < Model.Students.Count; count++ )
{ %><%=
Html.EditorFor(m => m.Students[count]) %><%
}
%>
Rendered this output:
<input class="text-box single-line" id="Students_0__Name" name="Students[0].Name" type="text" value="Harry" />
<input class="text-box single-line" id="Students_1__Name" name="Students[1].Name" type="text" value="Tom" />
<input class="text-box single-line" id="Students_2__Name" name="Students[2].Name" type="text" value="Richard" />
And when I posted the content, the display was this (because I have a Student.ascx):
<table>
<tr><td><span>Harry</span> </td></tr>
<tr><td><span>Tom</span> </td></tr>
<tr><td><span>Richard</span> </td></tr>
</table>
But that's it (I think). Next question is how to get rid of those name="" tags.