I am creating a form dynamically with the data that I get from the backend:
{
"title": "Contact Me",
"fields": [
{
"label": "Name",
"type": "textbox",
"required": "1"
},
{
"label": "Email",
"type": "email",
"required": "1"
},
{
"label": "Message",
"type": "textarea",
"required": "1"
},
{
"label": "Submit",
"type": "submit",
"required": null
}
]
}
In Vue the component where I am making this form looks like this:
<form #submit.prevent="submit()" class="form">
<template v-for="input in ninjaForm.fields">
<div v-if="input.type != 'submit' && input.type != 'textarea'" class="control">
<input
v-bind:value="form[input.label]"
class="input is-large"
:type="input.type"
:name="input.label.toLowerCase()"
:required="input.required == 1">
<label>{{ input.label }}</label>
</div>
<div v-if="input.type == 'textarea'" class="control">
<textarea
v-bind:value="form[input.label]"
class="textarea"
:name="input.label.toLowerCase()">
</textarea>
<label>{{ input.label }}</label>
</div>
<div v-if="input.type == 'submit'">
<button class="button is-primary">{{ input.label }}</button>
</div>
</template>
</form>
I would like to submit this data back to the backend, but I am not sure how to do that, I have tried with something like this:
data() {
return {
form: {},
};
},
methods: {
submit() {
let payload = {
headers: {
'Content-Type': 'application/json'
},
params: JSON.parse(JSON.stringify(this.form))
};
console.log(payload);
this.$backend.post('submit', null, payload)
.then(_ => {
this.response = 'Meldingen ble sendt!';
}, err => {
console.warn(err);
this.response = 'En feil oppstod under innsending av skjemaet, prøv igjen senere.';
});
}
}
But when I am doing console.log(this.form) I get an observer object, and if I do console.log(payload) I get an empty params property. What am I doing wrong and how should I fix this so that I can send form data as a params object?
I have tried with setting the form properties on created method, like this:
created() {
this.ninjaForm.fields.forEach(field => this.form[field.label.toLowerCase()] = '');
},
Which has made an object with properties that looks like this:
form: {
email:"",
message:"",
name:"",
submit:""
}
But, when I was submitting the form, the values of this properties where still empty:
v-bind:value="form[input.label.toLowerCase()]"
I have also tried with changing v-bind:value to v-model, but then I have got an error:
v-model does not support dynamic input types. Use v-if branches
instead.
Please check this thread:
https://github.com/vuejs/vue/issues/3915#issuecomment-294707727
Seems like it works with v-model. However, this doesn't work when you use a v-bind on the input type. The only workaround is to create a v-if for every possible form type. Really annoying, but there seems to be no apparent other solution.
Related
TL;DR
When using the 'required'-validator, then it doesn't update, when I insert content into a text-field.
CodeSandbox: https://codesandbox.io/s/confident-benz-x1lq8?file=/src/App.vue
Further details
I'm experiencing a wierd bug - and I've been sitting with it all day! I'm afraid that I'm missing something obvious, but I'm starting to get the feeling, that it could be a bug in the Vuelidate-library.
I have a simple form like this:
<div class="field__container">
<div>
<label for="emailToInvite">Email to invite</label> <br />
<input
type="email"
id="emailToInvite"
name="emailToInvite"
v-model="$v.emailToInvite.$model"
/>
<div class="errors" v-if="showErrors">
<p v-if="!$v.emailToInvite.required">Email to invite is required.</p>
<p v-if="!$v.emailToInvite">The written email is not valid.</p>
</div>
</div>
</div>
<button type="button" #click="submitForm()">Submit</button>
and the logic:
import { required, email } from "vuelidate/lib/validators";
export default {
data() {
return {
number: 1,
showAll: false,
submitAttempts: 0,
};
},
computed: {
showErrors() {
if (this.submitAttempts > 0) {
if (this.$v.$invalid) {
return true;
}
}
return false;
},
},
methods: {
submitForm() {
this.submitAttempts++;
},
resetAll() {
this.submitAttempts = 0;
this.$v.emailToInvite.$model = "";
},
},
validations: {
emailToInvite: {
required,
email,
},
},
}
And when I insert some text in the emailToInvite-field, then the 'required'-validator stays 'false'.
Another wierd thing is that the 'email'-validator is true, when the input is just an empty string.
All this can be seen in this CodeSandbox: https://codesandbox.io/s/confident-benz-x1lq8?file=/src/App.vue
What am I doing wrong?
I noticed a few things you should change -
First, you must add emailToInvite: '' to data:
data() {
return {
number: 1,
showAll: false,
submitAttempts: 0,
emailToInvite: ''
};
},
I'm not sure how Vuelidate works, but it seems it doesn't create the property for you. So it can't track the change properly.
Second, the showErrors computed property is set to 'false' until you press on 'Submit'. So you won't see the error message before you click on 'Submit'. Set it to 'true' if you want to see the error message (or hide it) while you type.
I am trying to set some objects in a Bootstrap-Vue form select which I get via JSON.
The JSON is made up of teacher objects from the following fields:
[
{
"id": 1,
"name": "John",
"surname": "Doe",
"email": "john.doe#gmail.com"
}
]
What I'm trying to do is put the name and surname in the select list, that is the full name.
I have already managed to do this via a computed property by processing the list.
But now I want that when I select a teacher, the list of courses is filtered according to the chosen teacher.
To do this I need the teacher's email, which I can't recover, having processed the teachers to get the full name.
Consequently, I can't even update the list of courses based on the teacher chosen.
This is the code for the template:
<b-form-group
id="input-group-3"
label="Docente:"
label-for="input-3"
>
<b-form-select
v-model="teacher"
:options="teachers"
value-field="item"
text-field="fullName"
required
#change="filterCourse"
></b-form-select>
<div class="mt-3">
Selected: <strong>{{ teacher }}</strong>
</div>
</b-form-group>
This is the script code:
import { mapGetters, mapActions } from "vuex";
export default {
data() {
return {
teacher: "",
course: "",
};
},
created: function() {
this.GetActiveTeachers();
this.GetActiveCourses();
},
computed: {
...mapGetters({
ActiveTeacherList: "StateActiveTeachers",
ActiveCourseList: "StateActiveCourses",
FilteredTeacherList: "StateTeacherByCourse",
FilteredCourseList: "StateCourseByTeacher",
}),
teachers: function() {
let list = [];
this.ActiveTeacherList.forEach((element) => {
let teacher = element.name + " " + element.surname;
list.push(teacher);
});
return list;
},
},
methods: {
...mapActions([
"GetActiveTeachers",
"GetActiveCourses",
"GetCourseByTeacher",
"GetTeacherByCourse",
"AssignTeaching",
]),
async filterCourse() {
const Teacher = {
teacherEmail: "john.doe#gmail.com", // For testing purpose
};
try {
await this.GetCourseByTeacher(Teacher);
} catch {
console.log("ERROR");
}
},
async filterTeacher() {
const Course = {
title: "Programming", // For testing purpose
};
try {
await this.GetTeacherByCourse(Course);
} catch {
console.log("ERROR");
}
},
},
};
You're currently using the simplest notation that Bootstrap Vue offers for form selects, an array of strings.
I suggest you switch to use their object notation, which will allow you to specify the text (what you show in the list) separately from the value (what's sent to the select's v-model).
This way, you'll be able to access all the data of the teacher object that you need, while still being able to display only the data you'd like.
We can do this by swapping the forEach() in your teachers computed property for map():
teachers() {
return this.ActiveTeacherList.map((teacher) => ({
text: teacher.name + " " + teacher.surname,
value: teacher
}));
},
Then, all you need to do is update your filterCourse() handler to use the new syntax, eg.:
async filterCourse() {
const Teacher = {
teacherEmail: this.teacher.email,
};
try {
await this.GetCourseByTeacher(Teacher);
} catch {
console.log("ERROR");
}
},
As a final note, if you don't want or need the full object as the value, then you can mold it to be whatever you need, that's the beauty of this syntax.
For example, you want the full name and email, instead of the parts:
value: {
fullName: teacher.name + " " + teacher.surname,
email: teacher.email
}
Here's two different options you can do.
One would be to generate the <option>'s inside the select yourself, using a v-for looping over your teachers, and binding the email property to the value, and displaying the name and surname inside the option.
This will make your <b-select>'s v-model return the chosen teachers e-mail, which you can then use in your filter.
new Vue({
el: '#app',
data() {
return {
selectedTeacher: null,
activeTeachers: [{
"id": 1,
"name": "Dickerson",
"surname": "Macdonald",
"email": "dickerson.macdonald#example.com"
},
{
"id": 2,
"name": "Larsen",
"surname": "Shaw",
"email": "larsen.shaw#example.com"
},
{
"id": 3,
"name": "Geneva",
"surname": "Wilson",
"email": "geneva.wilson#example.com"
}
]
}
}
})
<link href="https://unpkg.com/bootstrap#4.5.3/dist/css/bootstrap.min.css" rel="stylesheet" />
<link href="https://unpkg.com/bootstrap-vue#2.21.2/dist/bootstrap-vue.css" rel="stylesheet" />
<script src="https://unpkg.com/vue#2.6.12/dist/vue.min.js"></script>
<script src="https://unpkg.com/bootstrap-vue#2.21.2/dist/bootstrap-vue.js"></script>
<div id="app">
<b-select v-model="selectedTeacher">
<option v-for="teacher in activeTeachers" :value="teacher.email">
{{ teacher.name }} {{ teacher.surname }}
</option>
</b-select>
{{ selectedTeacher }}
</div>
The other option would be to change your computed to return an array of objects instead of simple strings as you're currently doing.
By default <b-select> expects the properties value and text if you use an array of objects in the options prop.
Here you would bind the email for each teacher to the value, and the name and surname to the text prop.
This will make your <b-select>'s v-model return the chosen teachers e-mail, which you can then use in your filter.
Reference: https://bootstrap-vue.org/docs/components/form-select#options-property
new Vue({
el: '#app',
data() {
return {
selectedTeacher: null,
activeTeachers: [{
"id": 1,
"name": "Dickerson",
"surname": "Macdonald",
"email": "dickerson.macdonald#example.com"
},
{
"id": 2,
"name": "Larsen",
"surname": "Shaw",
"email": "larsen.shaw#example.com"
},
{
"id": 3,
"name": "Geneva",
"surname": "Wilson",
"email": "geneva.wilson#example.com"
}
]
}
},
computed: {
teacherOptions() {
return this.activeTeachers.map(teacher => ({
value: teacher.email,
text: `${teacher.name} ${teacher.surname}`
}));
}
}
})
<link href="https://unpkg.com/bootstrap#4.5.3/dist/css/bootstrap.min.css" rel="stylesheet" />
<link href="https://unpkg.com/bootstrap-vue#2.21.2/dist/bootstrap-vue.css" rel="stylesheet" />
<script src="https://unpkg.com/vue#2.6.12/dist/vue.min.js"></script>
<script src="https://unpkg.com/bootstrap-vue#2.21.2/dist/bootstrap-vue.js"></script>
<div id="app">
<b-select v-model="selectedTeacher" :options="teacherOptions"></b-select>
{{ selectedTeacher }}
</div>
I wonder if someone could answer this question for me, maybe I'm using Vue in the incorrect way here.
I'm using vue-router to link to a .vue file with a template. So I'm referencing the below code using Submit Artwork
I'm developing a form, and want to use the toFormData() function which I believe is on the Vue() instance. I cannot access the vue instance however.
At the moment my call to app.toFormData(var) or this.toFormdata(var) will produce an error "404 cannot POST" since it's failing invalid function.
How do I access this function so I can use it to parse the input form data?
<template>
<div class="submitArtwork">
<div class="container">
<hr class="bg-info">
<form id="paintingForm" action="#" method="post">
<div class="form-group">
<v-text-field
name="aa_name"
label="Name of Painting"
id="aa_name"
v-model="newPainting.aa_name"
></v-text-field>
<v-autocomplete
label="Medium"
:items="mediums"
v-on:mouseover="activateHelper('mediumHelper');"
v-on:mouseleave="activateHelper('');"
v-model="newPainting.aa_medium"
></v-autocomplete>
<v-autocomplete
label="Country (optional)"
:items="country_list"
v-on:mouseover="activateHelper('countryHelper');"
v-on:mouseleave="activateHelper('');"
v-model="newPainting.aa_country"
></v-autocomplete>
<v-autocomplete
label="Tags (optional)"
:items="tags"
multiple
v-on:mouseover="activateHelper('tagHelper');"
v-on:mouseleave="activateHelper('');"
v-model="newPainting.aa_tags"
></v-autocomplete>
<v-file-input :rules="rules" prepend-icon="attachment" accept="image/*" multiple label="File input" #change="onFilePicker"></v-file-input>
<v-switch
v-model="consentCheck"
:label="`Consent: ${consentCheck.toString()}`"
></v-switch>
</div>
<div class="form-group">
<button class="btn btn-info btn-block btn-lg" #click="showAddModal=false; addPainting();">Submit Painting</button>
</div>
</form>
...
</template>
<script>
export default {
name: 'submitArtwork',
data: function() {
return {
countryHelper: false,
tagHelper: false,
mediumHelper: false,
newPainting: {aa_fbid: "", aa_a_firstname: "", aa_a_surname: "", aa_a_email: "", aa_country: "", aa_name: "", aa_tags: "", aa_medium: ""},
country_list: [""],
tags: [,
],
mediums: [
],
errorMsg: false,
successMsg: "",
showEditModal: false,
showAddModal: true,
consentCheck: true,
user: {
picture: { data: { url: '' } }
},
rules: [
value => !value || value.size > 2000000 || 'Photo size should be less than 2 MB!',
],
}
},
mounted() {
showAddModal=true;
},
methods: {
activateHelper(helper) {
this.countryHelper=false
this.tagHelper=false
this.mediumHelper=false
if(helper == "countryHelper") {
this.countryHelper=true
}
else if(helper == "tagHelper") {
this.tagHelper=true
}
else if(helper == "mediumHelper") {
this.mediumHelper=true
}
},
addPainting() {
// ERRORS OUT HERE // ------------------------------------>
var formData = toFormData(this.newPainting)
axios.post("http://localhost/process.php?action=create", formData).then(function(response) {
app.newUser = {name: "",email: "",phone: ""};
if(response.data.error) {
app.errorMsg = response.data.message;
}
else{
app.succcessMsg = response.data.message;
app.getAllUsers();
}
});
*/
},
}
}
</script>
<style>
...
</style>
Thanks
The problem is that toFormData is not a method on your instance (Vue does not come with any predefined instance methods, except for lifecycle hooks). You would also have to access instance methods through this.method().
Could you mean the HTML FormData API instead?
https://developer.mozilla.org/en-US/docs/Web/API/FormData
You can create a computed property and inside it prepare your form data for request. Iterate over JSON properties and add each data to form data. Or you can add ref=“form” to form and use like this:
var formData = new FormData(this.$refs.form)
I've written a custom validator like this:
created () {
this.$validator.extend('validateCert', {
getMessage: (field) => {
return field + ' is not a valid certificate';
},
validate: (value) => {
return value.startsWith('-----BEGIN CERTIFICATE-----') && value.endsWith('-----END CERTIFICATE-----');
}
});
}
I've attached it to a text area inside a modal:
<div class="pb-3 mr-4">
<b-form-textarea
type="text"
v-validate="'required|validateCert'"
data-vv-validate-on="change"
v-model.trim="signedCerts[index]"
data-vv-scope="uploadCert"
:name="'certificate_' + index"
:class="[{'is-invalid': errors.has('certificate_' + index)}]"
rows="15"/>
<fr-validation-error :validatorErrors="errors" :fieldName="'certificate_' + index"></fr-validation-error>
</div>
Then - on button click I do the following:
uploadCerts (event) {
let idmInstance = this.getRequestService(),
body = {
fromCSR: true,
certs: _.each(this.signedCerts, (cert) => {
JSON.stringify(cert);
})
};
this.$validator.validateAll('uploadCert').then((valid) => {
// Prevent modal from closing
event.preventDefault();
if (valid) { // some more logic
If I inspect the computed errors object, I will see my failed validation:
{
"items": [
{
"id": "19",
"field": "certificate_0",
"msg": "certificate_0 is not a valid certificate",
"rule": "validateCert",
"scope": "uploadCert",
"regenerate": {
"_custom": {
"type": "function",
"display": "<span>ƒ</span> regenerate()"
}
}
}
]
}
and the value of 'valid' (either true or false) is accurate at all times. I'm just not seeing my error classes being triggered.
Hard to completely answer the question because part of it depends on what happens in fr-validation-error, but I think the problem is how you're using scopes.
When you define data-vv-scope="uploadCert" that means that every reference to field-name has to be prefaced by uploadCert. in errors. So when you specify in your :class that errors.has('certificates_'+index), you have to change that to errors.has('uploadCert.certificates_'+index).
Here's how it would look in full (minus the bootstrap-vue and multiple fields bits):
<textarea
v-validate="'required|validateCert'"
data-vv-validate-on="change"
data-vv-scope="uploadCert"
v-model.trim="signedCert"
name="certificate"
class="form-control"
:class="{ 'is-invalid': errors.has('uploadCert.certificate') }"
rows="10"
>
</textarea>
Full working example for one certificate upload field: https://codesandbox.io/s/z2owy0r2z3
Using ng-repeat I am creating bunch of forms with values in it. With each form there is also button to add rows to that particular form with new fields. Code is below
HTML:
<form name="{{form.name}}"
ng-repeat="form in forms">
<h2>{{form.name}}</h2>
<div ng-repeat="cont in form.contacts">
<input type="text" class="xdTextBox" ng-model="cont.ac"/>
<input type="text" class="xdTextBox" ng-model="cont.a_number"/>
<input type="text" class="xdTextBox" ng-model="cont.p_id"/>
</div>
<button ng-click="submit(form)">Submit</button>
<button ng-click="addFields(form)">Add</button>
<hr>
</form>
Javascript:
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.forms = [{
"name" : "form1", "ac": 251, "a_number": "7933", "p_id": 33
}, {
"name": "form2", "ac": 252, "a_number": "7933", "p_id": 4
}, {
"name": "form3", "ac": 253, "a_number": "7362", "p_id": 3
}];
$scope.addFields = function (form) {
form.contacts.push({name:'', ac: '', a_number: '', p_id: '' });
}
$scope.submit = function(form){
console.log(form.contacts);
}
});
It is not working. Here is the plunker for it:
http://plnkr.co/edit/THdtLgkwKrV7imqZGjL2?p=preview
This is how it should be looking(Difference is data object received from db is little different than this previously asked question):
http://plnkr.co/edit/fETiSYVW7Y5C1yTCwizd?p=preview
Please let me know where the problem is. Thanks
Your addFields method is the problem. Just add a case for when form.contacts is undefined and set it to empty array. Or make each form item start with a contacts key set to an empty array.
$scope.addFields = function (form) {
if(typeof form.contacts === 'undefined') {
form.contacts = [];
}
form.contacts.push({name:'', ac: '', a_number: '', p_id: '' });
}
Works with that change in this fork of your plunk.
Angular also has a helper function for determining when something is undefined you might want to use though I do not know if it really makes any difference.
angular.isUndefined(form.contacts)