Making a table with vue-js and Laravel - php

I'm in the beginning of learning laravel and vue-js, so this is rather difficult to me. I want to make a component in vue-js with a table, with sorting and pagination.
When I started the project I only used Laravel and jquery, so now I'm turning to vue js and it's getting complicated. What I have is this:
In my index.blade.php
#extends('layouts.dashboard')
#section('content')
<div class="container">
<div class="row">
<div class="col">
<table class="table">
<thead>
<tr>
<th> #sortablelink('first_name','First name') </th>
<th> #sortablelink('last_name', 'Last name') </th>
<th> #sortablelink('email', 'E-mail address') </th>
<th> #sortablelink('created_at', 'Creation date') </th>
<th></th>
</tr>
</thead>
<tbody is="submissions"></tbody>
</table>
</div>
</div>
</div>
<div class="container">
<div class="row">
<div class="col">
{{ $submissions->appends(\Request::except('page'))->render() }}
<div class="total-submissions">
Total submissions:
{{ $submissions->firstItem() }}-{{ $submissions->lastItem() }} of {{ \App\Submission::count() }}
</div>
</div>
</div>
</div>
#stop
In my component Submissions.vue:
<template>
<tbody>
<tr v-for="submission in submissions" :key="submission.id">
<td> {{submission.first_name}}</td>
<td> {{submission.last_name}} </td>
<td> {{submission.email}} </td>
<td> {{submission.created_at}} </td>
<td>
<a class="btn btn-default btn-primary" id="btn-view"
:href="'/dashboard/submissions/' + submission.id">View</a>
<a class="btn btn-default btn-primary"
id="btn-delete"
:href="'/dashboard/submissions'"
#click.prevent="deleteSubmission(submission)">Delete</a>
<label class="switch">
<input class="slider-read" name="is_read"
v-model="submission.is_checked"
#change="updateCheckbox(submission)"
type="checkbox">
<span class="slider round"></span>
</label>
</td>
</tr>
</tbody>
</template>
<script>
import qs from 'qs';
import axios from 'axios';
export default {
data: function () {
return {
submissions: [],
}
},
beforeCreate() {
},
created() {
},
mounted() {
this.fetch();
},
methods: {
fetch: function () {
let loader = this.$loading.show();
var queryString = window.location.search;
if (queryString.charAt(0) === '?')
queryString = queryString.slice(1);
var args = window._.defaults(qs.parse(queryString), {
page: 1,
sort: 'id',
order: 'asc'
});
window.axios.get('/api/submissions?' + qs.stringify(args)).then((response) => {
loader.hide();
this.submissions = response.data.data
});
},
deleteSubmission(submission) {
this.$dialog.confirm("Are you sure you want to delete this record?", {
loader: true
})
.then((dialog) => {
axios.delete('api/submissions/' + submission.id)
.then((res) => {
this.fetch()
})
.catch((err) => console.error(err));
setTimeout(() => {
console.log('Delete action completed');
swal({
title: "Update Completed!",
text: "",
icon: "success",
});
dialog.close();
}, 1000);
})
.catch(() => {
console.log('Delete aborted');
});
},
updateCheckbox(submission)
{
this.$dialog.confirm("Are you sure?", {
loader: true
})
.then((dialog) => {
axios.put('/api/submissions/' + submission.id, submission,
)
.then(function (response) {
console.log(response.data);
})
.catch(function (error) {
console.log(error);
});
setTimeout(() => {
console.log('Action completed');
dialog.close();
swal({
title: "Update Completed!",
text: "",
icon: "success",
});
}, 0);
})
.catch(() => {
submission.is_checked === false ? submission.is_checked = true : submission.is_checked = false;
console.log('Aborted');
});
},
}
}
</script>
Now what I want to accomplish: Put everything in the component, but since I have php in the table to sort everything how can I do this in vue? I'm trying with bootstrap vue tables, but I'm not sure if I can display data like this. Thanks in advance.

