Use variable in LARAVEL update form - ajax

I need to use an old() variable value in a #if condition. When i open the UPDATE form, i see the correct value. But I don't know why, when i use old() in a condition the value is NULL. This form is using in fullcalendar. Actually i use ajax.
FORM UPDATE:
<!-- FORM per aggiornare eventi -->
{!!Form::open(['route'=>['events.update',1], 'method'=>'PUT', 'id'=>'updatemodal'])!!}
<div class="form-group">
{!! Form::label('tipologia_evento_id', 'Tipo evento') !!}
<select id="tipologia_evento_id" name="tipologia_evento_id" class="form-control" disabled>
#foreach(DB::table('tipologie_eventi')->get() as $tipologia)
<option
#if(old('_tipologia_evento_id') == $tipologia->id)
selected="selected"
#endif
value="{{$tipologia->id}}">{{$tipologia->nome}}</option>
#endforeach
</select>
</div>
#if(!in_array(old('_tipologia_evento_id'),array(1,2)))
<div class="modal-footer">
<meta name="csrf-token" content="{{ csrf_token() }}">
<a id="delete" data-href="{{ url('events') }}" data-id="" class="btn btn-danger">Elimina</a>
<button id="aggiornaBtn" type="submit" class="btn btn-success" disabled="disabled">Aggiorna</button>
</div>
#endif
{!! Form::close() !!}
AJAX CODE:
$('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,basicWeek,listDay'
},
navLinks: true, // can click day/week names to navigate views
editable: false,
selectable: true,
selectHelper: true,
select: function(start, end){
start = moment(start.format());
end = moment(end.format());
$('#date_start').val(start.format('DD.MM.YYYY'));
$('#date_end').val(end.format('DD.MM.YYYY HH:mm'));
$('#responsive-modal').modal('show');
},
events: BASEURL + '/events',
eventClick: function(event, jsEvent, view){
var date_start = $.fullCalendar.moment(event.start).format('DD.MM.YYYY');
var time_start = $.fullCalendar.moment(event.start).format('HH:mm');
var date_end = $.fullCalendar.moment(event.end).format('DD.MM.YYYY HH:mm');
$('#modal-event #delete').attr('data-id', event.id);
$('#updatemodal').attr("action", '/events/'+event.id);
$('#modal-event #title').val(event.title);
$('#modal-event #description').val(event.description);
$('#modal-event #date_start').val(date_start);
$('#modal-event #time_start').val(time_start);
$('#modal-event #date_end').val(date_end);
$('#modal-event #responsabile').val(event.responsabile);
$('#modal-event #tipologia_evento_id').val(event.tipologia_evento_id);
$('#modal-event').modal('show');
}
});
I tried to use #if(!in_array(old('_tipologia_evento_id'),array(1,2))) but not work good.
Some advice?

You have a typo in your field. Your first field referenced tipologia_evento_id here:
<select id="tipologia_evento_id" name="tipologia_evento_id" class="form-control" disabled>
<!-- Take note it has no _ (underscore) starting -->
But then you wanted to access the value with _ starting it as here:
#if(old('_tipologia_evento_id') == $tipologia->id)
AND here:
#if(!in_array(old('_tipologia_evento_id'),array(1,2)))

Related

How to sort / filter / search data and display in modal in Laravel Vuejs

