Laravel 5.1 datatables reorder row - laravel

I need help.
I'm using yajra/laravel-datatables for include datatables into my project.
All is working.
Now I want to use the row reorder extension: https://datatables.net/extensions/rowreorder/
But when I make a drag and drop with a row seems to work, but is not working.
I think is possible that is reloaded because I use ajax url to load data, unmaking the reorder I do. Is possible?
Well, these are my codes:
Controller:
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$med = new Medicinas;
return view('admin.medicinas.index', ['med' => $med->get()]);
}
/**
* Process datatables ajax request.
*
* #return \Illuminate\Http\JsonResponse
*/
public function anyData()
{
return Datatables::of(User::select('*'))->make(true);
}
Routes:
Route::get('administrator/medicinas', [
'as' => 'admin.medicinas',
'uses' => 'MedicinasController#index'
]);
Route::controller('administrator/medicinas', 'MedicinasController', [
'anyData' => 'datatables.data',
'index' => 'administrator/medicinas',
]);
View:
#extends('app')
#section('content')
<div class="col-xs-12 col-sm-10">
#foreach($med as $medicina)
<div class="col-xs-12 col-sm-4">
{{ $medicina->nombre_comercial }}
</div>
#endforeach
</div>
<table id="users-table" class="table table-striped table-bordered" cellspacing="0" width="100%">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Email</th>
<th>Created At</th>
<th>Updated At</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Id</th>
<th>Name</th>
<th>Email</th>
<th>Created At</th>
<th>Updated At</th>
</tr>
</tfoot>
</table>
<input type="text" name="" value="" placeholder="">
#endsection
#section('scripts')
<script type="text/javascript">
$(function() {
var table_id = '#' + 'users-table';
window.table = $(table_id).DataTable({
rowReorder: true,
processing: true,
serverSide: true,
ajax: '{!! route('datatables.data') !!}',
columns: [
{ data: 'id', name: 'id' },
{ data: 'name', name: 'name' },
{ data: 'email', name: 'email' },
{ data: 'created_at', name: 'created_at' },
{ data: 'updated_at', name: 'updated_at' }
]
});
window.table_h = $(table_id + ' thead th');
window.table_f = $(table_id + ' tfoot th');
});
</script>
#endsection

This is my layout:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Medicinas de amoooor</title>
{!! Html::style('assets/css/bootstrap.css') !!}
{!! Html::style('assets/css/bootstrap-switch.css') !!}
{!! Html::style('assets/css/bootstrap-tagsinput.css') !!}
{!! Html::style('assets/css/rowReorder.bootstrap.min.css') !!}
{!! Html::style('assets/css/style.css') !!}
<!-- Datatables -->
<link rel="stylesheet" href="//cdn.datatables.net/1.10.7/css/jquery.dataTables.min.css">
<!-- Fonts -->
<link href='https://fonts.googleapis.com/css?family=Arimo:400,400italic,700,700italic' rel='stylesheet' type='text/css'>
{!! Html::style('assets/css/font-awesome.min.css') !!}
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
#include('header')
<!-- Contents -->
#if (Auth::guest())
<div class="row">
<div class="container">
#yield('content')
</div>
</div>
#else
<div class="row">
<div class="container">
#include('admin.sidebar')
#yield('content')
</div>
</div>
#endif
#if (Session::has('errors'))
<div class="container">
<div class="alert alert-danger" role="alert">
<ul>
<strong>Oops! Something went wrong : </strong>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
</div>
#endif
<!-- Footer -->
#include('footer')
<!-- Modal -->
#yield('modal')
<!-- Scripts -->
{!! Html::script('assets/js/jquery-2.1.4.min.js') !!}
{!! Html::script('assets/js/jquery.dataTables.min.js') !!}
{!! Html::script('assets/js/dataTables.jqueryui.min.js') !!}
{!! Html::script('assets/js/dataTables.bootstrap.min.js') !!}
{!! Html::script('assets/js/bootstrap.min.js') !!}
{!! Html::script('assets/js/bootstrap-switch.js') !!}
{!! Html::script('assets/js/bootstrap-tagsinput.js') !!}
{!! Html::script('assets/js/dataTables.rowReorder.min.js') !!}
<!-- DataTables -->
<script src="//cdn.datatables.net/1.10.7/js/jquery.dataTables.min.js"></script>
#yield('scripts')
<script type="text/javascript">
$(function() {
if (typeof table_h !== 'undefined') {
// Setup - add a text input to each header cell
table_h.each( function () {
var title = $(this).text();
$(this).html( '<input type="text" placeholder="Search '+title+'" />' );
} );
}
if (typeof table_f !== 'undefined') {
// Setup - add a text input to each header cell
table_f.each( function () {
var title = $(this).text();
$(this).html( '<input type="text" placeholder="Search '+title+'" />' );
} );
}
// Apply the search
table.columns().every( function () {
var that = this;
if (typeof table_h !== 'undefined') {
$( 'input', this.header() ).on( 'keyup change', function () {
if ( that.search() !== this.value ) {
that
.search( this.value )
.draw();
}
});
}
if (typeof table_f !== 'undefined') {
$( 'input', this.footer() ).on( 'keyup change', function () {
if ( that.search() !== this.value ) {
that
.search( this.value )
.draw();
}
});
}
});
});
</script>

