Writing edit-form component using form from "create" component - vue.js

I want to use the form I made in 'create' component in 'edit' component.
There are some properties in data object that i need to populate in edit-component that were empty in create-component, also I want to replace create() method with edit(), method which uses axios to communicate with API.
I am clueless how to proceed with this problem, also I thought this might be a pretty common question to ask but I didn't find any satisfying answer. Is there no way i can replace existing methods in child component? Should I make different component for html form and for relevant methods?
create-component
<template>
<div id="dashboard-form">
<button class="button modal-button"
data-target="#myModal"
#click="modalToggle">
Launch Form
</button>
<div class="modal" id="myModal"
:class="{'is-active': modalStatus}">
<div class="modal-backgound"></div>
<div class="modal-card">
<header class="modal-card-head">
<p class="modal-card-title">Fill a new entry</p>
<button class="delete"
aria-label="close"
#click="modalToggle">
</button>
</header>
<section class="modal-card-body">
<form action="post">
<div class="modal-form" v-if="step === 1">
<div class="field">
<label class="label">Parent's Name</label>
<div class="control">
<input type="text" class="input"
placeholder="Enter parent name here"
v-model="parentName"
v-validate="'required'"
name="parentName"
:class="{'is-danger': errors.has('parentName'),
'is-success': parentName!=='' && !errors.has('parentName')}">
</div>
<p class="help has-text-left is-danger"
v-show="errors.has('parentName')">
{{ errors.first('parentName')}}
</p>
</div>
<div class="field">
<label for="parentContact" class="label">
Parent's Contact Number
</label>
<div class="control">
<input type="tel" class="input"
placeholder="Enter 10 digit mobile number"
v-model="parentContact"
v-validate="{required: true, regex: /^[5-9]\d{9}$/}"
:class="{'is-danger': errors.has('parentContact'),
'is-success': parentContact!=='' && !errors.has('parentContact')}"
name="parentContact">
</div>
<p class="help has-text-left is-danger"
v-show="errors.has('parentContact')">
{{ errors.first('parentContact' )}}
</p>
</div>
<div class="field">
<label class="label">Student's Name</label>
<div class="control">
<input type="text" class="input is-success"
placeholder="enter student name here"
v-model="studentName"
name="studentName">
</div>
</div>
<div class="field">
<label class="label">Tutor's Name</label>
<div class="control">
<input type="text" class="input"
placeholder="Enter tutor's name here"
v-model="tutorName"
v-validate="'required'"
name="tutorName"
:class="{'is-danger': errors.has('tutorName'),
'is-success': tutorName!=='' && !errors.has('tutorName')}">
</div>
<p class="help has-text-left is-danger"
v-show="errors.has('tutorName')">
{{ errors.first('tutorName')}}
</p>
</div>
<div class="field">
<label for="tutorContact" class="label">
Tutor's Contact Number
</label>
<div class="control">
<input type="tel" class="input"
placeholder="Enter 10 digit mobile number"
v-model="tutorContact"
v-validate="{required: true, regex: /^[5-9]\d{9}$/}"
:class="{'is-danger': errors.has('tutorContact'),
'is-success': tutorContact!=='' && !errors.has('tutorContact')}"
name="tutorContact">
</div>
<p class="help has-text-left is-danger"
v-show="errors.has('tutorContact')">
{{ errors.first('tutorContact') }}
</p>
</div>
<div class="field">
<label for="startingDate" class="label">
Tuition Started on
</label>
<div class="control">
<input type="date" class="input"
v-model="startingDate"
v-validate="'required'"
:class="{'is-danger': errors.has('startingDate'),
'is-success': startingDate!='' && !errors.has('startingDate')}"
name="startingDate">
</div>
<p class="help has-text-left"
v-show="errors.has('startingDate')">
{{ errors.first('startingDate') }}
</p>
</div>
<div class="field">
<label for="sessionDuration" class="label">
How long each session lasts(in hours)
</label>
<div class="control">
<input type="text" class="input"
v-model="sessionDuration"
v-validate="'required'"
:class="{'is-danger': errors.has('sessionDuration'),
'is-success': !errors.has('sessionDuration')}"
name="sessionDuration">
</div>
<p class="help has-text-left" v-show="errors.has('sessionDuration')">
{{ errors.first('sessionDuration') }}
</p>
</div>
<div class="field">
<label for="sessionsMonth" class="label">
Number of sessions in a month.
</label>
<div class="control">
<input type="number" class="input"
v-model="sessionsMonth"
v-validate="'required'"
:class="{'is-danger': errors.has('sessionsMonth'),
'is-success': !errors.has('sessionsMonth')}"
name="sessionsMonth">
</div>
<p class="help has-text-left"
v-show="errors.has('sessionsMonth')">
{{ errors.first('sessionsMonth') }}
</p>
</div>
<div class="field">
<label for="fees" class="label">
Fees Charged from Parents
</label>
<div class="control">
<input type="number" class="input"
v-model="fees" v-validate="'required|min_value:500'"
:class="{'is-danger': errors.has('fees'),
'is-success': !errors.has('fees')}"
name="fees">
</div>
<p class="help has-text-left"
v-show="errors.has('fees')">
{{ errors.first('fees') }}
</p>
</div>
<div class="field">
<label for="commission" class="label">
How much commission is being charged?
</label>
<div class="control">
<input type="number" class="input"
v-model="commission"
v-validate="'required|min_value:0|max_value:50'"
:class="{'is-danger': errors.has('commission'),
'is-success': !errors.has('commission')}"
name="commission">
</div>
<p class="help has-text-left"
v-show="errors.has('commission')">
{{ errors.first('commission') }}
</p>
</div>
<div class="field">
<label for="coordinator" class="label">Coordinator</label>
<div class="control">
<div class="select"
:class="{'is-success': coordinator!=='',
'is-danger': coordinator==='' && coordinatorIsFocused}">
<select name="coordinator" v-model="coordinator"
#focus.once="coordinatorToggle">
<option selected disabled>Name of Coordinator</option>
<option value="seth">Himanshu(Seth)</option>
<option value="hk">Himanshu(HK)</option>
<option value="anuj">Anuj</option>
</select>
</div>
</div>
<p class="help has-text-left"
v-show="coordinator==='' && coordinatorIsFocused">
Selecting one of the option is required
</p>
</div>
<div class="field">
<label for="paymentMode" class="label"></label>
<div class="control">
<div class="select"
:class="{'is-success': paymentMode!=='',
'is-danger': paymentMode==='' && paymentModeIsFocused}">
<select name="paymentMode" v-model="paymentMode"
#focus.once="paymentModeToggle">
<option disabled selected>Mode of Payment</option>
<option value="cash">Cash</option>
<option value="paytm">PayTM</option>
<option value="bank seth">Bank Seth</option>
<option value="bank anuj">Bank Anuj</option>
<option value="kotak">Kotak</option>
</select>
</div>
</div>
<p class="help has-text-left"
v-show="paymentMode==='' && paymentModeIsFocused">
Selecting one of the option is required
</p>
</div>
</div>
<div class="modal-form" v-if="step === 2">
<div class="field">
<p class="has-text-left">In which standard student is studing?</p>
<div class="control">
<div class="select"
:class="{'is-success': standard!='',
'is-danger': standard==='' && standardIsFocused}">
<select v-model="standard"
#focus.once="standardToggle()"
#change="emptySubjects()">
<option value="pre-primary">Pre-Primary</option>
<option value="1">Standard 1</option>
<option value="2">Standard 2</option>
<option value="3">Standard 3</option>
<option value="4">Standard 4</option>
<option value="5">Standard 5</option>
<option value="6">Standard 6</option>
<option value="7">Standard 7</option>
<option value="8">Standard 8</option>
<option value="9">Standard 9</option>
<option value="10">Standard 10</option>
<option value="11-sci">Standard 11 - Science</option>
<option value="11-com">Standard 11 - Commerce</option>
<option value="11-art">Standard 11 - Arts</option>
<option value="12-sci">Standard 12 - Science</option>
<option value="12-com">Standard 12 - Commerce</option>
<option value="12-art">Standard 12 - Arts</option>
</select>
</div>
</div>
<p class="help has-text-left is-danger"
v-show="standard==='' && standardIsFocused">
Selecting one of the option is required.
</p>
</div>
<p>Which subject(s) does the student need help with?</p>
<div class="field">
<div class="control" v-for="(subject,index) in subjectListFinal" :key="index">
<label class="checkbox">
<input type="checkbox" :value="subject" v-model="subjects" v-validate="'required'" name="subjects">
{{subject}}
</label>
</div>
</div>
<p class="help has-text-left is-danger"
v-show="errors.has('subjects')">
Select atleast one subject.
</p>
</div>
</form>
</section>
<footer class="modal-card-foot">
<div class="field is-grouped">
<button class="button is-link"
#click="prev" v-show="step===2">
Previous
</button>
<button class="button is-link"
#click="next" v-show="step===1">
Next
</button>
<button class="button is-link"
#click="validateBeforeSubmit" v-show="step===2">
Submit
</button>
</div>
</footer>
</div>
<label class="modal-close is-large" #click="modalToggle"></label>
</div>
</div>
</template>
<script>
import axios from 'axios'
export default {
name: 'DashboardForm',
data () {
return {
modalStatus: false,
standardIsFocused: false,
coordinatorIsFocused: false,
paymentModeIsFocused: false,
step: 1,
parentName: '',
parentContact: '',
studentName: '',
tutorName: '',
tutorContact: '',
startingDate: '',
sessionDuration: '1',
sessionsMonth: 24,
fees: null,
commission: null,
coordinator: '',
paymentMode: '',
standard: '',
subjects: [],
prePrimarySubjects: [
'Abacus',
'Handwriting Basics',
'English Phonetics',
'English',
'KG Academics'
],
standard1To5Subjects: [
'All Subjects',
'Vedic Maths',
'Mathematics',
'Science',
'English',
'Hindi',
'Environmental Studies',
'Mathematics-Science (Combo)',
'Handwriting (English/Hindi)'
],
standard6To10Subjects:[
'Mathematics',
'Science',
'Computer Science',
'English',
'Hindi',
'Social Science',
'Sanskrit',
'Environmental Studies',
'French',
'German',
'Spanish',
'Mathematics-Science (Combo)',
'Olympiad Maths/Science'
],
standard11To12ArtsSubjects: [
'Geography',
'History',
'Political Science',
'Humanities',
'English',
'Psychology',
'Computer Science/Information Practices'
],
standard11To12CommerceSubjects: [
'Accounts',
'Business Studies',
'Economics',
'Mathematics',
'English',
'Psychology',
'Computer Science/Information Practices'
],
standard11To12ScienceSubjects: [
'Mathematics',
'Physics',
'Chemistry',
'English',
'PCB Combo',
'PCM Combo',
'Computer Science/Information Practices',
'Competitive Exam Preparation'
]
}
},
methods: {
modalToggle() {
this.modalStatus = !this.modalStatus
},
prev() {
this.step--
},
next() {
this.coordinatorToggle()
this.paymentModeToggle()
this.$validator.validate('parentName', this.parentName)
this.$validator.validate('parentContact', this.parentContact)
this.$validator.validate('tutorName', this.tutorName)
this.$validator.validate('tutorContact', this.tutorContact)
this.$validator.validate('startingDate', this.startingDate)
this.$validator.validate('sessionDuration', this.sessionDuration)
this.$validator.validate('sessionsMonth', this.sessionsMonth)
this.$validator.validate('fees', this.fees)
this.$validator.validate('commission', this.commission).then(() => {
if(!this.errors.any() && this.coordinator!=='' && this.paymentMode!==''){
this.step++
}
})
},
validateBeforeSubmit() {
this.$validator.validateAll().then(() => {
if(!this.errors.any()) {
this.addQuery()
this.modalToggle()
}
})
},
standardToggle() {
this.standardIsFocused = true
},
coordinatorToggle() {
this.coordinatorIsFocused = true
},
paymentModeToggle() {
this.paymentModeIsFocused = true
},
emptySubjects() {
this.subjects = []
},
addQuery() {
axios({
method: 'post',
url: 'http://127.0.0.1:8000/api/dashboard/',
data: {
parent_name: this.parentName,
parent_contact: this.parentContact,
student_name: this.studentName,
tutor_name: this.tutorName,
tutor_contact: this.tutorContact,
standard: this.standard,
subject: this.subjects,
starting_date: this.startingDate,
session_month: this.sessionsMonth,
session_duration: this.sessionDuration,
fees: this.fees,
commission: this.commission,
coordinator: this.coordinator,
mode_payment: this.paymentMode
}
}).then(() =>{
this.parentName = '',
this.subjects = [],
this.parentContact = '',
this.studentName = '',
this.tutorName = '',
this.tutorContact = '',
this.standard = '',
this.startingDate = '',
this.sessionsMonth = 24,
this.sessionDuration = '1',
this.fees = null,
this.commission = null,
this.coordinator = '',
this.paymentMode = '',
this.step = 1
})
.catch((error) => {
console.log(error);
});
}
},
computed: {
subjectListFinal: function() {
if (this.standard==='pre-primary'){
return this.prePrimarySubjects
}
else if (this.standard==='1'||this.standard==='2'||this.standard==='3'||this.standard==='4'||this.standard==='5') {
return this.standard1To5Subjects
}
else if (this.standard==='6'||this.standard==='7'||this.standard==='8'||this.standard==='9'||this.standard==='10') {
return this.standard6To10Subjects
}
else if (this.standard==='11-sci'||this.standard==='12-sci') {
return this.standard11To12ScienceSubjects
}
else if (this.standard==='11-com'||this.standard==='12-com') {
return this.standard11To12CommerceSubjects
}
else if (this.standard==='11-art'||this.standard==='12-art') {
return this.standard11To12ArtsSubjects
}
}
}
}
</script>

