Dynamic Vue Form from Input-Elements - forms

I'm building a reusable vue-form-component. For more flexibility the basic idea is to NOT have to specify the form information in the vue-data-object beforehand, but to get the data-structure from the dom-input-elements itself.
On instance-creation the "v-model" attributes are read from the input-tags and applied to the instance via vue.set()
This works fairly well: https://jsfiddle.net/seltsam23/hrL3ec3z/9/
One detail is missing though: I need to only query the children-input-fields, and not the site-wide fields in case I'm using more than one form-component at the same time:
created() {
var inputs = document.querySelectorAll('input'); // works, but this returns ALL elements
var inputs = this.$el.querySelectorAll('input'); // Doesn't work because $el is only available after mounted().
...
}
mounted() {
var inputs = this.$el.querySelectorAll('input'); // works, but attribute "v-model" is removed from inputs at this point
...
}
I've tried to create data-path attribute in the created() phase to store the v-model value on the element itself, but after mount all those created attributes disappear.
Any ideas how to achieve this in an elegant way?

You should be aware that the only reason you see v-model attributes at all is that you're using inline-template. They are in the DOM during the created phase because the template has not yet been processed. What I'm saying is that you're trying to do something pretty hacky, and you probably shouldn't.
It's backward to the normal Vue approach of having the data model drive the DOM, but I know that in some cases it is useful to initialize things from the HTML.
How about this approach?
Vue.component('my-form', {
props: ['init'],
data() {
return {
form: {}
}
},
created() {
this.form = this.init;
}
})
new Vue({
el: '#vue',
})
<script src="//cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.min.js"></script>
<div id="vue">
<my-form inline-template :init="{foo: {bar: 'one', baz: 'two'}}">
<form>
<input type="text" v-model="form.foo.bar">
<span v-text="form.foo.bar"></span>
<hr>
<input type="text" v-model="form.foo.baz">
<span v-text="form.foo.baz"></span>
</form>
</my-form>
</div>

Related

How to get reactive validation with array group?

I have set code this way
errorGroup: any = FormGroup;
this.errorGroup = this.formBuilder.group({
errors: this.formBuilder.array([])
});
For repeat/add new data in group I have add this function which works fine.
addErrorGroup() {
return this.formBuilder.group({
error_code: ['',[Validators.required ]]
})
}
Get controls by this way. I think hear I'm missing something.
get f() { return this.errorGroup.controls.errors; }
In HTML
<select formControlName="error_code" name="error_code" (change)="errorCodeChange($event.target.value , i)">
<option *ngFor="..." value={{...}}>{{...}}</option>
</select>
<span *ngIf="f.error_code.errors.required" class="error-msg">This is required field.</span>
I got this error.
ERROR TypeError: Cannot read property 'errors' of undefined
If that error is coming from HTML, it's because your *ngIf condition is trying to read a value from an undefined object.
At the point where the view is rendered, and checked, it's entirely possible that f (incidentally, you should change that variable name to something more descriptive, but 🤷🏻‍♂️) doesn't have any errors populated yet, so will be undefined.
You can do one of two things here, either, you can wrap the whole thing in another *ngIf to ensure the error_code part of f is populate before accessing it:
<span *ngIf="f && f.error_code">
<span *ngIf="f.error_code.errors.required" class="error-msg">This is required field.</span>
</span>
Or, you can use the safe navigation operator:
<span *ngIf="f?.error_code?.errors?.required" class="error-msg">This is required field.</span>
Note the ? after each object key. This bails out when it hits the first null value, but, the app continues to work as it fails gracefully.
You can read more about it here: https://angular.io/guide/template-syntax#the-safe-navigation-operator----and-null-property-paths
How about if you just do below?
<span *ngIf="errorGroup.get('error_code').errors.required" class="error-msg">
This is required field.
</span>
so by doing this way, you don't need the f() getter in your component file.

Angular 2++ | NgForm: Form.Dirty is Always Dirty