Related

Laravel how to create filter by date for table

so I made an update to my table so the user can search the data filtered by date (year), by adding a drop down menu for the selection. I'm trying to use ajax to filter the date, but somehow I can't get it to work. May I know what is wrong with my code? Or is there another way to filter my table by date?
Blade file for the table view
<section class="content">
<div class="container-fluid">
<div class="row">
<div class="col-12">
<div class="card">
<div class="card-header">
<h3 class="card-title">Tabel Pekerjaan</h3>
<br>
<div class="card-tools">
<i class="fa fa-plus"></i>&nbsp Tambah Pekerjaan
</div>
<div class="col-md-2">
<select id="filter-tahun" class="form-control filter">
<option value="">Pilih Tahun</option>
#foreach ($pekerjaan as $pekerjaans)
<option value="{{$pekerjaans->id}}">{{$pekerjaans->tanggal}}</option>
#endforeach
</select>
</div>
</div>
<!-- /.card-header -->
<div class="card-body table-responsive">
<table id="tabelpekerjaan" class="table table-bordered">
<thead>
<tr>
<th style="width: 10px">No.</th>
<th>Paket Pekerjaan</th>
<th>Tanggal</th>
<th>Nama Perusahaan</th>
<th>Lokasi Pekerjaan</th>
<th>PPK</th>
<th>HPS</th>
<th>Gambar</th>
<th style="width: 120px">Aksi</th>
</tr>
</thead>
<tbody>
#php $no = 1; #endphp
#foreach ($pekerjaan as $pekerjaans)
<tr>
<td>{{$no++}}</td>
<td>{{$pekerjaans->pekerjaan}}</td>
<td>{{$pekerjaans->tanggal}}</td>
<td>{{$pekerjaans->penyedia->nama}}</td>
<td>{{$pekerjaans->lokasi}}</td>
<td>{{$pekerjaans->user->name}}</td>
<td>Rp. {{number_format($pekerjaans->hps,0,',',',')}}</td>
<td>
<img src="{{asset('gambarpekerjaan/'.$pekerjaans->gambar)}}" style="width: 100px"alt="">
</td>
<td>
#if (Auth::user()->status=='super')
Edit
Hapus
#else
Edit
#endif
</td>
</tr>
#endforeach
</tbody>
</table>
</div>
<!-- /.card-body -->
</div>
<!-- /.card -->
</div>
</section>
here is the script
<script>
$(function () {
// let pekerjaan = $("#filter-tahun").val();
/*const table =*/ $('#tabelpekerjaan').DataTable({
"paging": true,
"lengthChange": true,
"searching": true,
"ordering": true,
"info": true,
"autoWidth": true,
"responsive": true,
// "ajax":{
// url: "{{url('')}}/datapekerjaan",
// type:"POST",
// data:function(d){
// d.pekerjaan = pekerjaan;
// return d
// }
// }
});
//Initialize Select2 Elements
$('.select2bs4').select2({
theme: 'bootstrap4'
})
});
#if (session()->has('message'))
toastr.success("{{session()->get('message')}}")
#endif
$('.delete').click(function(){
var idpekerjaan = $(this).attr('data-id');
var namapekerjaan = $(this).attr('data-nama');
Swal.fire({
title: 'Apakah Anda yakin?',
text: "Paket Pekerjaan "+namapekerjaan+" akan dihapus!",
icon: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Ya, yakin!'
}).then((result) => {
if (result.isConfirmed) {
window.location = "/deletepekerjaan/"+idpekerjaan+""
Swal.fire(
'Dihapus!',
'Data berhasil dihapus.',
'success'
)
}
});
});
// $(".filter").on('change',function(){
// pekerjaan = $("#filter-tahun").val()
// table.ajax.reload(null,false)
// })
</script>
I commented on the ajax's part since it doesn't work at all and my table become a mess...
May I know how to resolve this problem? Thank in advance
Check This
$(document).ready(function () {
// Setup - add a text input to each footer cell
$('#example thead tr')
.clone(true)
.addClass('filters')
.appendTo('#example thead');
var table = $('#example').DataTable({
orderCellsTop: true,
fixedHeader: true,
initComplete: function () {
var api = this.api();
// For each column
api
.columns()
.eq(0)
.each(function (colIdx) {
// Set the header cell to contain the input element
var cell = $('.filters th').eq(
$(api.column(colIdx).header()).index()
);
var title = $(cell).text();
$(cell).html('<input type="text" placeholder="' + title + '" />');
// On every keypress in this input
$(
'input',
$('.filters th').eq($(api.column(colIdx).header()).index())
)
.off('keyup change')
.on('change', function (e) {
// Get the search value
$(this).attr('title', $(this).val());
var regexr = '({search})'; //$(this).parents('th').find('select').val();
var cursorPosition = this.selectionStart;
// Search the column for that value
api
.column(colIdx)
.search(
this.value != ''
? regexr.replace('{search}', '(((' + this.value + ')))')
: '',
this.value != '',
this.value == ''
)
.draw();
})
.on('keyup', function (e) {
e.stopPropagation();
$(this).trigger('change');
$(this)
.focus()[0]
.setSelectionRange(cursorPosition, cursorPosition);
});
});
},
}); });
Refer This https://datatables.net/extensions/fixedheader/examples/options/columnFiltering.html