Related

laravel 9 vue 3 edit multiple checked checkbox value

when editing a checkbox array, I cannot select (checked) that are in the database
how to select those that exist in the checkbox database (checked) ?
please, help
Edit.vue
<template>
<div>
<admin-layout>
<template #header>
<div class="row">
<div class="col-md-12">
<h4>Емделуші</h4>
</div>
</div>
</template>
<div class="row">
<div class="col-md-12 mb-3">
<div class="card">
<div class="card-header">
<span><i class="bi bi-table me-2"></i></span> Емделушіні өзгерту
<div class="card-header-pills float-end">
<inertia-link :href="route('admin.schedules.index')" class="btn btn-primary text-white text-uppercase" style="letter-spacing: 0.1em;">
Кері қайту
</inertia-link>
</div>
</div>
<form #submit.prevent="updateSchedule">
<div class="card-body">
<div class="mb-3">
<label for="name" class="form-label">Аты-жөні</label>
<input type="text" class="form-control" id="name" v-model="form.name" :class="{'is-invalid' : form.errors.name }" autofocus="autofocus" autocomplete="off">
</div>
<div class="invalid-feedback mb-3" :class="{ 'd-block' : form.errors.name }">
{{ form.errors.name }}
</div>
<div class="mb-3">
<label class="form-label" for="email">Email</label>
<input type="text" class="form-control" id="email" v-model="form.email" :class="{'is-invalid' : form.errors.email }" autofocus="autofocus" autocomplete="off">
</div>
<div class="invalid-feedback mb-3" :class="{ 'd-block' : form.errors.email }">
{{ form.errors.email }}
</div>
<div class="mb-3">
<label class="form-label" for="phone">Телефон</label>
<input type="text" class="form-control" id="phone" v-model="form.phone" :class="{'is-invalid' : form.errors.phone }" autofocus="autofocus" autocomplete="off">
</div>
<div class="invalid-feedback mb-3" :class="{ 'd-block' : form.errors.phone }">
{{ form.errors.phone }}
</div>
<div class="form-check form-check-inline" v-for="(time, index) in times" :key="index">
<input class="form-check-input" type="checkbox" id="inlineCheckbox1" :value="time.time" v-model="form.times" :class="{'is-invalid' : form.errors.times }">
<label class="form-check-label" for="inlineCheckbox1">{{ time.time }}</label>
</div>
<div class="invalid-feedback mb-3" :class="{ 'd-block' : form.errors.times }">
{{ form.errors.times }}
</div>
</div>
<div class="card-footer clearfix">
<div class="float-end">
<jet-button class="ms-4 btn-primary text-white" :class="{ 'text-white-50': form.processing }" :disabled="form.processing">
<div v-show="form.processing" class="spinner-border spinner-border-sm" role="status">
<span class="visually-hidden">Өзгертілуде...</span>
</div>
Өзгерту
</jet-button>
</div>
</div>
</form>
</div>
</div>
</div>
</admin-layout>
</div>
</template>
<script>
import AdminLayout from '#/Layouts/AdminLayout';
import JetButton from '#/Jetstream/Button.vue'
import { useForm } from '#inertiajs/inertia-vue3';
import InertiaLink from "#inertiajs/inertia-vue3/src/link";
export default {
name: "Edit",
components: {
AdminLayout,
JetButton,
InertiaLink,
},
props: {
appointment: {},
times: {},
},
setup (props) {
const form = useForm({
name: props.appointment.name,
email: props.appointment.email,
phone: props.appointment.phone,
times: props.times,
});
return {
form,
}
},
methods: {
},
}
}
</script>
when editing a checkbox array, I cannot select (checked) that are in the database how to select those that exist in the checkbox database (checked) ? please, help