Scenario 1
I am using v-for loop to print categories on button, now when I click on button it should show me the data related to that category. It is working fine when i use dropdown select category and click search and it displays all the related data.
But how to do it on button click event.
=====
Fetching categories in Button using v-for directives
<form #submit.prevent="product_info_form">
<div class="row mb-4">
<div class="col-3 px-2" v-for="(category, index) in categories" v-bind:value="category.slack" v-bind:key="index">
<button type="submit" class="btn btn-primary btn-lg btn-block py-4 margin-bottom" v-on:click="displaynumbers" v-bind:value="category.slack">{{ category.label }}</button>
</div>
<select name="category" v-model="category" class="form-control custom-select custom-select-lg">
<option value="">Filter by Category..</option>
<option v-for="(category, index) in categories" v-bind:value="category.slack" v-bind:key="index">
{{ category.label }}
</option>
</select>
</div>
</form>
In method I have written following code :
displaynumbers: function(e)
{
var buttonValue = e.target.value;
var formData = new FormData();
formData.append("access_token", window.settings.access_token);
//formData.append("barcode", this.barcode);
//formData.append("product_title", this.product_title);
if(buttonValue != '')
{
alert(buttonValue);
formData.append("product_category", this.buttonValue);
}
else
{
alert('Null vlaue passed');
}
axios.post('/api/get_product', formData).then((response) => {
this.product_processing = false;
console.log(response.data.data);
this.product_list = response.data.data;
if(this.barcode !='' && this.product_list.length == 1){
this.add_to_cart(this.product_list[0]);
this.barcode = '';
}
})
.catch((error) => {
console.log(error);
});
},

How to solve "interpolation inside attributes has been removed". Vue and Laravel 5.8

I'm trying to pass a user auth ID to hidden using Vue and Laravel, but when I submit the form, I get this error:
value="{{ Auth::user()->id }}": Interpolation inside attributes has been removed. Use v-bind or the colon shorthand instead. For example, instead of <div id="{{ val }}">, use <div :id="val">.
Please help me to overcome this error.
My Component Code is
<template>
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">Example Component</div>
<button class="btn btn-success" #click="updateLocation">Update Position</button>
<div class="card-body">
<div id="realtimemap" style="height: 412px; width: 100%;"></div>
<input type="hidden" class="form-control" name="user_id" id="user_id" value="{{ Auth::user()->id }}">
</div>
</div>
</div>
</div>
</div>
<script>
export default{
data(){
return{
map:null,
marker:null,
center:{lat: 10, lng: 10},
data:null,
lineCoordinates:[]
}
},
methods:{
mapInit(){
this.map = new google.maps.Map(document.getElementById('realtimemap'),{
center: this.center,
zoom: 8
});
this.marker = new google.maps.Marker({
map: this.map,
position: this.center,
animation:"bounce",
});
},
updateMap(){
let newPosition = {lat:this.data.lat,lng:this.data.long};
this.map.setCenter(newPosition);
this.marker.setPosition(newPosition);
this.lineCoordinates.push(new google.maps.LatLng(newPosition.lat,newPosition.lng));
var lineCoordinatesPath = new google.maps.Polyline({
path: this.lineCoordinates,
geodesic: true,
map: this.map,
strokeColor: '#FF000',
strokeOpacity: 1.0,
strokeWeight: 2
});
},
updateLocation(){
let randomNumber=Math.random();
let position={
lat:10+randomNumber,
long:10+randomNumber
};
axios.post('/api/map',position).then(response=>{
console.log(response);
})
}
},
mounted() {
console.log('Component mounted.');
this.mapInit();
},
created(){
Echo.channel('location')
.listen('SendLocation', (e) => {
this.data=e.location;
this.updateMap();
console.log(e);
});
}
}
Controller Code is
public function store(Request $request)
{
$input = $request->all();
$realtimelocations = Realtimelocations::create($input);
event(new SendLocation($realtimelocations));
return response()->json(['status'=>'success', 'data'=>$realtimelocations]);
}
please let me know the solution.
Thanks in advance.
You can't use laravel blade interpolation inside vue component file.
You have to think other way.
For example, you can declare user as global javascript variable, and use it in vue.js component.

Toggle form in nested v-for loop in VueJS