Determine if NgForm Looks Exactly As It Did Before Any User-Input
It seems that form.dirty doesn't redact its value after it has been changed, and form.touched seems to always be false no matter what: dirty is touched, and touched is tetched.
template.html
<form #form="ngForm" (ngSubmit)="handleSubmission($event, {}, form)">
...
<input
#input
type="text"
[name]="item.title"
[(ngModel)]="item.estimate"
(ngModelChange)="handleEstimateChange(item, item.estimate, input, form)"
/>
...
</form>
component.ts
export class LeComponent {
#Input('data') public data: any;
public handleEstimateChange: Function;
constructor(private $: Sandbox) {
this.handleEstimateChange = $.debounce(this.handleEstimate.bind(this), (1000*0.2));
}
handleEstimate(item: any, estimate: number, input: HTMLInputElement, form: NgForm) {
if (!estimate) delete item.esitmate;
(this, item, estimate, input, form);
// Why does form.dirty never change back to pristine again???
}
}
In the TypeScript, I'm debouncing the ngModelChange handler to give Angular a chance to change the form.dirty value before I check it. This is because ngModelChange gets triggered before the NgForm object has been modified.
If !estimate, because estimate === "", then set it back to its original value of undefined. In this case, the form should look exactly like it did before any user-input had occurred.
However, when I put a breakpoint on the line right above the comment and I output form.dirty to the console, the NgForm never changes dirty back to false.
Is it possible to determine if the form looks exactly like it did before any user-input?
Obviously, I can write my own dirty logic, but wouldn't that mean that NgForm is kind of useless? There's got to be something I'm missing, right? How could dirty not mean dirty?
I've taken a look at some other SO questions -- the first one being similar but definitely not the question I am asking. They are asking if this is intentional -- I don't care; I'd like to know how to accomplish the goal above.
Close, but no cigar:
angular2 formcontrol stays dirty even if set to original value
Block routing if form is dirty [ Angular 2 ]
Angular 2 getting only the dirty values in a controlgroup
How do I programmatically set an Angular 2 form control to dirty?
Angular 2.x/4.x & bootstrap: patchValue does not alter dirty flag. Possible bug?
With template-driven forms and a very flat data model, I implemented it like this:
private currentProduct: IProduct;
private originalProduct: IProduct;
get isDirty(): boolean {
return JSON.stringify(this.originalProduct) !== JSON.stringify(this.currentProduct);
}
get product(): IProduct {
return this.currentProduct;
}
set product(value: IProduct) {
this.currentProduct = value;
// Clone the object to retain a copy
this.originalProduct = Object.assign({}, value);
}
But this only works for very simple cases.
As I mentioned in the comments, using reactive forms gives you more flexibility in managing your data model separate from your user entries.
What Was Most Useful
template.html
<form #form="ngForm" (ngSubmit)="handleSubmission($event, {}, form)">
...
<input
#input
type="text"
[name]="item.title"
[attr.name]="item.title"
[(ngModel)]="item.estimate"
(ngModelChange)="handleEstimateChange(item, item.estimate, input, form)"
/>
...
</form>
component.ts
export class LeComponent {
#Input('data') public section: any;
public handleEstimateChange: Function;
private resetFormControl = (input: HTMLInputElement, form: NgForm) => {
var name = input.name, control = form.controls[name];
control.reset();
// control.markAsPristine();
// control.setValue(undefined);
// control.updateValueAndValidity();
};
constructor(private $: Sandbox) {
this.handleEstimateChange = $.debounce(this.handleEstimate.bind(this), (1000*0.2));
}
handleEstimate(item: any, estimate: number, input: HTMLInputElement, form: NgForm) {
if (!estimate) this.resetFormControl(input, form);
(this, item, estimate, input, form);
// Why does form.dirty never change back to pristine again???
}
}
Note
[attr.name]="..." (template.html)
resetFormControl
Basically, simply deleteing the value was not enough because it was still present on the FormControl object (form.controls). To clear it properly, invoke control.reset() for the individual control -- this in-turn invokes .markAsPristine() which communicates to the parent NgForm. Also, input.name was empty as it was only represented by ng-reflect-name unless [attr.name] elucidated the same value -- [name] is really just there because its required by Angular.
Now, anytime an <input /> value changes -- and its falsey -- we reset the input ensuring that if all are falsey, Angular will automatically handle the NgForm's dirty-state correctly.

Binding an html form action to a controller method that takes some parameters