VueJs - Duplicating form vs. input field

Picture of interlinkage between forms and fields.
I have searched this forum for an answer, as I suspect this has been asked before, but I haven't managed to find an answer.
I just picked up using Vue and Laravel, where I am building a form. Right now I am building a test to learn how to do it before I add complexity. The right form consists of 1 select-box and 3 text fields.
My requirements for the form are:
One button to duplicate the entire form.
One button in each form (also ones that are duplicated), which adds the 3 input-text fields in the form, by duplication the fields in the div called "registration_grid". One form may require the text-fields to be duplicated 10 times, others only 1 or 2...
I realize the code is a bit messy in its context, but it is put together by various pieces I found in tutorials along the way.
var app = new Vue({
el: '.container',
data: {
workouts: [
{
workout_unit: '',
workout_weight: '',
workout_comment: ''
}
]
},
methods: {
addNewEmployeeForm () {
this.workouts.push({
workout_unit: '',
workout_weight: '',
workout_comment: ''
})
},
deleteEmployeeForm (index) {
this.workouts.splice(index, 1)
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.9/vue.js"></script>
<div class="container">
<button class="btn btn-primary" type="button" name="button" #click="addNewEmployeeForm">Add form fields</button>
<div class="card" v-for="(workout, index) in workouts">
<div class="card-body">
<i class="far fa-trash-alt float-right" #click="deleteEmployeeForm(index)"></i>
<h4 class="card-title">Test form - #{{index}}</h4>
<div class="employee-form">
<select class="form-select form-select-sm" aria-label=".form-select-sm example">
<option selected>Open this select menu</option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
<div class="registration_grid">
<input type="text" class="form-control" name="unit" placeholder="unit" v-model="workout.workout_unit">
<input type="text" class="form-control" name="weight" placeholder="weight" v-model="workout.workout_weight">
<input type="text" class="form-control" name="comment" placeholder="comment" v-model="workout.workout_comment">
</div>
</div>
</div>
</div>
Can this be done by Vue, and if so how?
You need to access the form data with workouts[index].unit for the v-model instead of workout.workout_unit
var app = new Vue({
el: '.container',
data: {
workouts: [
{
unit: '',
weight: '',
comment: ''
}
]
},
methods: {
addRow () {
this.workouts.push({
unit: '',
weight: '',
comment: ''
})
},
deleteRow (index) {
this.workouts.splice(index, 1)
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.9/vue.js"></script>
<div class="container">
<button class="btn btn-primary" type="button" name="button" #click="addRow">Add form fields</button>
<div class="card" v-for="(workout, index) in workouts">
<div class="card-body">
<i class="far fa-trash-alt float-right" #click="deleteRow(index)"></i>
<h4 class="card-title">Test form - {{index}}</h4>
<div class="employee-form">
<select class="form-select form-select-sm" aria-label=".form-select-sm example">
<option selected>Open this select menu</option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
<div class="registration_grid">
<input type="text" class="form-control" name="unit" placeholder="unit" v-model="workouts[index].unit">
<input type="text" class="form-control" name="weight" placeholder="weight" v-model="workouts[index].weight">
<input type="text" class="form-control" name="comment" placeholder="comment" v-model="workouts[index].comment">
</div>
</div>
</div>
</div>
</div>
Modified example to only duplicate the input fields
var app = new Vue({
el: '.container',
data: {
workouts: [
{
unit: '',
weight: '',
comment: ''
}
]
},
methods: {
addRow () {
this.workouts.push({
unit: '',
weight: '',
comment: ''
})
},
deleteRow (index) {
this.workouts.splice(index, 1)
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.9/vue.js"></script>
<div class="container">
<button class="btn btn-primary" type="button" name="button" #click="addRow">Add form fields</button>
<div class="card">
<div class="card-body">
<h4 class="card-title">Test form</h4>
<div class="employee-form">
<select class="form-select form-select-sm" aria-label=".form-select-sm example">
<option selected>Open this select menu</option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
<div class="registration_grid" v-for="(workout, index) in workouts">
<input type="text" class="form-control" name="unit" placeholder="unit" v-model="workouts[index].unit">
<input type="text" class="form-control" name="weight" placeholder="weight" v-model="workouts[index].weight">
<input type="text" class="form-control" name="comment" placeholder="comment" v-model="workouts[index].comment">
<i class="far fa-trash-alt float-right" #click="deleteRow(index)"></i>
</div>
</div>
</div>
</div>
</div>

How to clear form after submit in vuejs

I am trying to empty the form after it submits form but I am unable to do this. Here is the code
<form class="form-horizontal" #submit.prevent="addtodirectory" id="form-directory">
<div class="model-body">
<div class="card-body">
<div class="form-group row">
<label for="inputEmail3" class="col-sm-2 col-form-label">Name</label>
<div class="col-sm-10">
<input v-model="form.name" type="text" name="name"
class="form-control" :class="{ 'is-invalid': form.errors.has('name') }">
<has-error :form="form" field="name"></has-error>
</div>
</div>
<div class="form-group row">
<label for="inputEmail3" class="col-sm-2 col-form-label">Address</label>
<div class="col-sm-10">
<textarea v-model="form.address" type="text" name="address"
class="form-control" :class="{ 'is-invalid': form.errors.has('address') }"></textarea>
<has-error :form="form" field="address"></has-error>
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label">Profession</label>
<div class="col-sm-10">
<input v-model="form.profession" type="text" name="profession"
class="form-control" :class="{ 'is-invalid': form.errors.has('profession') }">
<has-error :form="form" field="profession"></has-error>
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label">Contact Number</label>
<div class="col-sm-10">
<input v-model="form.contact_number" type="text" name="contact_number"
class="form-control" :class="{ 'is-invalid': form.errors.has('contact_number') }">
<has-error :form="form" field="contact_number"></has-error>
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label">City</label>
<div class="col-sm-10">
<input v-model="form.city" type="text" name="city"
class="form-control" :class="{ 'is-invalid': form.errors.has('city') }">
<has-error :form="form" field="city"></has-error>
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label">State</label>
<div class="col-sm-10">
<select v-model="form.state" type="text" name="state"
class="form-control" :class="{ 'is-invalid': form.errors.has('state') }">
<has-error :form="form" field="state"></has-error>
<option value="Rajasthan">Rajasthan</option>
<option value="Gujrat">Gujrat</option>
</select>
</div>
</div>
</div>
<!-- /.card-body -->
<div class="card-footer">
<button type="submit" class="btn btn-success">Submit</button>
<button type="submit" class="btn btn-default float-right">Cancel</button>
</div>
<!-- /.card-footer -->
</div>
</form>
<script>
export default {
data() {
return {
news:{},
form: new Form({
name : '',
address:'',
profession:'',
city:'',
state:''
})
}
},
methods: { addtodirectory() {
this.$Progress.start();
this.form.post('api/addtodirectory');
Toast.fire({
type: 'success',
title: 'Directory Updated successfully'
})
$('#form-directory input[type="text"]').val('');
this.$Progress.finish();
}
}
I am using vform plugin to submit the form. Using Laravel as backend. The data is being submitted in database but I am not able to clear the form. please help in this regarding. Should I use jquery or javascript to clear the form? I tried different ways but I could not figure out the problem.
Simply empty your form object after form submit.
form: new Form({
name : '',
address:'',
profession:'',
city:'',
state:''
})
Well it was simple and I did following code for emptying the form.
addtodirectory(event) {
this.$Progress.start();
this.form.post('api/addtodirectory');
// document.getElementById("form-directory").reset();
console.log('durgesh');
// document.getElementsByName('name').value = '';
Toast.fire({
type: 'success',
title: 'Directory Updated successfully'
})
this.form.name = "";
this.form.profession ="";
this.form.address="";
this.form.city = "";
this.form.state = "";
this.$Progress.finish();
},
after submitting the form I did not used the form. so after doing this I emptied the form.
Or in a one-liner:
Object.keys(form).forEach(v => form[v] = "")
instead of:
this.form.name = "";
this.form.profession ="";
this.form.address="";
this.form.city = "";
this.form.state = "";

Validate specific amount of input fields with vee-validate

I want to validate varios steps in a wizard, without validating all inputs, when clicking on the next button. When clicking on the next button it should fire the function to validate the input fields of the first step. Then in the next step the input fields of the second step and so on. The next button is no submit button.
<tab-content title="Company" icon="fas fa-building" :before-change="validateThirdStep">
<div class="col-md-8 offset-md-2">
<label class="col-form-label text-md-right">Do you have a chicken?</label>
<div class="form-goup row">
<div class="col-md-7">
<input type="radio" name="dsb" id="radios" value="yes" v-model="pickeddsb">Yes
<input type="radio" name="dsb" id="radios" value="no" v-model="pickeddsb">No
</div>
</div>
</div>
<div class="form-group" v-if="pickeddsb=='yes'">
<div class="col-md-8 offset-md-2">
<h4>Data</h4>
</div>
<div class="col-lg-8 m-auto">
<!-- Name -->
<div class="form-group row">
<label class="col-md-3 col-form-label text-md-right">{{ $t('name') }}</label>
<div class="col-md-7">
<input
v-model="namedsb"
v-validate="'required|namedsb'"
:class="{ 'has-error': errors.has('namedsb') }"
type="text"
name="namedsb"
>
{{ errors.first('namedsb') }}
</div>
</div>
<!-- Firm -->
<div class="form-group row">
<label class="col-md-3 col-form-label text-md-right">{{ $t('companyname') }}</label>
<div class="col-md-7">
<input
v-model="firm"
v-validate="'required|firmdsb'"
:class="{ 'has-error': errors.has('firmdsb') }"
class="form-control"
type="text"
name="firmdsb"
>
{{ errors.first('firmdsb') }}
</div>
</div>
<!--Telephone-->
<div class="form-group row">
<label class="col-md-3 col-form-label text-md-right">{{$t('telephone')}}</label>
<div class="col-md-7">
<input
v-model="telephonedsb"
v-validate="'required|telephonedsb'"
:class="{ 'has-error': errors.has('telephonedsb')}"
class="form-control"
type="tel"
name="telephonedsb"
>
{{ errors.first('telephonedsb') }}
</div>
</div>
<!-- Email -->
<div class="form-group row">
<label class="col-md-3 col-form-label text-md-right">{{ $t('email') }}</label>
<div class="col-md-7">
<input
v-model="emaildsb"
v-validate="'required|emaildsb'"
:class="{ 'has-error': errors.has('emaildsb') }"
class="form-control"
type="email"
name="emaildsb"
>
{{ errors.first('emaildsb') }}
</div>
</div>
</div>
</div>
</tab-content>
export default {
data() {
return {
namedsb: "",
telephonedsb: "",
emaildsb: "",
namere: "",
telephonere:"",
emailre: "",
}
},
methods: {
validateThirdStep: function() {
this.$validator.validate('namedsb', this.namedsb);
this.$validator.validate('firmdsb', this.firmdsb);
this.$validator.validate('telephonedsb', this.state);
this.$validator.validate('emaildsb', this.emaildsb);
}
}
}
It's fairly easy with the built-in scopes of VeeValidate, you can read about it on this page: enter link description here
A simple explanation is to add a specific scope for each tab/step, by adding this on the fields:
data-vv-scope="step1"
And then use this method when pressing the button for validation:
methods: {
validateForm(scope) {
this.$validator.validateAll('step1').then((result) => {
if (result) {
alert('Form Submitted!');
}
});
}
}

VueJS + Two instances of vForm in one component

I'm using laravel + VueJS for front-end. I have a groups component to handle groups creation and groups permissions. I need to use two vForms: One to create groups, and the other to create / assign permissions for the group.
The problem is when I send the permissions form, laravel receives data of the first form, this i suppose is because I create that instance first. I think I should create two instances of vForm, but I do not know how. Is this possible?
My component code:
<template>
<div class="container">
<div class="row mt-5">
<div class="col-md-12">
<div class="card">
<div class="card-header">
<h3 class="card-title">Grupos</h3>
<div class="card-tools">
<button class="btn btn-success" #click="newGroupModal" v-if="$can('groupscreate')"> <i class="fas fa-user-plus fa-fw"></i> Nuevo Grupo </button>
</div>
</div>
<!-- /.card-header -->
<div class="card-body table-responsive p-0">
<table class="table table-hover">
<tbody>
<tr>
<th>ID</th>
<th>Nombre</th>
<th>Fecha Alta</th>
<th>Fecha Act</th>
<th>Acc.</th>
</tr>
<tr v-for="group in groups" :key="groups.id">
<td>{{ group.id }}</td>
<td>{{ group.name }}</td>
<td>{{ group.created_at | formattedDate }}</td>
<td>{{ group.updated_at | formattedDate }}</td>
<td><i class="fas fa-edit"></i></td>
<td><i class="fas fa-key"></i></td>
</tr>
</tbody>
</table>
</div>
<!-- /.card-body -->
</div>
<!-- /.card -->
</div>
</div>
<!-- Modal -->
<div class="modal fade" id="groupModal" tabindex="-1" role="dialog" aria-labelledby="groupModal" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="groupModal">Nuevo Grupo</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<form #submit.prevent="editMode ? updateGroup() : createGroup()">
<div class="modal-body">
<div class="form-group">
<input v-model="form.name" type="text" name="name" placeholder="Name"
class="form-control" :class="{ 'is-invalid': form.errors.has('name') }">
<has-error :form="form" field="name"></has-error>
</div>
</div>
<div class="modal-footer">
<button v-show="editMode" type="button" class="btn btn-danger" #click="deleteGroup" v-if="$can('groupsdelete')">Eliminar</button>
<button type="button" class="btn btn-secondary" data-dismiss="modal">Cerrar</button>
<button type="submit" class="btn btn-primary" v-if="$can('groupsedit')">Guardar</button>
</div>
</form>
</div>
</div>
</div>
<!-- Modal Permissions-->
<div class="modal fade" id="groupPermissionsModal" tabindex="-1" role="dialog" aria-labelledby="groupPermissionsModal" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="userModal">Permisos por Grupo</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<form #submit.prevent="updateGroupPermissions()">
<div class="modal-body">
<div class="form-group">
<label class="control-label">Usuarios</label><br>
<div class="form-check form-check-inline">
<input class="form-check-input" type="checkbox" id="usersview" value="usersview" v-model="groupPermissions">
<label class="form-check-label" for="usersview">Ver</label>
</div>
<div class="form-check form-check-inline">
<input class="form-check-input" type="checkbox" id="userscreate" value="userscreate" v-model="groupPermissions">
<label class="form-check-label" for="userscreate">Crear</label>
</div>
<div class="form-check form-check-inline">
<input class="form-check-input" type="checkbox" id="usersedit" value="usersedit" v-model="groupPermissions">
<label class="form-check-label" for="usersedit">Editar</label>
</div>
<div class="form-check form-check-inline">
<input class="form-check-input" type="checkbox" id="usersdelete" value="usersdelete" v-model="groupPermissions">
<label class="form-check-label" for="usersdelete">Eliminar</label>
</div>
</div>
<div class="form-group">
<label class="control-label">Grupos</label><br>
<div class="form-check form-check-inline">
<input class="form-check-input" type="checkbox" id="groupsview" value="groupsview" v-model="groupPermissions">
<label class="form-check-label" for="groupsview">Ver</label>
</div>
<div class="form-check form-check-inline">
<input class="form-check-input" type="checkbox" id="groupscreate" value="groupscreate" v-model="groupPermissions">
<label class="form-check-label" for="groupscreate">Crear</label>
</div>
<div class="form-check form-check-inline">
<input class="form-check-input" type="checkbox" id="groupsedit" value="groupsedit" v-model="groupPermissions">
<label class="form-check-label" for="groupsedit">Editar</label>
</div>
<div class="form-check form-check-inline">
<input class="form-check-input" type="checkbox" id="groupsdelete" value="groupsdelete" v-model="groupPermissions">
<label class="form-check-label" for="groupsdelete">Eliminar</label>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Cerrar</button>
<button type="submit" class="btn btn-primary" v-if="$can('permissionsedit')">Guardar</button>
</div>
</form>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
editMode: false,
groups: {},
groupPermissions: {},
form: new Form({
id: '',
name : '',
}),
formPermissions: new Form({
users: [],
groups: []
}),
}
},
methods: {
newGroupModal(){
this.editMode = false;
this.form.reset();
$('#groupModal').modal('show');
},
newGroupPermissionsModal(groupId){
this.loadGroupPermissions(groupId);
this.form.reset();
$('#groupPermissionsModal').modal('show');
this.form.fill(this.groupPermissions);
},
newEditGroupModal(group){
this.editMode = true;
this.form.reset();
$('#groupModal').modal('show');
this.form.fill(group);
},
loadGroups(){
this.$Progress.start();
axios.get('api/group').then(({data}) => (this.groups = data.data));
this.$Progress.finish();
},
loadGroupPermissions(groupId){
this.$Progress.start();
axios.get('api/permissions/group/' + groupId).then(({data}) => (this.groupPermissions = data));
this.$Progress.finish();
},
createGroup(){
this.$Progress.start();
this.form.post('api/group')
.then(() => {
Fire.$emit('GroupInform');
$('#groupModal').modal('hide');
Toast.fire({
type: 'success',
title: 'Usuario creado satisfactoriamente.'
})
this.form.reset();
this.$Progress.finish();
})
.catch(() => {
this.$Progress.fail();
})
},
updateGroup(groupId){
this.$Progress.start();
this.form.put('api/group/' + this.form.id)
.then(() => {
Fire.$emit('GroupInform');
$('#groupModal').modal('hide');
Toast.fire({
type: 'success',
title: 'Usuario actualizado satisfactoriamente.'
})
this.form.reset();
this.$Progress.finish();
})
.catch(() => {
this.$Progress.fail();
})
},
deleteGroup(){
Swal.fire({
title: 'Estas seguro?',
text: "No podrás restaurar los datos eliminados.",
type: 'warning',
showCancelButton: true,
confirmButtonColor: '#d33',
cancelButtonColor: '#14b750',
confirmButtonText: 'Si'
}).then((result) => {
if (result.value) {
this.form.delete('api/group/'+this.form.id).then(()=>{
Toast.fire({
type: 'success',
title: 'Usuario eliminado satisfactoriamente.'
})
Fire.$emit('GroupInform');
$('#groupModal').modal('hide');
}).catch(()=> {
Swal.fire("Error!", "Algo anda mal.", "warning");
this.$Progress.fail();
});
}
})
},
updateGroupPermissions(){
this.$Progress.start();
this.form.post('api/permissions/group/1')
.then(() => {
Fire.$emit('GroupInform');
$('#groupModal').modal('hide');
Toast.fire({
type: 'success',
title: 'Usuario actualizado satisfactoriamente.'
})
this.form.reset();
this.$Progress.finish();
})
.catch(() => {
this.$Progress.fail();
})
}
},
mounted() {
this.loadGroups();
Fire.$on('GroupInform', () => {
this.loadGroups();
});
}
}
</script>
Simply add a new variable with a different name than 'form' as a new instance from v-form
form2: new Form({
id: '',
name : '',
})
then access it like that:
<div class="form-group">
<input v-model="form2.name" type="text" name="name" placeholder="Name" class="form-control" :class="{ 'is-invalid': form.errors.has('name') }">
<has-error :form="form2" field="name"></has-error>
</div>