Can't pass Vue variable to hidden input v-model in view(v-for) - laravel

I'm new to Vue JS and I'm building an application with Laravel Spark and trying to utilize Vue as much as possible.
I have a form to simply add an 'Asset Type' with a component. Once the Asset Type is successfully created, a list of properties is grabbed from the database and set to a 'data' attribute. In my view(I'm using an inline template), I have a 'v-for' that creates a form for each property that has two hidden inputs for the property id and the type id, and one "Add" button that assigns the property to the newly created type.
THE PROBLEM:
I can't seem to assign the value of the hidden inputs within the view while using v-models. When I submit one of the forms, the form request data always returns the initial data value from the new SparkForm object.
In other words, I need to assign the hidden input values within the v-for loop in the view.
Here's my component:
Vue.component('new-asset-type', {
props: [],
data() {
return {
// type_id: this.type_id,
properties: this.properties,
newAssetType: new SparkForm({
label: null,
enabled: false,
}),
assignPropForm: new SparkForm({
prop_id: "",
type_id: "",
}),
};
},
methods: {
createType: function () {
Spark.post('/asset-types', this.newAssetType)
.then(response => {
this.type_id = response.type_id;
axios.get('/getTypeNotProps/' + this.type_id).then((response) => {
this.properties = response.data;
console.log(this.properties);
});
})
.catch(response => {
console.log("fail");
});
},
assignProp: function () {
Spark.post('/asset-properties/add', this.assignPropForm)
.then(response => {
console.log(response);
})
.catch(response => {
console.log("fail");
});
}
}
});
And here's my view:
#extends('spark::layouts.app')
#section('content')
<new-asset-type inline-template>
<div class="container">
<!-- Application Dashboard -->
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="panel panel-default">
<div class="panel-heading">Add a New Asset Type</div>
<div class="panel-body" id="addTypeForm">
<div class="form-horizontal">
<div class="form-group" :class="{'has-error': newAssetType.errors.has('label')}">
{{ Form::label('label', 'Label', ['class' => 'col-md-4 control-label']) }}
<div class="col-md-6" >
<input type="test" name="label" v-model="newAssetType.label">
<span class="help-block" v-show="newAssetType.errors.has('label')">
#{{ newAssetType.errors.get('label') }}
</span>
</div>
</div>
<div class="form-group">
{{ Form::label('enabled', 'Enabled?', ['class' => 'col-md-4 control-label']) }}
<div class="col-md-6">
<input type="checkbox" name="enabled" v-model="newAssetType.enabled" >
</div>
</div>
<!-- Submit -->
<div class="form-group">
<div class="col-md-8 col-md-offset-4">
<button class="btn btn-primary" #click="createType" :disabled="newAssetType.busy">
Create Asset Type
</button>
</div>
</div>
<div id="assignProps" v-if="newAssetType.successful">
<!-- Button trigger modal -->
<button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">
Add Property
</button>
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Add New Property to Asset Type</h4>
</div>
<div class="modal-body">
<assign-asset-prop v-for="property in properties" class="panel panel-info property-item">
<div class="panel-heading">#{{ property.label }}</div>
<div class="panel-body"><strong>Input Type: </strong>#{{ property.input_type }}
<div class="pull-right">
<input type="hidden" name="prop_id" v-bind:value="property.p_id" v-model="assignPropForm.prop_id">
<input type="hidden" name="type_id" v-bind:value="property.p_id" v-model="assignPropForm.type_id">
<button class="btn btn-primary" #click="assignProp" :disabled="assignPropForm.busy">
Add
</button>
</div>
</div>
</assign-asset-prop>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</new-asset-type>
#endsection

Thanks to the helpful comments, I learned that I shouldn't have been using hidden inputs at all. Instead, I simply passed the variables to the function on the click event.
<button class="btn btn-primary" #click="assignProp(type_id, property.p_id)" >
Add
</button>
Then in my component
methods: {
assignProp: function (type_id, property_id) {
var assignPropForm = new SparkForm({
propvalue: property_id,
typevalue: type_id,
});
Spark.post('/asset-properties/add', assignPropForm)
.then(response => {
console.log(response);
})
.catch(response => {
console.log("fail");
});
}
}

You need store variables at local data() dep., and geting it by getters function.

Related

Getting a modal to pop up when validation is false

I'm trying to create a page that when you click on add product button a modal pops up with a form that gets filled out.
What I'm trying to do is after you've submitted the form and there are errors then I would like for it to redirect back
and have the modal popup with the error messages.
Here is my code
My controller
public function addProduct(Product $product)
{
$validator = Validator::make(request()->all(), [
'title' => 'required'
]);
if($validator->fails())
{
return redirect()->back()->with([
'errors' => $validator->errors()
])
}
}
My blade file
<button type="button" class="btn btn-sm btn-success" data-toggle="modal" data-target="#addProductModal">
<i class="fa fa-plus"></i> Add Product
</button>
#include('admin.product.add-product')
and this is my modal
<div class="modal fade" id="addProductModal" tabindex="-1" aria-labelledby="addProductModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="addProductModalLabel">Add a Product</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<form action="{{ route('admin.product.addProduct') }}" method="post">
#csrf
<div class="modal-body">
<div class="form-group">
<label for="name">Name</label>
<input type="text" name="name" class="form-control">
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-success">Save changes</button>
</div>
</form>
</div>
</div>
</div>
You can achieve that using sessions.
I'm using Form Requests for validation, and in my CreateCategoryRequest I added:
public function withValidator($validator)
{
if ($validator->fails()) {
\Session::flash('create_category_error', 'Create category validation failed!');
}
}
In blade:
#if (session('create_category_error'))
<script type="text/javascript">
$('#myModal').modal('show');
</script>
#endif
Yes it's that simple :P
Happy coding!
You can use this also.
<!-- Test if validation failed; hence show modal -->
#if($errors->getBag('default')->first('name') != '')
<script type="text/javascript">
$(document).ready(function(){
$("#addProductModal").modal('show');
});
</script>
#endif

how do I send an image from vuejs to laravel server for upload

this is my form
<div class="modal" id="profileModal" tabindex="-1" role="dialog" aria-labelledby="profileModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header text-center">
<h5 class="modal-title">Upload Profile Picture</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="form-group">
<div class="row">
<div class="col-6">
<label>Profile Picture</label>
<input ref="image" id="image" type="file" name="image" accept="image/*" class="form-control" style="border: none" #change="loadImage($event)">
</div>
<div class="col-6">
<img :src="this.image_file" class="uploading-image img-thumbnail" height="128" alt="Preview" />
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-success" #click="submitImage">Upload <i class="fas fa-user-plus"></i></button>
</div>
</div>
</div>
</div>
this method is triggered when I select an image so I can preview before upload, it also stores the image in a variable I have created
loadImage(e){
this.file = e.target.files[0];
const reader = new FileReader();
reader.readAsDataURL(this.file);
reader.onload = e =>{
this.image_file = e.target.result;
};
console.log(this.file);
},
the above code works perfectly and am able to preview the image
these are my variables
formData: new FormData(),
file: null,
image_file: '',
this code handles the sending of request to the server using axios
submitImage(){
this.formData.append('image', this.file, this.file.name);
console.log(this.formData);
axios.put( '/data/profile/image',
this.formData,
{
headers: {
'Content-Type': 'multipart/form-data'
}
},
).then(function(response){
Fire.$emit('profileUpdate');
console.log(response.data);
swal.fire(
'Update',
'Profile Picture Updated Successfully',
'success'
);
})
.catch(function(error){
console.log(error.data);
});
$('#profileModal').modal('hide');
},
this is my laravel server side, an just checking if the request has a file
public function uploadImage(Request $request){
if($request->hasfile('image')){
return "Yes";
}
else{return "No";}
}
the above code returns 'NO' meaning there is no file attached to the formData
please is there anything I am not doing right?
Laravel has an issue receiving form-data from ajax requests using the HTTP VERB PUT, try the same thing using POST instead.
Links: https://github.com/laravel/framework/issues/13457

bootstrap 4 modal not showing after button is clicked with VueJs

I just learned vuejs with bootstrap 4 and I tried to display modal provided that when the create button was not clicked then the HTML modal tag is not displayed in the inspect element, and after the create button click bootstrap modal displayed. When the button create first time click HTML modal tag display on inspect element but bootstrap modal cannot be displayed on the browser page and the second time the bootstrap modal can be displayed. Here is the source code that I made with Laravel, can you help me on this issue, thank you.
User.vue
HTML
<template>
<div class="container">
<div class="row">
<div class="col-sm">
<div class="card-deck mb-3">
<div class="card mb-4 box-shadow">
<div class="card-header bg-success text-white">
<h4 class="my-0 font-weight-bold">
<!-- Button create user -->
<button #click="initAddUser()" class="btn btn-danger btn-sm"><i class="fa fa-plus"></i> Create New User</button>
<span class="float-right">User</span>
</h4>
</div>
<div class="card-body">
<!-- Bootstrap modal -->
<div v-if="showModal" class="modal fade" id="add_user_model" tabindex="-1" role="dialog" aria-labelledby="add_user_model_label" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header bg-info text-white">
<h5 class="modal-title" id="add_user_model_label"><i class="fa fa-plus"></i> Add New User</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
</div>
<div class="modal-body">
<!-- Message errors create user -->
<div class="alert alert-danger" v-if="errors.length > 0">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
<h5>{{ messages }}</h5>
<ul>
<li v-for="error in errors">{{ error }}</li>
</ul>
</div>
<div class="form-group">
<label class="font-weight-bold" for="name">Name :</label>
<input type="text" class="form-control" id="name" name="name" placeholder="Name" v-model="user.name">
</div>
<div class="form-group">
<label class="font-weight-bold" for="name">Email :</label>
<input type="email" class="form-control" id="email" name="email" placeholder="E-mail" v-model="user.email">
</div>
<div class="form-group">
<label class="font-weight-bold" for="password">Password:</label>
<input type="password" class="form-control" id="password" name="password" placeholder="Password" v-model="user.password">
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-sm btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-sm btn-primary" #click="createUser()">Submit</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</template>
Js
<script>
export default {
data() {
return {
user: {
name: '',
email: '',
password: ''
},
errors: [],
users: [],
showModal: false,
}
},
mounted() {
this.readUsers();
},
methods: {
initAddUser() {
this.errors = [];
$("#add_user_model").modal("show");
this.showModal = true;
},
reset() {
this.user.name = '';
this.user.email = '';
this.user.password = '';
},
readUsers() {
axios.get('/user/show')
.then(response => {
this.users = response.data.users;
});
},
createUser() {
axios.post('/user', {
name: this.user.name,
email: this.user.email,
password: this.user.password,
})
.then(response => {
this.reset();
this.users.push(response.data.user);
this.readUsers();
$("#add_user_model").modal("hide");
})
.catch(error => {
this.errors = [];
this.messages = error.response.data.message;
if (error.response.data.errors.name) {
this.errors.push(error.response.data.errors.name[0]);
}
if (error.response.data.errors.email) {
this.errors.push(error.response.data.errors.email[0]);
}
if (error.response.data.errors.password) {
this.errors.push(error.response.data.errors.password[0]);
}
});
}
}
}
</script>
Result images inspect element
This image button first time click https://ibb.co/jKENbU
This image button second time click https://ibb.co/nRy4qp

cannot insert data into vue select sent from laravel

This is the vuejs component for editing song info. the problem here is with tags.I cannot show the tags of the song in vue select for editing.
<template>
<div>
<a data-toggle="modal" :data-target="'#EditModal'+ modalid" #click="select(song)"><span title="edit" class="glyphicon glyphicon-pencil" ></span></a>
<a class=""><span title="delete" class="glyphicon glyphicon-trash"></span></a>
<!-- Modal for editing song tracks-->
<div class="modal fade" :id="'EditModal'+ modalid" tabindex="-1" role="dialog" aria-labelledby="EditModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="EditModalLabel">Edit Song</h5>
<button type="button" class="close" ref="closemodal" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form ref="uploadform">
<div class="form-group">
<div class="row">
<div class="col-md-12">
<div class="col-md-5">
<button type="button" #click="browseImage" class="btn btn-md btn-default">Choose image:</button>
<div id="image_previews">
<img ref='image' class="" v-bind:src="image" width="200px" height="200px" >
<input class="form-control-file" ref="imageinput" type="file" name="feature_image" #change="showImage($event)">
</div>
</div>
<div class="col-md-7">
<div class="form-group">
<label for="title">Song Title:</label>
<input type="text" v-model="esong.title" class="form-control" required maxlength="255">
</div>
<div class="form-group">
<label for="genre"> Genre (tag atleast one) </label>
<v-select :placeholder="'choose tag'" v-model="tagids" label="name" multiple :options="tags"></v-select>
</div>
<div class="form-group">
<label for="upload_type">Song Upload Type</label>
<select name="upload_type" v-model="esong.upload_type" class="form-control">
<option value="public">public( free )</option>
<option value="private">private( for sale )</option>
</select>
</div>
<div class="form-group">
<label for="message-text" class="col-form-label">Description:</label>
<textarea class="form-control" id="message-text" v-model="esong.song_description"></textarea>
</div>
<div class="form-group" v-if="private">
<label for="upload_type">Song price</label>
<input type="text" v-model="esong.amount" class="form-control" required maxlength="255">
</div>
</div>
</div>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-primary" #click="edit">Save</button>
</div>
</div>
</div>
</div><!-- end of modal -->
</div>
</template>
<script>
import vSelect from 'vue-select'
export default {
props: ['song','modalid','index','tags'],
components: {vSelect},
mounted() {
},
watch: {
tagids() {
console.log('changed tagids value');
// this.value = this.tagsid;
}
},
computed: {
private() {
if(this.esong.upload_type == 'private') {
return true;
}
return false;
},
},
methods: {
select(song) {
console.log(song.title);
this.getTagIds(song);
},
edit() {
let formData = new FormData();
formData.append('title', this.esong.title);
formData.append('img', this.esong.img);
formData.append('description', this.esong.song_description);
formData.append('upload_type', this.esong.upload_type);
formData.append('amount', this.esong.amount);
formData.append('tags', JSON.stringify(this.tagids));
formData.append('_method', 'PUT');
axios.post('/artist/songs/' + this.esong.id, formData,{
headers: {
'Content-Type': 'multipart/form-data'
}
}).then(response =>{
this.$refs.closemodal.click();
toastr.success('successfully edited song.');
this.$emit('update', {song:this.esong,index:this.index});
}).catch(error => {
console.log(error);
});
},
getTagIds(song) {
axios.post('/gettagids', song ).then(response =>{
this.tagids = response.data;
}).catch(error =>{
console.log(error);
});
},
browseImage() {
this.$refs.imageinput.click();
},
showImage(event) {
this.esong.img = event.target.files[0];
this.image = URL.createObjectURL(event.target.files[0]);
}
},
data() {
return {
esong: this.song,
tagids: {id:'', name:'', label:''},
name:'name',
image:this.song.image
}
}
}
</script>
<style scoped>
input[type="file"] {
display: none;
}
#image_previews {
border-radius: 5px;background-color: whitesmoke; width: 200px; height: 200px;
}
.btn{
border-radius: 0px;
}
</style>
here I cannot get the selected value that was inserted in my table. I wanted to show the tagged values for a song. I am able to get all object of tagged songs from axios post request but v-select doesn't shows the selected value retrieved from a table.
the object received from laravel is similar to the object provided in options which work well with v-select..but it doesn't show the same structure object provided to v-model..or should I provide other props. the document for vue select has not mentioned any of these things