In my Find controller I have a method like:
public Result findLatest(String repoStr) {
............
}
Which is linked through a route:
GET /latest controllers.Find.findLatest(repo: String)
Then, I have a form in a view like:
<form action="#routes.Find.findLatest()" method="get">
....
<select name="repo">....</select>
</form>
But obviously that is failing, because it is expecting some parameters that I do not fulfill in the action. What is the correct way to do this without having to end up leaving the findLatest method taking no parameters in my controller?
You could change the routes to accept an empty string:
GET /latest/:repo controllers.Find.findLatest(repo: String = "")
Then configure your controller function to handle empty string.
That way,
<form action="#routes.Find.findLatest()" method="get">
....
<select name="repo">....</select>
will evaluate repo as an empty string at the controller level.
Edit: Support for this implementation was dropped in Play v 2.1
You may be interested in Play's Optional parameters e.g. play.libs.F.Option[String]
Example: How to handle optional query parameters in Play framework
GET /latest/:repo/:artifact controllers.Find.findLatestArtifact(repo: play.libs.F.Option[String], artifact: play.libs.F.Option[String])
This will allow you flexibility in which arguments need to be provided.
Not sure which language you're using but the link above contains an example for scala and the method declaration in java would look something like:
import play.libs.F.Option;
public static Result findLatestArtifact(Option<String> repo, Option<String> artifact){ ... }
and updated implementation 2.1
Routes with optional parameter - Play 2.1 Scala
EDIT: play 2.1+ Support : Props to #RobertUdah below
Initializing to null:
GET /latest/ controllers.Find.findLatest(repo: String = null)
GET /latest/:repo controllers.Find.findLatest(repo: String)
<form action="#routes.Find.findLatest()" method="get">
Normally all form data go in the body and you can retrieve them in your action method with bindFromRequest() (see docs).
If you really want to pass one form element as a part of the URL then you have to dynamically compose your URL in JavaScript and change your route.
Your route could look like:
GET /latest/:repo controllers.Find.findLatest(repo: String)
And the JavaScript part like (I didn't actually test the code):
<form name="myform" action="javascript:composeUrl();" method="get">
....
<select name="repo">....</select>
</form>
<script>
function submitform() {
var formElement = document.getElementsByName("myform");
var repo = formElement.options[e.selectedIndex].text;
formElement.action = "/lastest/" + repo;
formElement.submit();
}
</script>
Cavice suggested something close to what I consider the best solution for this (since F.Option are not supported anymore with the default binders in Play 2.1 ).
I ended up leaving the route like:
GET /latest controllers.Find.findLatest(repo=null)
and the view like:
<form action="#routes.Find.findLatest(null)" method="get">
<select name="repo"> .... </select>
....
</form>
and in the controller:
public Result findLatest(String repoStr) {
if(repoStr==null) {
repoStr=Form.form().bindFromRequest().get("repo");
.....
This allows me to have a second route like:
GET /latest/:repo controllers.Find.findLatest(repo: String)

knockout.js select element binding loses value on subsequent form submit

I have a knockout viewmodel getting populated from a JSON call.
In a select element in a form, I have a set of options (also coming from viewmodel) and the value, part of observableArray.
The issue is only with the select element and not with input ones -- when submitting the form, only the values that have been assigned to in select contain proper values. So the ones that have been successfully loaded from JSON and presented in form, but left unchanged, will be sent back to server as the first value from the options array.
HTML Form:
<form>
<table >
<thead>
...
</thead>
<tbody data-bind='foreach: ScaledCostEntries'>
<tr>
<td><input data-bind='value: StartDateString' class="startdate" type="text"/></td>
<td><select data-bind='value: InvoiceType, options: $root.InvoiceTypes'></select></td>
<td><a href='#' data-bind='click: $root.removeCost'>Delete</a></td>
</tr>
</tbody>
</table>
<button data-bind='click: addCost'>Add New Row</button>
<button data-bind='click: save' >Update</button>
</form>
In this code above the problem is with InvoiceType, part of the viewmodels ScaledCostEntries observableArray. (Also, if I swap the order of value and options, that will not put a selected value in the select element).
and the JS:
<script type="text/javascript">
$(function () {
var scaledCostModel = function () {
var self = this;
self.ScaledCostEntries = ko.observableArray([]);
self.InvoiceTypes = ko.observableArray([]);
self.addCost = function () {
self.ScaledCostEntries.push({
StartDateString: ko.observable(),
InvoiceType: ko.observable()
});
};
self.removeCost = function (cost) {
cost.IsDeleted = true;
self.ScaledCostEntries.destroy(cost);
};
self.save = function (form) {
jQuery.ajax({
url: '#Request.Url.PathAndQuery',
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: ko.toJSON(self.ScaledCostEntries)
});
};
};
jQuery.getJSON('#Request.Url.PathAndQuery', function (data) {
ko.mapping.fromJS(data, {}, viewModel);
});
var viewModel = new scaledCostModel();
ko.applyBindings(viewModel);
});
</script>
So, to summarize, the issue is with viewmodel's property bound to a select element. When the select is left unchanged (not reselected), the viewmodel will have it's value as the first item from the options (InvoiceTypes) array, when posting to server.
In the end, I might be forgetting something trivial and this is my first more serious knockout.js attempt.
Note: InvoiceType is part of the ScaledCostEntries, which is observableArray.
InvoiceTypes is observableArray.
Both InvoiceTypes and ScaledCostEntries, come from JSON and ScaledCostEntries is sent back.
My assumption is that this is due to how the ScaledCostEntries are being handled on the server on the form submission.
I've run into the problem before (across various server-side frameworks) when I have a main model with a list of dependent models that are being added and removed, and a form submission is done against the main model to update everything.
The problem is that during form submission, when the values in the request are being mapped to the server-side model, blank values are taken to mean "no change" as opposed to "delete this". This works well with properties directly on a model, but doesn't work for lists of dependent models.
There are a couple of ways I've found of dealing with this: use Ajax to delete the underlying model and update the relationship with the main model when the 'remove' or 'delete' button is pressed in the view; or explicitly send the whole list of models each time and explicitly delete and rebuild the list on the server for each form submission. Each are applicable in different situations, and there are probably other approaches that may work well, too.

$_post in Kohana controller

i was wondering if i can get a variable with $_post, in a kohana controller if the controller doesn't 'control' a form.
So, if i insert in a view something like:
<form name="ordering" id="ordering" method="post" action="">
<input type="hidden" id="ordering" value="0">
<select id="ordering" name="ordering">
....
in the controller i put :
$ordering = $_POST['ordering'];
but gives me an error
or
if ($this->request->method == 'POST') {
$ordering = $_POST['ordering'];
}
but in this case it never gets there(at this bunch of code).
so my question is: how can i retrieve in a controller a $_post variable if the controller doesn't handle only a form? thank you!
Kohana 3.0 :
if ($_POST)
{
$ordering = arr::get($_POST, 'ordering');
...
Kohana 3.1 :
if ($ordering = $this->request->post('ordering')) // or just $this->request->post()
{
...
PHP will issue a notice if you attempt to access an undefined array element.
So if the "ordering" form was never submitted, attempting to access $_POST['ordering'] will result in
PHP Notice: Undefined index: ordering in ...
Kohana's Arr class provides a nice helper method to get around this.
If you call
$ordering = Arr::get($_POST, 'ordering', 0);
It will retrieve the ordering value from the post variable. If $_POST['ordering'] is not set, it will return the third parameter instead. You can then try if ($ordering) ...
This is useful for $_POST/$_GET arrays, or any function that accepts arrays – it allows you to concisely specify a fallback behavior rather than having to test with isset.
One of the advantages of Kohana is that the source code tends to be very clean and easy to understand (which is nice because documentation is sparse.) I'd suggest you take a check out the Kohana_Arr class and look at the methods available!
ID's are unique! Use class insted or different IDs.
Your form and the select both have got ordering, change one to something else, like:
<form name="ordering_form" id="ordering_form" method="post" action="">
<input type="hidden" id="ordering_input" value="0">
<select id="ordering" name="ordering">
...
</select>
</form>
and in your Kohana Controller:
if( isset( $_POST['ordering'] ) )
{
$ordering = $_POST['ordering'];
}
this should work, because i cant find any other error