Laravel record not deleting with delete nor destroy

I am using laravel 7. In my CRUD application, I am having trouble deleting a user record. I have tried a variety of methods which I have left commented out so that you can see what I tried. I am using Sweetalert2 for the confirmation call and when I click confirm, it redirects to the correct page but I do not get a success message nor is the record deleted from the database. I am new to Laravel so if anyone can spot where I may have gone wrong, I would sure appreciate it.
Here are the following relevant codes.
(EDIT OF CODE BELOW!!!)
index.blade.php
#extends('layouts.admin')
#section('content')
<div class="container-fluid mt-5">
<!-- Heading -->
<div class="card mb-4 wow fadeIn">
<!--Card content-->
<div class="card-body d-sm-flex justify-content-between">
<h4 class="mb-2 mb-sm-0 pt-1">
Inicio
<span>/</span>
<span>Registered Users</span>
</h4>
</div>
</div>
<!-- Heading -->
<!--Grid row-->
<!--Grid column-->
<div class="row">
<!--Card-->
<div class="col-md-12 mb-4">
<!--Card content-->
<div class="card">
<!-- List group links -->
<div class="card-body">
<h5>Users Online:
#php $u_total = '0'; #endphp
#foreach ($users as $user)
#php
if($user->isUserOnline()) {
$u_total = $u_total + 1;
}
#endphp
#endforeach
{{ $u_total }}
</h5>
<table id="datatable1" class="table table-bordered">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Email</th>
<th>Role</th>
<th class="text-center">Online/Offline</th>
<th class="text-center">Banned/Unban</th>
<th>Action</th>
</tr>
</thead>
<tbody>
#foreach ($users as $user)
<tr>
<input type="hidden" name="id" value="{{ $user->id }}">
<td>{{ $user->id }}</td>
<td>{{ $user->name }}</td>
<td>{{ $user->email }}</td>
<td>{{ $user->role_as }}</td>
<td>
#if($user->isUserOnline())
<label class="py-2 px-3 badge btn-success" for="">Online</label>
#else
<label class="py-2 px-3 badge btn-warning" for="">Offline</label>
#endif
</td>
<td>
#if($user->isBanned == '0' )
<label class="py-2 px-3 badge btn-primary">Not Banned</label>
#elseif($user->isBanned == '1')
<label class="py-2 px-3 badge btn-danger">Banned</label>
#endif
</td>
<td>
<a class="badge badge-pill btn-primary px-3 py-2" href="{{ url('role-edit/'.$user->id) }}">Editar</a>
<a class="delete badge badge-pill btn-danger px-3 py-2" data-toggle="modal" href="{{ url('user-delete/'.$user->id) }}" data-target="#delete" data-id="{{ $user->id }}">Borrar</a>
</td>
</tr>
#endforeach
</tbody>
</table>
{{-- <div>
{{ $users->links() }}
</div> --}}
</div>
<!-- List group links -->
</div>
</div>
<!--/.Card-->
</div>
<!--Grid row-->
</div>
#endsection
#section('scripts')
<script>
$(document).ready(function() {
$(document).on('click', '.delete', function (e) {
e.preventDefault();
var id = $(this).data('id');
swal.fire({
title: "¿Estás Seguro/a?",
text: "¡No podrás revertir esto!",
icon: 'warning',
showCancelButton: true,
cancelButtonText: 'Cancelar',
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Sí, Borralo!'
},
function() {
$.ajax({
type: "POST",
url: "{{url('/user-delete/{id}')}}",
data: {id:id},
success: function (data) {
//
}
});
});
});
});
</script>
#endsection
Within my web.php (relevant code only)
Route::group(['middleware' => ['auth', 'isAdmin']], function () {
Route::get('/dashboard', function () {
return view('admin.dashboard');
});
Route::get('registered-user', 'Admin\RegisteredController#index');
Route::delete('/user-delete/{id}', 'Admin\RegisteredController#destroy');
Route::get('registered-empresa', 'Admin\EmpresaController#index');
Route::get('registered-empleado', 'Admin\EmpleadoController#index');
Route::get('role-edit/{id}', 'Admin\RegisteredController#edit');
Route::put('role-update/{id}', 'Admin\RegisteredController#updaterole');
Route::post('save-empresa', 'Admin\EmpresaController#store');
Route::get('/edit-empresa/{id}', 'Admin\EmpresaController#edit');
Route::put('/empresa-update/{id}', 'Admin\EmpresaController#update');
Route::get('/edit-empleado/{id}', 'Admin\EmpleadoController#edit');
Route::put('/empleado-update/{id}', 'Admin\EmpleadoController#update');
Route::post('save-empleado', 'Admin\EmpleadoController#store');
});
RegisteredController.php (delete function only)
public function destroy(Request $request, $id)
{
// $user = User::findOrFail($id)->delete();
// return redirect()->back()->with('status', 'Usuario ha sido borrado.');
// $user = User::find($id);
// $user->delete();
// return redirect()->back()->with('status', 'Usuario ha sido borrado.');
User::destroy($id);
}
EDIT!!!
I changed the way I am calling the sweetalert2 but am still getting errors. I changed my delete button in index.blade.php to
<a class="delete badge badge-pill btn-danger px-3 py-2" onclick="deleteConfirmation({{ $user->id }})">Borrar</a>
In the same file, I changed the script to the following:
function deleteConfirmation(id) {
swal.fire({
title: "Borrar?",
text: "¿Estás seguro/a?",
icon: "warning",
showCancelButton: !0,
confirmButtonText: "Sí,Borralo!",
cancelButtonText: "Cancelar",
reverseButtons: !0
}).then(function (e) {
if (e.value === true) {
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
$.ajax({
type: 'POST',
url: "{{url('/user-delete')}}/" + id,
data: {_token: CSRF_TOKEN},
dataType: 'JSON',
success: function (results) {
if (results.success === true) {
swal.fire("Done!", results.message, "success");
} else {
swal.fire("Error!", results.message, "error");
}
}
});
} else {
e.dismiss;
}
}, function (dismiss) {
return false;
})
}
I also removed the .ready function as it was causing a conflict with sweetalert2
My Delete function in my RegisteredController now looks like this:
public function delete($id)
{
$delete = User::where('id', $id)->delete();
// check data deleted or not
if ($delete == 1) {
$success = true;
$message = "Usuario borrado exitosamente";
} else {
$success = true;
$message = "Usuario no encontrado";
}
// Return response
return response()->json([
'success' => $success,
'message' => $message,
]);
}
}
And in my web.php, I changed the route to:
Route::post('/user-delete/{id}', 'Admin\RegisteredController#delete');
The sweet alert now pops up and when I click delete, I get the console error:
POST http://ecomsivendo.test/user-delete/4 419 (unknown status)
You also need the headers section for jquery ajax calls.
$.ajax({
type: "POST",
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
//.......
Also make sure you have the meta tag in the <head> on the page.
<meta name="csrf-token" content="{{ csrf_token() }}">
Thank you for all those who tried to help me on this. I ended up giving the code another overhaul and this is what I had to do to get it to work.
I had to change my ajax request in the index.blade.php
function deleteConfirmation(id) {
swal.fire({
title: "Borrar?",
text: "¿Estás seguro/a?",
icon: "warning",
showCancelButton: true,
confirmButtonText: "Sí,Borralo!",
cancelButtonText: "Cancelar"
}).then(function (e) {
if (e.value === true) {
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
$.ajax({
type: 'POST',
url: "{{url('/user-delete')}}/" + id,
headers: {
'X-CSRF-TOKEN': '<?php echo csrf_token() ?>'
},
data: {"id": id, _method: 'delete'},
dataType: 'JSON',
success: function (results) {
if (results.success === true) {
swal.fire("¡Hecho!", results.message, "success");
setTimeout(function() {
location.reload();
}, 1000);
} else {
swal.fire("¡Error!", results.message, "error");
}
}
});
} else {
e.dismiss;
}
}, function (dismiss) {
return false;
})
}
I am not happy with the setTimout function to get the page to reload and if someone can offer a better solution to avoid reload, I would really appreciate it.
in the controller, I had to change the delete function to the following:
public function delete($id)
{
$delete = User::where('id', $id)->delete();
// check data deleted or not
if ($delete == 1) {
$success = true;
$message = "Usuario borrado exitosamente";
} else {
$success = true;
$message = "Usuario no encontrado";
}
// Return response
return response()->json([
'success' => $success,
'message' => $message,
]);
}
And finally in my web.php, I have the route as:
Route::delete('/user-delete/{id}', 'Admin\RegisteredController#delete');
like I mentioned earlier, I feel like the setTimeout is a hack and I would prefer something a bit more elegant.
In the end, the code does what it is supposed to do and that is delete the entry and update the view.

I can't understand how the destroy function work here?

I am working on old laravel project and I have to modify existing one. So I am now trying to understand the code. The project is on laravel and yajra datatable. I can't understand how the destroy function work ? In the view there is a no call for destroy function but when I click the delete button still it is working.
Controller
public function loadSizes()
{
$sizes = Size::select(['id', 'name', 'code'])->get();
return DataTables::of($sizes)
->addColumn('action', function ($size) {
return '<i class="fa fa-wrench" aria-hidden="true"></i>
<button type="button" data-id="' . $size->id . '" class="btn btn-default remove-size remove-btn" data-toggle="tooltip" data-placement="top" title="Delete"><i class="fas fa-trash-alt" aria-hidden="true"></i></button>';
})
->rawColumns(['action'])
->make(true);
}
public function destory(Request $request)
{
$result = Size::where('id', $request->input('size_id'))->delete();
if ($result) {
return "SUCCESS";
} else {
return "FAIL";
}
}
view
#extends('layouts.sidebar')
#section('content')
<div class="row">
<div class="col-sm-12 pad-main">
<div class="row">
<div class="col-md-6">
<h4 class="cat-name"> Size List</h4>
</div>
</div>
<div class="row">
<div class="col-md-12 table-responsive pad-tbl">
<table class="table table-striped" id="size_table">
<thead>
<tr>
<th scope="col"> Name</th>
<th scope="col"> Code</th>
<th scope="col"> Action</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</div>
</div>
#if (Session::has('action'))
#if (Session::get('action') == "create")
#if (Session::has('status_success'))
<script > showAlert("SUCCESS", "Size creation successful");</script >
#elseif(Session::has('status_error')))
<script > showAlert("FAIL", "Size creation fail");</script >
#endif
#elseif(Session::get('action') == "update")
#if (Session::has('status_success'))
<script > showAlert("SUCCESS", "Size update successful");</script >
#elseif(Session::has('status_error')))
<script > showAlert("FAIL", "Size update fail");</script >
#endif
#endif
#endif
<script>
$(document).ready(function () {
$('#size_table').DataTable({
language: {
searchPlaceholder: "Search records"
},
"columnDefs": [
{"className": "dt-center", "targets": "_all"}
],
processing: true,
serverSide: true,
ajax: '{!! url(' / load - sizes') !!}',
columns: [
{data: 'name', name: 'name'},
{data: 'code', name: 'code'},
{data: 'action', name: 'action'},
]
});
});
$(document.body).on("click", ".remove-size", function () {
var size_id = $(this).data('id');
showConfirm("DELETE", "Do you want to delete this Size ?", "deleteSize(" + size_id + ")");
});
function deleteSize(id) {
$.ajax({
type: 'get',
url: '{!! url('delete-size') !!}',
data: {size_id: id},
success: function (data) {
if (data == "SUCCESS") {
$('[data-id="' + id + '"]').closest('tr').remove();
showAlert("SUCCESS", "Delete Size successful");
}
}, error: function (data) {
showAlert("FAIL", "Delete Size fail");
}
});
}
</script>
#endsection
At the bottom of the blade view there is an AJAX in function destory(id).
That AJAX is sending a GET request to a URL delete-size with size id.
Now, if you search your web.php file for that URL (location - routes/web.php), you'll find something like this:
Route::get('delete-size', 'SizeController#destory');
This route would be sending the size id to your destory function, which is in turn searching the Size in your DB and deleting it.
// Controller
public function destroy($id)
{
Tag::find($id)->delete();
Toastr::success('Tag Successfully Deleted',"Success");
return redirect()->back();
}
// Route
Route::group(['as'=>'admin.','prefix'=>'admin','namespace'=>'Admin','middleware'=>['auth','admin']], function (){
Route::resource('tag','TagController');
});
// HTML file
<form id="delete-form-{{ $tag->id }}" action="{{ route('admin.tag.destroy',$tag->id) }}" method="POST" style="display: none;">
#csrf
#method('DELETE')
</form>

Laravel datatable. Illegal string offset 'start'

I have a datatable that works great. However, on the last column I have a button which should do another query and then build a second datatable, based on these results.
As you can see on the following example, when I click on the button 'searchMom' in the first row, it should run a query based on john newman´s mother('mary newman') and put the results on the panel called "Mom".
But it´s not working.
Please see the image and the code below:
View: viewFamily.blade.php
<div class="row">
<div class="col-md-12" id="rowFamily01">
<div class="panel">
<div class="panel-heading">
<div class="box-tools pull-right">
<button type="button" class="btn btn-xs panel_expand"><i class="material-icons md-18">expand_less</i></button>
</div>
<div class="panel-title">Find a person</div>
</div>
<div class="panel-body">
<div class="row">
<div class="col-md-9">
<div class="form-group">
<label class="control-label" for="inputPersonSearch" >Search: </label>
<input id="inputPersonSearch" class="form-control" type="text" name="inputPersonSearch" form="formPerson">
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<label class="control-label" for="btnPersonSearch" style="color: white;">Search:</label>
<button id="btnPersonSearch" class="form-control btn btn-success" type="submit" title="Search" form="formPerson">Search</button>
</div>
</div>
</div>
<div class="row" style="width:100%; margin-left: 0%;">
<div class="col-md-12 datatable" id="datatable-main">
</div>
</div>
</div>
</div>
</div>
</div>
routes: diego_routes.php
Route::group(['prefix' => 'diego', 'namespace' => 'Diego'], function () {
Route::get("/", "DiegoController#index")->name("index");
Route::get("viewFamily", "DiegoController#viewFamily")->name("viewFamily");
Route::post("searchPerson", "DiegoController#searchPerson")->name("searchPerson");
Route::get("searchMom/{mom}", "DiegoController#searchMom")->name("searchMom");
});
controller: DiegoController.php
public function searchMom($mom){
$input = $mom;
//dd($input);
//begining select query
$query = TD_CP_CIDADAO::where('CID_INT_ID_CIDADAO', '>=', "0");
if(!empty($input["filtro"])){
foreach($input["filtro"] as $k=>$v){
if(!empty($k) and !empty($v)){
//$searchValues = preg_split('/,/', $v, -1, PREG_SPLIT_NO_EMPTY);
$searchValues = array_map('trim', $v);
//dd($searchValues);
$query->where(function ($q) use ($searchValues) {
foreach ($searchValues as $value) {
$q->orWhere('CID_STR_DS_NOME', 'like', "%{$value}%");
}
});
}
}
}
//order data
if(!empty($input["order"]) and count($input["order"]) > 0)
{
foreach($input["order"] as $v){
$position = $v["column"];
$column = $input["columns"][$position]["data"];
$dir = !empty($v["dir"])? $v["dir"] : "asc";
$query->orderBy($column, $dir);
}
}
//other params...
$query->skip($input["start"])->take($input["length"]);
$json_data["data"] = $query->get()->toArray();
$json_data["recordsTotal"] = $query->count();
$json_data["recordsFiltered"] = $json_data["recordsTotal"];
$json_data["draw"] = $input["draw"];
return response()->json($json_data);
}
javascript: diego.js
$(document).on("click", ".btnMom", function(e){
e.preventDefault();
$("#newPanels").empty();
$("#newPanels").append(panelMom);
$("#datatable-mom").append(tableMom);
$("#datatable-mom").css("font-size", "12px");
if($.fn.dataTable.isDataTable('table#tbMom')){
$("table#tbMom").DataTable().destroy();
}
$.fn.dataTable.ext.errMode = 'throw';
var filtros = $(this).serializeArray().reduce(function(a, x) { a[x.name] = x.value; return a; }, {});
var options = {
serverSide: true,
processing: true,
retrieve: true,
ajax: {
dataSrc: 'data',
url : $(this).data("url"),
type: 'get',
async: false,
data: {filtro:filtros}
},
columns : columnsMom,
lengthMenu : [ 5, 10, 25 ]
};
$("table#tbMom").DataTable(options);
});
var columnsMom = [
{ data: 'CID_INT_ID_CIDADAO', visible:false},
{ data: 'CID_STR_DS_NOME'},
{ data: 'CID_DAT_DT_NASCIMENTO',
render: function(data, type, row){
return converterData(data);
}, className: "text-center"},
{ data: 'CID_STR_NM_MAE'},
{ data: 'CID_STR_NM_PAI'},
{ data: 'CID_INT_NR_RG', className: "text-center"},
{ data: 'CID_INT_NR_CPF', className: "text-center"},
{ data: 'acao',
render: function(data, type, row, meta){
var b0 = '\n\
\n\
';
return b0;
},orderable: false, className: "text-center"
}];
var panelMom =
`
<div class="panel" id="panelMom">
<div class="panel-heading">
<div class="box-tools pull-right">
<button type="button" class="btn btn-xs panel_expand"><i class="material-icons md-18">expand_less</i></button>
<button type="button" class="btn btn-xs panel_remove"><i class="material-icons md-18">close</i></button>
</div>
<div class="panel-title">Mom</div>
</div>
<div class="panel-body">
<div class="row">
<div class="col-md-12 datatable conteudod" id="datatable-mom">
</div>
</div>
</div>
</div>
`;
var tableMom =
`
<table id="tbMom" class="table table-hover compact" cellspacing="0" width="100%" >
<thead>
<tr>
<th class="hidden">ID</th>
<th>NAME</th>
<th>DOB</th>
<th>MOM</th>
<th>DAD</th>
<th class="text-center">DOC #</th>
<th class="text-center">FIELD #</th>
<th class="text-center">ACTION</th>
</tr>
</thead>
<tbody>
</tbody>
<tfoot>
</tfoot>
</table>
`;
The error message:
The line 219 (controller) shown in error message:
Results on "dd($input)" inside the controller:
I appreciate any help to solve this problem!
Thank you!
You're setting the value of $input to the value of $mom, which is the last value in your URL, so mom equals Mary Newman but the rest of your code expects $input to be an array of parameters like order, columns and start.
You should assign the value of $input as the request parameters, e.g:
public function searchMom($mom)
{
$input = request()->input();
}
Alternatively instead of $input being an array you could use the Request object directly, e.g:
public function searchMom(Request $request, $mom)
{
$request->order;
$request->columns;
$request->start;
}

Jquery UI Sortable with Symfony , sending updates to database

I am trying to add the Jquery UI Sortable behaviour to an existing table (which is populated through a JavaScript Code).I think I followed the right steps from this link Using Jquery UI sortable to sort table rows, yet the order never changes, it's as if the controller function is never called. Here is my code
This is the code in my twig
<table class="table">
<thead>
<tr>
<th class="col-md-2" data-sort="none">{{ 'element.single'|trans }}<span class="required"> *</span></th>
<th class="col-md-2"data-sort="none">{{ 'operation.type.single'|trans }}<span class="required"> *</span></th>
<th class="col-md-4" data-sort="none">{{ 'inspection.point.label'|trans }}<span class="required"> *</span></th>
<!--09:26-----edit-->
<th class="col-md-2" data-sort="none">{{ 'inspection.point.referenceValue'|trans }}</th>
<th class="col-md-2" data-sort="none">
{#bouton import des gammes d'opérations #}
{% if 'inspection_sheet_edit' != app.request.attributes.get('_route') %}
{% if is_granted('INSPECTIONSHEET_IMPORT',equipment) %}
<div class="btn-group pull-right">
<button class="btn btn-default btn-sm" type="submit" name="import">
<i class="fa fa-file"></i>
<span>{{ 'import'|trans }}</span>
</button>
</div>
{% endif %}
{% endif %}
</th>
</tr>
</thead>
<tbody id="tabledivbody" ></tbody>
</table>
<script>
var fixHelper = function(e, ui) {
ui.children().each(function() {
$(this).width($(this).width());
});
return ui;
}
$("#tabledivbody").sortable({
items: "tr",
cursor: 'move',
opacity: 0.6,
helper: fixHelper,
update: function() {
sendOrderToServer();
}
});
function sendOrderToServer() {
var order = $("#tabledivbody").sortable("serialize");
var test='console text';
$.ajax({
type: "POST", dataType: "json", url: "{{ path('post_order') }}",
data: order,
success: function(response) {
if (response.status == "success") {
console.log(test);
window.location.href = window.location.href;
} else {
alert('Some error occurred');
}
}
});
}
</script>
This is the function in my controller
/**
* #Route("/post_order", name="post_order")
*/
public function updateInspectionPointOrder(Request $request)
{
$em=$this->getDoctrine()->getManager();
$data = json_decode($request->request->get('request'));
$count=1;
foreach ($data->getPoints() as $point) {
//$count++;
$em->getRepository('EpxInspectionBundle:InspectionPoint')->updateDisplayOrderInspectionPoint($count,$point->getId());
$em->flush();
$point->setDisplayOrder($count);
$em->getRepository('EpxInspectionBundle:InspectionPoint')->updateDisplayOrderInspectionPoint($count,$point->getId());
$em->flush();
$count++;
}
}
Any insights please.

Categories