I have a list of nested comments. Under each comment, I'd like to add a "reply" button that, when click, show a reply form.
For now, everytime I click a "reply" button, it shows the form. But the thing is, I'd like to show only one form on the whole page. So basically, when I click on "reply" it should close the other form alreay opened and open a new one under the right comment.
Edit :
So I was able to make some slight progress. Now I'm able to only have one active form opening on each level of depth in the nested loop. Obviously, what I'm trying to do now is to only have one at all.
What I did was emitting an event from the child component and handle everything in the parent component. The thing is, it would work great in a non-nested comment list but not so much in my case...
Here is the new code:
In the parentComponent, I have a handleSelected method as such:
handleSelected (id) {
if(this.selectedItem === id)
this.selectedItem = null;
else
this.selectedItem = id;
},
And my childComponent:
<template>
<div v-if="comment">
<div v-bind:style=" iAmSelected ? 'background: red;' : 'background: none;' ">
<p>{{ comment.author.name }}<br />{{ comment.created_at }}</p>
<p>{{ comment.content }}</p>
<button class="button" #click="toggle(comment.id)">Répondre</button>
<button class="button" #click="remove(comment.id)">Supprimer</button>
<div v-show="iAmSelected">
<form #submit.prevent="submit">
<div class="form-group">
<label for="comment">Votre réponse</label>
<textarea class="form-control" name="comment" id="comment" rows="5" v-model="fields.comment"></textarea>
<div v-if="errors && errors.comment" class="text-danger">{{ errors.comment[0] }}</div>
</div>
<button type="submit" class="btn btn-primary">Envoyer</button>
<div v-if="success" class="alert alert-success mt-3">
Votre réponse a bien été envoyée !
</div>
</form>
</div>
</div>
<div v-if="comment.hasReply">
<div style="margin-left: 30px;">
<comment v-for="comment in comments"
:key="comment.id"
:comment="comment" #remove-comment="remove"
:is-selected="selectedItem" #selected="handleSelected($event)">
</comment>
</div>
</div>
</div>
</template>
<script>
import comment from './CommentItem'
export default {
name: 'comment',
props: {
isSelected: Number,
comment: {
required: true,
type: Object,
}
},
data () {
return {
comments: null,
fields: {},
errors: {},
success: false,
loaded: true,
selectedItem: null,
}
},
computed: {
iAmSelected () {
return this.isSelected === this.comment.id;
}
},
methods: {
remove(id) {
this.$emit('remove-comment', id)
},
toggle(id) {
this.$emit('selected', id);
},
handleSelected(id) {
if(this.selectedItem === id)
this.selectedItem = null;
else
this.selectedItem = id;
},
},
mounted(){
if (this.comment.hasReply) {
axios.get('/comment/replies/' + this.comment.id)
.then(response => {
this.comments = response.data
})
}
}
}
</script>
Thanks in advance for your help!

Laravel + Vue how to display values from selected item?

