Laravel Vue, pass data in form from component after submit - laravel

i need a little help about how to get values from a component that is in a form.
This is the form also a photo: form
`
<form #submit.prevent="form.patch(route('profile.update.account'))" class="mt-6 space-y-6">
<div>
<InputLabel for="adresa" value="Adresa" />
<TextInput
id="adresa"
type="text"
class="mt-1 block w-full"
v-model="form.adresa"
required
autofocus
autocomplete="adresa"
/>
<InputError class="mt-2" :message="form.errors.adresa" />
</div>
<DropdownCountries
id="tara"
v-model="form.tara"
required
autocomplete="Romania"
/>
<div class="flex items-center gap-4">
<PrimaryButton :disabled="form.processing">Save</PrimaryButton>
<Transition enter-from-class="opacity-0" leave-to-class="opacity-0" class="transition ease-in-out">
<p v-if="form.recentlySuccessful" class="text-sm text-gray-600">Saved.</p>
</Transition>
</div>
</form>
`
There is the component also a photo: dropdown
`
<template>
<div class="container">
<div class="row justify-content-center" style="margin: 20px 0px 20px 0px;">
<div class="col-md-8">
<div class="card">
<div class="card-body">
<div class="form-group">
<select name="tara" class='form-control' v-model='country' #change='getStates()'>
<option value='0' >Select Country</option>
<option v-for='data in countries' :value='data.id'>{{ data.name }}</option>
</select>
</div>
<div class="form-group">
<select name="judet" class='form-control' v-model='state' #change='getCities()'>
<option value='0' >Select State</option>
<option v-for='data in states' :value='data.id'>{{ data.name }}</option>
</select>
</div>
<div class="form-group">
<select name="oras" class='form-control' v-model='city'>
<option value='0' >Select City</option>
<option v-for='data in cities' :value='data.id'>{{ data.name }}</option>
</select>
</div>
</div>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
data(){
return {
country: 180,
countries: [],
state: 0,
states: [],
city: 0,
cities: [],
}
},
methods:{
getCountries: function(){
axios.get('/api/tari')
.then(function (response) {
this.countries = response.data;
}.bind(this));
},
getStates: function() {
axios.get('/api/judete/' + this.country).then(function(response){
this.states = response.data;
}.bind(this));
},
getCities: function() {
axios.get('/api/orase/' + this.state).then(function(response) {
this.cities = response.data
}.bind(this));
}
},
created: function(){
this.getCountries()
}
}
</script>
`
My problem is that when i press Save button for submitting the form the values from dropdowns are not applied: response
I've been looking on internet for 2 hours can someone explain me why is that.

You should check this: v-model and child components?
This should answer your question. Let me know if you need more informaiton of how passing v-model values works.

Related

How to fetch data from the database as a select option to the dropdown using API in laravel 9 with vue js 3