What you need to do is inject the sequence into the data.
<script type="text/javascript">
$(function() {
var table_id = '#' + 'users-table';
window.table = $(table_id).DataTable({
rowReorder: true,
processing: true,
serverSide: true,
ajax: {
url:'{!! route('datatables.data') !!}',
dataSrc: function ( d ) {
for ( var i=0, ien=d.data.length ; i<ien ; i++ ) {
d.data[i].seq = i;
}
return d.data;
}
},
columns: [
{ data: 'id', name: 'id' },
{ data: 'name', name: 'name' },
{ data: 'email', name: 'email' },
{ data: 'created_at', name: 'created_at' },
{ data: 'updated_at', name: 'updated_at' }
]
});
window.table_h = $(table_id + ' thead th');
window.table_f = $(table_id + ' tfoot th');
});
</script>

Related

POST http://localhost/DemoWebsite/wp-admin/custom_Settings.php 404 (Not Found) after ajax call

My server giving me the response as following
when my ajax call to the same page. Before Ajax call everything is working fine on console but after ajax call and updating database, this error is occurring. I think my Ajax_url is not correct but I want to get ajax data on same page that name is "custom_Settings.php" as mentioned in url.
Please help me to solve this error.
Thanks!
jquery-3.4.1.min.js:2 POST
http://localhost/DemoWebsite/wp-admin/custom_Settings.php 404 (Not
Found)
JS
<script type="text/javascript">
var $j = jQuery.noConflict();
$j(document).ready(function(){
saveNewPositions();
});
function saveNewPositions(){
var positions = [];
$j('.updated').each(function(){
positions.push([$j(this).attr('data-index'), $j(this).attr('data-position')]);
$j(this).removeClass('updated');
});
$j.ajax({
url: 'custom_Settings.php',
method: 'POST',
dataType: 'text',
data: {
update: 1,
positions: positions
}, success: function(response){
console.log(response);
}
});
}
</script>
PHP
function wp_pageOrdering_field_settings(){
global $wpdb;
if (isset($_POST['update'])) {
foreach($_POST['positions'] as $position){
$index = $position[0];
$newPosition = $position[1];
}
$wpdb->update(
'wp_page_settings',
array('page_order' => $newPosition),
array('ID' => $index)
);
wp_die();
}
HTML
<html>
<head>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<title></title>
</head>
<body>
<div class="container" style="margin-top: 100px;">
<div class="row justify-content-center">
<div class="col-md-4 col-md-offset-4">
<table class="table table-stripped table-hover table-border">
<head>
<tr>
<td>Page Title</td>
</tr>
</head>
<tbody>
<?php
$var = get_option('Accessable_Pages');
$list = implode(",", $var);
$newRes = $wpdb->get_results("SELECT ID, post_title, page_order FROM wp_page_settings WHERE ID IN ($list) ORDER BY page_order ASC",ARRAY_A);
if($newRes){
foreach ($newRes as $value1 ) {
echo '
<tr data-index="'.$value1['ID'].'" data-position="'.$value1['page_order'].'">
<td>'.$value1['post_title'].'</td>
</tr>
';
}
}
?>
</tbody>
</table>
</div>
</div>
</div>

Laravel & Vue.js. I Can't Fix My Code

I'm working on an application to manage some Cvs.
All my resource functions work perfectly (creating and editing new Cvs etc.)
But in my Vue.js part, it's about showing details for every Cv in a show view using Axios to get data from the database or post using a form.
My console shows a reactivity problem about my variables: infos and info.
Here is my show.blade.php code:
#extends('layouts.app')
#section('content')
<div class ="container" id="app">
<div class="container" id="app">
<div class ="row">
<div class="col-md-12">
<div class="panel-panel-primary">
<div class="panel-heading">
<div class="row">
<div class="col-md-18"> <h3 class="panel-title"> Experience </h3></div>
<div class="col-md-2 text-right">
<button class="btn btn-success" > Ajouter</button>
</div>
</div>
</div>
<div class="panel-body" >
<ul class="list-group">
<li class="list-group-item" v-for="info in infos">
<div class="pull-right">
<button class="btn btn-warning btn-sm">Edit</button>
</div>
<h3>#{{ info.titre }}</h3>
<p>#{{ info.body }}</p>
</li>
</ul>
</div>
</div>
</div>
</div>
<div >
<form class="flex flex-col" #submit.prevent="addExperience">
<textarea class="border rounded p-2 mp-3" v-model="info.titre"></textarea>
<textarea class="border rounded p-2 mp-3" v-model="info.body"></textarea>
<button type="submit" class="border rounded py-2">Commenter</button>
</form>
</div>
</div>
</div>
#endsection
#section('javascripts')
<script src="{{ asset('js/vue.js')}}"> </script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
window.Laravel={!! json_encode([
'csrfToken' => csrf_token(),
'idExperience' => $id,
'url' =>url('/')]) !!} ;
</script>
<script>
var app= new Vue({
el:'#app',
data:{
message: '',
infos: [],
info:{
id:0,
cv_id:window.Laravel.idExperience,
titre:'',
body:'',
}},
methods:{
getExperiences: function() {
axios.get(window.Laravel.url+'/getexperiences/'+window.Laravel.idExperience)
.then(response=>{
console.log(reponse.data);
this.info=reponse.data;})
.catch(error =>{
console.log('errors: ', error);})},
addExperience:function(){
axios.post(window.Laravel.url+'/addexperience', this.info)
.then(repsonse => {
if(response.data.etat){
this.infos.unshift(this.info);
this.info={
id:0,
cv_id:window.Laravel.idExperience,
titre:'',
body:'',
};}})
.catch(error =>{
console.log('errors: ', error)})},
created:function(){
this.getExperiences();})};
</script>
#endsection
And my two functions get Experiences and addExperience in CvController:
public function getExperiences($id){
$cv= Cv::find($id);
return $cv->infos;
}
public function addExperience(Request $request){
$info = new Info;
$info->titre=$request->titre;
$info->body=$request->body;
$info->cv_id=$request->cv_id;
$info->save();
return response()->json(['etat'=> true, 'id'=> $info->id]);
}
And these are my routes:
Route::resource('cvs','CvController');
Route::get('/getexperiences/{id}', 'CvController#getExperiences');
Route::post('/addexperience', 'CvController#addExperience');
My console:
There are some syntax errors that need to be fixed first.
There's an extra ")" at the end of your created method
The methods property is missing a closing "}"
There's a missing ")" at the very end to match the opening new Vue( parenthesis.
It's helpful to indent your code to make these things easier to spot.
Then, you'll need to update your data to be a function that returns an object. See Vue Docs - Data Must Be a Function
You also have some typos for the "response" variable.
Lastly, in your HTML you have two divs that have id="app".
Your JS should look something like:
var app = new Vue({
el: '#app',
data: {
message: '',
infos: [],
info: {
id: 0,
cv_id: window.Laravel.idExperience,
titre: '',
body: '',
}
},
methods: {
getExperiences: function () {
axios.get(window.Laravel.url + '/getexperiences/' + window.Laravel.idExperience)
.then(response => {
console.log(reponse.data);
this.info = response.data;
})
.catch(error => {
console.log('errors: ', error);
})
},
addExperience: function () {
axios.post(window.Laravel.url + '/addexperience', this.info)
.then(response => {
if (response.data.etat) {
this.infos.unshift(this.info);
this.info = {
id: 0,
cv_id: window.Laravel.idExperience,
titre: '',
body: '',
};
}
})
.catch(error => {
console.log('errors: ', error)
})
},
created: function () {
this.getExperiences();
}
}
});
Let me know if that works for you.

How to reload the data of a table with vue and axios?

Well, i have a table populated with v-for: "usuario in usuarios". The initial charge does it correctly. But when i push the button "Buscar" only my <p>{{nombre}}</p> shows data. Look at these pictures:
Table populated with data
In the above picture, the table was populated with data, through getUsuarios() method. But in the next picture the table only shows blank data.
Table with blank data and <p>{{nombre}}</p>
Here are my codes:
Template:
<div>
<div class="panel panel-default">
<div class="panel-heading"><h1><strong>Lista de nombres</strong></h1></div>
<div class="panel-body">
<table class="table table-hover table-bordered table-striped">
<thead>
<tr>
<th>Nombre</th>
<th>Apellido Paterno</th>
<th>Apellido Materno</th>
</tr>
</thead>
<tbody>
<tr v-for="usuario in usuarios">
<td>{{usuario.Nombre}}</td>
<td>{{usuario.Apellido_P}}</td>
<td>{{usuario.Apellido_M}}</td>
</tr>
</tbody>
</table>
</div>
</div>
<br />
<p>Buscar usuario</p>
<div class="form-group">
<div class="input-group">
<input type="text" class="form-control" v-model="busqueda" placeholder="Buscar usuario" />
<button class="btn btn-default" v-on:click="buscarUsuario">Buscar</button>
</div>
<p>{{nombre}}</p>
</div>
</div>
</template>
Script
<script>
import axios from 'axios'
export default {
data() {
return {
usuarios:[],
busqueda: '',
nombre: '',
}
},
methods: {
buscarUsuario() {
axios.get('http://localhost:50995/api/GetUsuario?id=' + this.busqueda)
.then(response => {
this.usuarios = response.data,
this.nombre = response.data.Nombre
}).catch(e => {
console.log(e)
})
},
getUsuarios() {
axios.get("http://localhost:50995/api/GetUsuarios")
.then(response => {
this.usuarios = response.data
})
.catch(e => {
console.log(e)
})
}
},
created() {
this.getUsuarios(),
this.buscarUsuario()
}
}
</script>
As you can see, the <p>{{nombre}}</p> is populated with the data of the ID that i put in the input. But the table only shows blank data.
The <p>{{nombre}}</p> is only for test if the buscarUsuario() method works, and it's works but not with the table.
And, how can i reload the data of the table with the properties of the ID when i push the "Buscar" button?
Thank you
Something is wrong in your buscarUsuario() logic: you are overwriting the initial correct array of usuario objects with a single object of one usuario
axios.get('http://localhost:50995/api/GetUsuario?id=' + this.busqueda)
.then(response => {
/* REMOVE THIS LINE */ this.usuarios = response.data,
this.nombre = response.data.Nombre
}).catch(e => {
console.log(e)
})

Yajra Datatable custom Model Attribute

I'm using Yajra Datatables for Laravel and it won't show the custom attribute for my User model. This is my User model:
protected $appends = ['sum_work_hours'];
public function work_hours()
{
return $this->hasMany(WorkHour::class);
}
public function getSumWorkHoursAttribute()
{
return $this->work_hours->sum('hours_total');
}
And this is in Controller:
public function showHours()
{
return view('hour');
}
public function getHoursDatatable()
{
$users = User::select(['name', 'email', 'sum_work_hours']);
return Datatables::of($users)->make();
}
And in view:
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.15/css/dataTables.bootstrap.min.css">
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="panel panel-default">
<div class="panel-heading">All Working Hours</div>
<div class="panel-body">
<table id="users-table" class="table table-striped table-bordered">
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Sum Work Hours</th>
</tr>
</thead>
</table>
</div>
</div>
</div>
</div>
</div>
<script src="https://cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.15/js/dataTables.bootstrap.min.js"></script>
<script type="text/javascript">
$(function() {
$('#users-table').DataTable({
processing: true,
serverSide: true,
ajax: 'http://127.0.0.1:8000/datatables/get_hours_datatable',
columns: [
{ data: 'name' },
{ data: 'email' },
{ data: 'sum_work_hours' }
]
});
});
</script>
And this is what I get:
What could be wrong?
The problem was in my Controller
public function getHoursDatatable()
{
// this line was wrong
$users = User::select(['name', 'email', 'sum_work_hours']);
return Datatables::of($users)->make();
}
It should have been like this:
$users = User::with('work_hours')->get();
Now I get the results in my table.

Datatables Handlebars Use of undefined constant

I am working on a a page to display a datatables with row details. I have used exactly the info on the website as follow:
#extends('layouts.app')
#section('style')
<!-- CSS -->
<!-- Select2 -->
<link href="{{ asset('/plugins/select2/select2.min.css') }}" rel="stylesheet" type="text/css" />
<!-- DataTables -->
<link rel="stylesheet" href="{{ asset('/plugins/datatables/dataTables.bootstrap.css') }}">
#stop
#section('scriptsrc')
<!-- JS -->
<!-- Select2 -->
<script src="{{ asset('/plugins/select2/select2.full.min.js') }}" type="text/javascript"></script>
<!-- DataTables -->
<script src="{{ asset('/plugins/datatables/jquery.dataTables.min.js') }}" type="text/javascript"></script>
<script src="{{ asset('/plugins/datatables/dataTables.bootstrap.min.js') }}" type="text/javascript"></script>
<script src="{{ asset('/plugins/datatables/handlebars.js') }}"></script>
#stop
#section('content')
<!-- table widget -->
<div class="box box-info">
<div class="box-header">
<i class="fa fa-cloud-download"></i>
<h3 class="box-title">Employee List</h3>
<div class="box-tools pull-right">
<button class="btn btn-box-tool" data-widget="collapse"><i class="fa fa-minus"></i></button>
</div><!-- /.box-tools -->
</div>
<div class="box-body">
<table id="employeeTable" class="display table-bordered table-hover" cellspacing="0" width="100%">
<thead>
<tr>
<th></th>
<th>ID</th>
<th>Manager name</th>
<th>Name</th>
<th>Manager ID</th>
<th>Is Manager</th>
<th>Region</th>
<th>Country</th>
<th>Domain</th>
<th>Subdomain</th>
<th>Management Code</th>
<th>Job role</th>
<th>Type</th>
</tr>
</thead>
</table>
<script id="details-template" type="text/x-handlebars-template">
<table class="extra_info display table-bordered table-hover" cellspacing="0" width="50%">
<tr>
<td>Full name:</td>
<td>{{ name }}</td>
</tr>
</table>
</script>
</div>
</div>
#stop
#section('script')
<script>
$(document).ready(function() {
var employeeTable;
var template = Handlebars.compile($("#details-template").html());
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
employeeTable = $('#employeeTable').DataTable({
serverSide: true,
processing: true,
ajax: {
url: "{!! route('ajaxlistemployee') !!}",
type: "POST"
},
columns: [
{
"className": 'details-control',
"orderable": false,
"searchable": false,
"data": null,
"defaultContent": ''
},
{ data: 'id', name: 'employee.id'},
{ data: 'manager_name', name: 'manager.name'},
{ data: 'name', name: 'employee.name'},
{ data: 'manager_id', name: 'employee.manager_id'},
{ data: 'is_manager', name: 'employee.is_manager'},
{ data: 'region', name: 'employee.region'},
{ data: 'country', name: 'employee.country'},
{ data: 'domain', name: 'employee.domain'},
{ data: 'subdomain', name: 'employee.subdomain'},
{ data: 'management_code', name: 'employee.management_code'},
{ data: 'job_role', name: 'employee.job_role'},
{ data: 'employee_type', name: 'employee.employee_type'},
],
columnDefs: [
{
"targets": [1, 4, 5], "visible": false, "searchable": false
}
],
order: [[2, 'asc']]
} );
// Add event listener for opening and closing details
$('#employeeTable tbody').on('click', 'td.details-control', function () {
var tr = $(this).closest('tr');
var row = employeeTable.row( tr );
if ( row.child.isShown() ) {
// This row is already open - close it
row.child.hide();
tr.removeClass('shown');
}
else {
// Open this row
console.log(row.data());
row.child( template(row.data()) ).show();
tr.addClass('shown');
}
});
} );
</script>
#stop
In the script id details-template that is called, if I use {{ name }}, I get the error Use of undefined constant. But if I put some simple text instead, then everything works (but I don't get my data in this row details of course.
I have checked row.data in the console log and I have all the data available.
What is wrong?
Thanks.

Resources