Need help with Vuejs, as I'm very new to it.
I have form selector, and depends on selected item I should display information from selected item below the form and send id of this item to my form request.
Visual understand:
I have tried v-bind:value="post.id" make like v-bind:value="post"
and I can easy display #{{post.goal}}, but it sends {object Object} to my request.
Please help who have more skill.
My selector:
<div class="uk-form-controls" id="equity-name">
<select name="share_id" v-model="post">
<option v-for='post in posts' v-bind:value="post.id">#{{post.title}}</option>
</select>
{{-- Here I need help --}}
<div v-if="post">
selected post:
#{{post.goal}} {{-- HOW TO DISPLAY GOAL IN DOM? --}}
</div>
And my Vue:
<script type="text/javascript">
new Vue({
el: "#equity-name",
data: function() {
return {
posts: [
#foreach($company->equities as $equity)
{title: "{{ $equity->name }}", id: '{{ $equity->id }}', goal: '{{ $equity->goal() }}' },
#endforeach
],
post: null
}
},
})
</script>
Cheers, love!:)
Make a method getPostGoal to get goal of selected index
new Vue({
el:"#app",
data:{
posts:[
{id:1,title:'test1',goal:'goal1'},
{id:2,title:'test2',goal:'goal2'},
{id:3,title:'test3',goal:'goal3'},
],
post:1
},
methods:{
getPostGoal:function(id=null){
if(id){
var index = this.posts.map(e=>e.id).indexOf(id);
return this.posts[index].goal;
}
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<div>
<div class="uk-form-controls" id="equity-name">
<select name="share_id" v-model="post">
<option v-for='p in posts' v-bind:value="p.id">{{p.title}}</option>
</select>
<div v-if="post">
selected post:
{{getPostGoal(post)}}
</div>
</div>
</div>
</div>
Another solution is, set object as value
new Vue({
el:"#app",
data:{
posts:[
{id:1,title:'test1',goal:'goal1'},
{id:2,title:'test2',goal:'goal2'},
{id:3,title:'test3',goal:'goal3'},
],
post:{goal:'NA'}
},
mounted(){
if(this.posts.length){
this.post = this.posts[0];
}
},
methods:{
getPostGoal:function(id=null){
if(id){
var index = this.posts.map(e=>e.id).indexOf(id);
return this.posts[index].goal;
}
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<div>
<div class="uk-form-controls" id="equity-name">
<select name="share_id" v-model="post">
<option v-for='p in posts' v-bind:value="p">{{p.title}}</option>
</select>
<div v-if="post">
selected post:
{{post.goal}}
</div>
</div>
</div>
</div>

Adding records to a drop down menu without form refresh

I want to add records to a drop down menu without form refresh. I'm using codeigniter and bootstrap
Here is the Bootstrap Modal :
<div class="modal fade bs-example-modal-lg" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button aria-hidden="true" data-dismiss="modal" class="close" type="button">×</button>
<h4 id="myLargeModalLabel" class="modal-title">Add Record</h4>
</div>
<div class="modal-body">
<form class="sky-form" id="sky-inchidere" method="post" accept-charset="utf-8" action="">
<dl class="dl-horizontal">
<dt>Name<span class="color-red">*</span></dt>
<dd>
<section>
<label class="input">
<i class="icon-append fa fa-inbox"></i>
<input type="text" value="" name="name" required>
<b class="tooltip tooltip-bottom-right">Add New Record</b>
</label>
</section>
</dd>
</dl>
<hr>
<button type="submit" class="btn-u" style="float:right; margin-top:-5px;">Submit</button>
</form>
</div>
</div>
</div>
Ajax script :
$(document).ready(function(){
$("#sky-inchidere").submit(function(e){
e.preventDefault();
var tdata= $("#sky-inchidere").serializeArray();
$.ajax({
type: "POST",
url: 'http://localhost/new/oportunitati/add',
data: tdata,
success:function(tdata)
{
alert('SUCCESS!!');
},
error: function (XHR, status, response) {
alert('fail');
}
});
});
});
CI Controller ( i have added the modal code here for test )
public function add() {
$tdata = array( name=> $this->input->post(name),
);
$this->db->insert('table',$tdata);
}
When i use this code i get "fail" error message.
Thanks for your time.
how yo debug:
1. Print your 'tdata' and see what happen;
2. Something wrong here: $this->input->post('name');
Try to use:
$tdata = array(
'name' => $this->input->post('name')
);
I manage to find the problem and correct it. (typo on the table name)
Now I have come across a different problem. In the ajax success I cant refresh the chosen dropdown records i have tried :
success:function(tdata)
{
// close the modal
$('#myModal').modal('hide');
// update dropdown ??
$('.chosen-select').trigger('liszt:updated');
$('#field-beneficiar_p').trigger('chosen:updated');
$('#field-beneficiar_p').trigger('liszt:updated');
},
Any help in how i can refresh the records to see the last added item will be appreciated. I'm using chosen plugin.
from controller send data in json_encode
then in js function
$.ajax({
type: "POST",
url: "<?php echo base_url('login/get_time'); ?>",
data: {"consltant_name": consltant_name, "time": time},
success: function(data) {
var data = JSON.parse(data);
var options = '';
options = options + '<option value="">Please Select One</option>'
$.each(data, function(i, item) {
options = options + '<option value="' + item + '">' + item + '</option>'
});
selectbox.html(options);
}});

Resources