I have fields to submit to insert into the database. The account field has to select from options by Dropdown. The options should be fetched from the accounts table in the database and I have used API for that. I have coded and it can not see the accounts. Please instruct me to fix it.
the input types as follows.
<div class="modal-body">
<div class="form-row" v-show="!deleteMode">
<div class="form-group col-md-6">
<label for="exampleInputBorderWidth2">Funds From</label>
<select class='form-control' v-model='accountData.selectAccount'>
<option value='0' >Select Account</option>
<option v-for='data in selectAccounts' :value='data.id'>{{ data.name }}</option>
</select>
<span class="text-danger" v-show="accountError.selectAccount">Fund From required </span>
</div>
</div>
<div class="form-row" v-show="!deleteMode">
<div class="form-group col-md-6">
<label for="exampleInputBorderWidth2">Account Name</label>
<input type="text" class="form-control form-control-border border-width-2 text-danger text-lg" id="name" placeholder="Account Name" v-model="accountData.name" required>
<span class="text-danger" v-show="accountError.name">Name is required </span>
</div>
<div class="form-group col-md-6">
<label for="exampleInputBorderWidth2">Account Description</label>
<input type="text" class="form-control form-control-border border-width-2 text-primary text-lg" id="description" placeholder="Account Description" v-model="accountData.description">
<span class="text-danger" v-show="accountError.description">Description is required</span>
</div>
</div>
</div>
script as follows
data() {
return {
editMode: false,
deleteMode:false,
accountData:{
id: '',
name: '',
description: '',
status: '',
selectAccount: 0,
selectAccounts:[]
},
get Method
getSelectAccounts(){
axios.get("/api/allAccForSelect").then(response => {
this.selectAccounts = response.data
}).bind(this);
},
getDepAcc(){
axios.get("/api/depositAccount/depositAccountIndex").then(response => {
this.depAccs = response.data
}).catch(errors =>{
console.log(errors)
});
},
router API
Route::get('/allAccForSelect', [AccountController::class, 'allAccForSelect']);
Controller
public function allAccForSelect(Request $request)
{
$userId = Auth::id();
return response()->json(Account::where('user', $userId)->where('status', 1)->get());
}

Laravel Vue store data foreign key

<form #submit.prevent="store">
<div class="form-group mb-3">
<label class="form-label">NIP</label>
<input type="text" class="form-control" v-model="pegawai.nomor_induk_pegawai"
placeholder="Masukkan nomor induk pegawai">
<!-- validation -->
<div v-if="validation.nomor_induk_pegawai" class="mt-2 alert alert-danger">
{{ validation.nomor_induk_pegawai[0] }}
</div>
</div>
<div class="form-group mb-3">
<label for="content" class="form-label">Nama Pegawai</label>
<input class="form-control" v-model="pegawai.nama_pegawai"
placeholder="Masukkan nama pegawai">
<!-- validation -->
<div v-if="validation.nama_pegawai" class="mt-2 alert alert-danger">
{{ validation.nama_pegawai[0] }}
</div>
</div>
<div class="form-group mb-3">
<label for="content" class="form-label">Departemen</label>
<select class="form-control" v-model="pegawai.id_departemen">
<option v-for="departemen in departemens" v-bind:value="departemen.id">{{ departemen.nama_departemen }}</option>
</select>
<div v-if="validation.id_departemen" class="mt-2 alert alert-danger">
{{ validation.id_departemen[0] }}
</div>
</div>
<div class="form-group mb-3">
<label class="form-label">Email</label>
<input type="text" class="form-control" v-model="pegawai.email"
placeholder="Masukkan email">
<!-- validation -->
<div v-if="validation.email" class="mt-2 alert alert-danger">
{{ validation.email[0] }}
</div>
</div>
<div class="form-group mb-3">
<label for="content" class="form-label">Telepon</label>
<input class="form-control" v-model="pegawai.telepon" placeholder="Masukkan telepon">
<!-- validation -->
<div v-if="validation.telepon" class="mt-2 alert alert-danger">
{{ validation.telepon[0] }}
</div>
</div>
<div class="form-group mb-3">
<label for="content" class="form-label">Gender</label>
<select class="form-control" v-model="pegawai.gender">
<option value="0"> Wanita </option>
<option value="1"> Pria </option>
</select>
<!-- validation -->
<div v-if="validation.gender" class="mt-2 alert alert-danger">
{{ validation.gender[0] }}
</div>
</div>
<div class="form-group mb-3">
<label for="content" class="form-label">Status</label>
<select class="form-control" v-model="pegawai.status">
<option value="1"> Aktif </option>
<option value="0"> Tidak Aktif </option>
</select>
<!-- validation -->
<div v-if="validation.status" class="mt-2 alert alert-danger">
{{ validation.status[0] }}
</div>
</div>
<button type="submit" class="btn btn-primary">SIMPAN</button>
<script>
import { reactive, ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import axios from 'axios'
export default {
setup() {
//state departemen
const pegawai = reactive({
nomor_induk_pegawai: '',
id_departemen:'',
nama_pegawai: '',
email: '',
telepon: '',
gender: '',
status: ''
})
let departemens = ref([])
onMounted(() => {
//get API from Laravel Backend
axios.get('http://localhost:8000/api/departemens')
.then(response => {
//assign state posts with response data
departemens.value = response.data.data
}).catch(error => {
console.log(error.response.data)
})
})
//state validation
const validation = ref([])
//vue router
const router = useRouter()
//method store
function store() {
let nomor_induk_pegawai = pegawai.nomor_induk_pegawai
let nama_pegawai = pegawai.nama_pegawai
let id_departemen = departemen.id
let email = pegawai.email
let telepon = pegawai.telepon
let gender = pegawai.gender
let status = pegawai.status
axios.post('http://localhost:8000/api/pegawais', {
nomor_induk_pegawai: nomor_induk_pegawai,
nama_pegawai: nama_pegawai,
id_departemen: id_departemen,
email: email,
telepon: telepon,
gender: gender,
status: status
}).then(() => {
//redirect ke post index
router.push({
name: 'pegawai.index'
})
}).catch(error => {
//assign state validation with error
validation.value = error.response.data
})
}
//return
return {
departemens,
pegawai,
validation,
router,
store
}
}
I'm trying to create data in table pegawais with id_departemen as foreign key from table departemens. the dropdown on label departemen suppose to show nama_departemen from table departemen with value id from table department. So I tried this and it said
32:37 error Elements in iteration expect to have 'v-bind:key' directives vue/require-v-for-key
128:33 error 'departemen' is not defined no-undef
As written in the error, this is how you should have it
<option v-for="departemen in departments"
:value="departemen.id"
:key="departmen.id" // 👈🏻 missing that one
>
{{ departemen.nama_departemen }}
</option>
More details are available here: https://eslint.vuejs.org/rules/require-v-for-key.html
And also here: https://vuejs.org/guide/essentials/list.html#maintaining-state-with-key
TLDR: when using a v-for, add a :key to it.

dependent dropdown for update loads all the states by default in Laravel

In my Laravel-5.8, I am using dependent dropdown for country and corresponding states. For the create view blade, I have this:
Controller
public function getStateList(Request $request)
{
$states = DB::table("config_states")
->where("country_id",$request->country_id)
->pluck("state_name","id")
->sortByDesc('state_name');
return response()->json($states);
}
public function edit($id)
{
$userCompany = Auth::user()->company_id;
$employee = HrEmployee::where('id', $id)->first();
$countries = ConfigCountries::all();
$states = ConfigState::all();
return view('hr.employees.edit')
->with('employee', $employee)
->with('countries', $countries)
->with('states', $states);
}
create.blade
<div class="col-12 col-sm-4">
<div class="form-group">
<label class="control-label"> Country:</label>
<select id="country" class="form-control select2bs4" data-placeholder="Choose Country" tabindex="1" name="country_id" style="width: 100%;">
<option value="" selected disabled>Select Country</option>
#if($countries->count() > 0 )
#foreach($countries as $country)
<option value="{{$country->id}}">{{$country->country_name}}</option>
#endforeach
#endif
</select>
</div>
<!-- /.form-group -->
</div>
<!-- /.col -->
<div class="col-12 col-sm-4">
<div class="form-group">
<label class="control-label"> State:</label>
<select id="state" class="form-control select2bs4" data-placeholder="Choose State" tabindex="1" name="state_id" style="width: 100%;">
</select>
</div>
<!-- /.form-group -->
</div>
Javascript
<script type="text/javascript">
$('#country').change(function(){
var countryID = $(this).val();
if(countryID){
$.ajax({
type:"GET",
url:"{{url('get-state-list')}}?country_id="+countryID,
success:function(res){
if(res){
$("#state").empty();
$("#state").append('<option>Select</option>');
$.each(res,function(key,value){
$("#state").append('<option value="'+key+'">'+value+'</option>');
});
}else{
$("#state").empty();
}
}
});
}else{
$("#state").empty();
}
});
});
</script>
This works.
However, for the edit view blade:
<div class="row">
<div class="col-12 col-sm-4">
<div class="form-group">
<label class="control-label"> Country:</label>
<select id="country" class="form-control select2bs4" data-placeholder="Choose Country" tabindex="1" name="country_id" style="width: 100%;">
<option value="" selected disabled>Select Country</option>
#if($countries->count() > 0 )
#foreach($countries as $country)
<option value="{{$country->id}}" #if($country->id == $employee->country_id) selected #endif>{{$country->country_name}}</option>
#endforeach
#endif
</select>
</div>
<!-- /.form-group -->
</div>
<!-- /.col -->
<div class="col-12 col-sm-4">
<div class="form-group">
<label class="control-label"> State:</label>
<select id="state" class="form-control select2bs4" data-placeholder="Choose State" tabindex="1" name="state_id" style="width: 100%;">
</select>
</div>
<!-- /.form-group -->
</div>
Javascript
<script type="text/javascript">
$('#country').change(function(){
var countryID = $(this).val();
if(countryID){
$.ajax({
type:"GET",
url:"{{url('get-state-list')}}?country_id="+countryID,
success:function(res){
if(res){
$("#state").empty();
$("#state").append('<option>Select</option>');
$.each(res,function(key,value){
$("#state").append('<option value="'+key+'">'+value+'</option>');
});
}else{
$("#state").empty();
}
}
});
}else{
$("#state").empty();
}
});
});
</script>
I expect it by default to load the current state of origin from the database into the select id="state" dropdown but it was empty.
Then when I changed it to:
<div class="col-12 col-sm-4">
<div class="form-group">
<label class="control-label"> State:</label>
<select id="state" class="form-control select2bs4" data-placeholder="Choose State" tabindex="1" name="state_id" style="width: 100%;">
<option value="" selected disabled>Select state</option>
#if($states->count() > 0 )
#foreach($states as $state)
<option value="{{$state->id}}" #if($state->id == $employee->state_id) selected #endif>{{$cstate->state_name}}</option>
#endforeach
#endif
</select>
</div>
<!-- /.form-group -->
</div>
It loads all the states of origin in the database instead of the corresponding state.
How do I resolve this?
Thanks
As i said in the comment, you're missing the condition of the country in your states selection.
public function edit($id)
{
$userCompany = Auth::user()->company_id;
$employee = HrEmployee::where('id', $id)->first();
$countries = ConfigCountries::all();
$states = ConfigState::where("country_id", $employee->country_id)->get();
return view('hr.employees.edit')
->with('employee', $employee)
->with('countries', $countries)
->with('states', $states);
}