Laravel 5, Vue 2 - send html form via controller and bind submit action to the component method

I am trying to bind action to component method, to the button which is sent via ajax response (json).
So far I have two Vue components - Service and Modal.
Service:
<template>
<div>
<h1>Services ({{ services.length }})</h1>
<div class="services-actions">
<button type="button" class="btn btn-primary" #click="openModal">Add Service</button>
</div>
<div class="services" v-for="(service, index) in services" :key="service.id">
<p>{{ service.name }}</p>
</div>
</div>
</template>
<script>
export default {
data(){
return {
services: []
}
},
methods: {
getAll(){
axios.get('/admin/services/all', {})
.then((response) => {
this.services = response.data
})
},
openModal(){
axios.get('/admin/services/create', {})
.then((response) => {
Event.$emit('modal:show', response.data)
})
},
save(){
console.log('test');
}
},
mounted(){
this.getAll()
}
}
</script>
Modal:
<template>
<div class="modal fade" tabindex="-1" role="dialog" id="main-modal">
<div class="modal-dialog" role="document">
<div class="modal-content">
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
</template>
<script>
export default {
mounted(){
let mainModal = $('#main-modal')
Event.$on('modal:show', (html) => {
mainModal.find('.modal-content').html(html)
mainModal.modal('show')
})
Event.$on('modal:hide', () => {
mainModal.modal('hide')
})
}
}
</script>
View file:
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title">Modal title</h4>
</div>
<form id=service-store action='/admin/service/store'>
<label for="name">Name</label>
<input type="text" name=name id=name>
</form>
<div class="modal-body">
<p>One fine body…</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
Is it possible bind save changes to the Service component save method when I click the Save changes button?

Resources