two select dynamics vue laravel

I want to load 2 select with vue, I have country, city state, but I don't want to call the js from resources / app.js since I don't need it in all the pages only in a particular sight. I am new to vue. when I load it from resources / app.js if it works but only for status but not for city and in the other pages it throws me an error since it cannot find the object.
I don't want to call him here
require('./bootstrap');
window.Vue = require('vue');
Vue.component('example-component', require('./components/ExampleComponent.vue').default);
//require('./estado');
//require('./ciudad');
so how do i make the call and where do i put the js files
file get state resources/js/estado.js
const app = new Vue({
el: '#app',
data: {
selected_pais: '',
selected_estado: '',
selected_ciudad: '',
estados: [],
ciudades: [],
},
mounted(){
document.getElementById('estado').disabled = true;
this.selected_pais = document.getElementById('pais').getAttribute('data-old');
if(this.selected_pais !='')
{
this.loadEstados();
}
this.selected_estado = document.getElementById('estado').getAttribute('data-old');
document.getElementById('ciudad').disabled = true;
this.selected_estado = document.getElementById('estado').getAttribute('data-old');
if(this.selected_estado !='')
{
this.cargarCiudades();
}
this.selected_ciudad = document.getElementById('ciudad').getAttribute('data-old');
},
methods: {
loadEstados() {
this.selected_estado ='';
document.getElementById('estado').disabled =true;
if (this.selected_pais !="") {
axios.get(`http://127.0.0.1:80/estados/pais`, {params: {pais_id: this.selected_pais} }).then((response) => {
this.estados = response.data;
document.getElementById('estado').disabled =false;
});
}
},
cargarCiudades() {
this.selected_ciudad ='';
document.getElementById('ciudad').disabled =true;
if (this.selected_estado !="") {
axios.get(`http://127.0.0.1:80/ciudades/estado`, {params: {estado_id: this.selected_estado} }).then((response) => {
this.ciudades = response.data;
document.getElementById('ciudad').disabled =false;
});
}
},
}
});
file get city resources/js/ciudades.js
const app = new Vue({
el: '#app',
data: {
selected_estado: '',
selected_ciudad: '',
ciudades: [],
},
mounted(){
document.getElementById('ciudad').disabled = true;
this.selected_estado = document.getElementById('estado').getAttribute('data-old');
if(this.selected_estado !='')
{
this.cargarCiudades();
}
this.selected_ciudad2 = document.getElementById('ciudad').getAttribute('data-old');
},
method: {
cargarCiudades() {
this.selected_ciudad2 ='';
document.getElementById('ciudad').disabled =true;
if (this.selected_estado !="") {
axios.get(`http://127.0.0.1:80/ciudades/estado`, {params: {estado_id: this.selected_estado} }).then((response) => {
this.ciudades = response.data;
document.getElementById('ciudad').disabled =false;
});
}
}
}
});
files view
#extends('layouts.app')
#section('content')
#inject('paises','App\Services\Paises')
<div class="container">
<div class="row">
<div class="col-md-8">
#if ($errors->any())
<div class="alert alert-danger">
<h4>Por Favor corriga los siguientes errores </h4>
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<form action="/usuarios" method="POST">
#csrf
<div class="form-row">
<div class="form-group col-md-6">
<label for="inputEmail4">Nombre</label>
<input type="text" class="form-control" name="nombre" id="inputEmail4" placeholder="Nombre" value="{{old('nombre')}}">
</div>
<div class="form-group col-md-6">
<label for="inputPassword4">Email</label>
<input type="text" class="form-control" name="email" id="inputPassword4" placeholder="Email" value="{{old('email')}}">
</div>
</div>
<div class="form-group">
<label for="inputAddress">Direccion</label>
<input type="text" class="form-control" id="inputAddress" placeholder="1234 Main St" name="direccion" value="{{old('direccion')}}">
</div>
<div class="form-row">
<div class="form-group col-md-4" id="div_pais">
<label for="inputCity">Pais</label>
<select v-model="selected_pais" id="pais" data-old="{{old('cbo_pais')}}"
v-on:change="loadEstados()" name="cbo_pais" class="form-control">
#foreach ($paises->get() as $index => $pais)
<option value="{{$index}}" >{{$pais}}</option>
#endforeach
</select>
</div>
<div class="form-group col-md-4">
<label for="inputCity">Estado</label>
<select v-model="selected_estado" id="estado" data-old="{{old('cbo_estado')}}"
v-on:change="cargarCiudades()" name="cbo_estado" class="form-control" >
<option value="">Selecione un Estado</option>
<option v-for="(estado, index) in estados" v-bind:value="index">#{{estado}}</option>
</select>
</div>
<div class="form-group col-md-4">
<label for="inputState">Ciudad</label>
<select v-model="selected_ciudad" id="ciudad" data-old="{{old('cbo_ciudad')}}"
name="cbo_ciudad" class="form-control" >
<option value="">Selecione un Ciudad</option>
<option v-for="(ciudad, index) in ciudades" v-bind:value="index">#{{ciudad}}</option>
</select>
</div>
</div>
<div class="form-group">
<label for="inputZip">Zip</label>
<input type="text" class="form-control" id="inputZip" name="zip">
</div>
<div class="form-group">
<div class="form-check">
<input class="form-check-input" type="checkbox" id="gridCheck">
<label class="form-check-label" for="gridCheck">
Check me out
</label>
</div>
</div>
<button type="submit" class="btn btn-primary">Registrar</button>
<button type="reset" class="btn btn-danger">Cancelar</button>
</form>
</div>
</div>
</div>
#endsection
#section('scripts')
#endsection
how do I call the files in the view?

Programatically trigger form validation with JQuery Validator don't work

According to the docs of jQuery Validator doing this should programatically trigger form validation.
var validator = $( "#myform" ).validate();
validator.form();
But in my code it does nothing, why? I have a submit button on my form that is working fine, but validator.form() doesn't work at all. I've updated the post with my HTML form as well as the javascript code.
This is my form
<form class="kt-form kt-form--label-right" id="frm_sok" action="ajax/artikkel.php?a=sok_artikler" method="post">
<div class="kt-portlet__body">
<div class="kt-blog-post">
<div class="form-group ">
<div class="col-12">
<input class="form-control" type="search" value="{{ sok }}" id="searchinput" name="searchinput">
</div>
</div>
<div class="row">
<div class="col-4">
<label>Ikke søk i :</label>
<div class="form-check">
<input class="form-check-input" type="checkbox" value="1" id="skjulnyheter" name="skjulnyheter">
<label class="form-check-label" for="skjulnyheter">Nyheter</label>
</div>
<div class="form-check">
<input class="form-check-input" type="checkbox" value="1" id="skjulforum" name="skjulforum">
<label class="form-check-label" for="skjulforum">Forum</label>
</div>
</div>
<div class="col-4">
<label for="sorter">Sorter:</label><br />
<select class="form-control" name="sorter" id="sorter">
<option value="a.opp_dato DESC">Nyeste</option>
<option value="score">Beste treff</option>
<option value="a.opp_dato ASC">Eldste</option>
</select>
</div>
</div>
</div>
</div>
<div class="kt-portlet__foot">
<div class="kt-form__actions">
<input type="submit" class="btn btn-primary sokknapp" value="Søk" />
</div>
</div>
</form>
Here is my Javascript:
$( window ).on( 'load', function()
{
var validator = $("#frm_sok").validate(
{
rules:
{
searchinput:
{
required: true
}
},
messages:
{
searchinput :
{
required : 'Du må neste søke etter noe. Noe som helst. Ett eller annet.'
}
},
invalidHandler: function(event, validator)
{
$('.error').css( "display", "inline-block !important");
},
submitHandler: function(form)
{
preload_kamp();
$(form).ajaxSubmit(
{
success: function(data)
{
$( "#sokcontent" ).html(data);
}
});
}
});
validator.form();
});

Resources