I have the following table:
DataTable
The field "placa" is a relation of the tables "maintenance" and "vehicles", when I try to search by means of a data from the field "placa" the datatable does not return results, how can I solve it?
Controller code:
public function mantenimientoData()
{
$mantenimiento = Mantenimiento::all();
return Datatables()
->eloquent(Mantenimiento::query())
->addColumn('placa', function($mantenimiento){
if ($mantenimiento->vehiculo_id) {
return $mantenimiento->vehiculos->placa;
} else {
return 'N/A';
}
})
->addColumn('btn', 'mantenimientos.actions')
->rawColumns(['btn'])
->make(true);
}
My view:
var table = $("#mantenimientos-table").DataTable({
serverSide: true,
pageLength: 10,
ajax: '{!! route('datatables.mantenimientos') !!}',
columns: [
{ data: 'nro_ficha', name: 'nro_ficha' },
{ data: 'placa', name: 'placa' },
{ data: 'fecha_ingreso', name: 'fecha_ingreso' },
{ data: 'fecha_egreso', name: 'fecha_egreso' },
{ data: 'estado', name: 'estado' },
{ data: 'valor_total', name: 'valor_total' },
{ data: 'btn', name: 'btn',orderable:false,serachable:false,sClass:'text-center' }
],
});
Maintenance Model:
class Mantenimiento extends Model
{
public function vehiculos()
{
return $this->belongsTo(Vehiculo::class, 'vehiculo_id');
}
}
and finally Vehicles Model:
class Vehiculo extends Model
{
public function mantenimientos()
{
return $this->hasMany(Mantenimiento::class);
}
}
Sorry for my bad English, but in Spanish I couldn't find help
I was able to fix it by applying a join as follows.
In my controller:
public function mantenimientoData()
{
$mantenimientos = Mantenimiento::join('vehiculos', 'vehiculos.id', '=', 'mantenimientos.vehiculo_id')
->select('vehiculos.id', 'vehiculos.placa', 'mantenimientos.nro_ficha',
'mantenimientos.fecha_ingreso', 'mantenimientos.fecha_egreso',
'mantenimientos.estado', 'mantenimientos.valor_total');
return Datatables::of($mantenimientos)
->addColumn('btn', 'mantenimientos.actions')
->rawColumns(['btn'])
->make(true);
}
Then in my view script:
var table = $("#mantenimientos-table").DataTable({
serverSide: true,
pageLength: 10,
ajax: '{!! route('datatables.mantenimientos') !!}',
columns: [
{ data: 'nro_ficha', name: 'mantenimientos.nro_ficha' },
{ data: 'placa', name: 'vehiculos.placa' },
{ data: 'fecha_ingreso', name: 'mantenimientos.fecha_ingreso' },
{ data: 'fecha_egreso', name: 'mantenimientos.fecha_egreso' },
{ data: 'estado', name: 'mantenimientos.estado' },
{ data: 'valor_total', name: 'mantenimientos.valor_total' },
{ data: 'btn', name: 'btn',orderable:false,serachable:false,sClass:'text-center' }
]
});
I share the solution that helped me in case someone else needs it
Related
i Have a function to showing Age on Model
This Model like this :
public function getAgeAttribute()
{
return Carbon::parse($this->attributes['tanggal_lahir'])->age;
}
and i parsing data on view ( without datatable) like
$users->age
but on datatable , not showing this data , just only Age is not showing
My Controller
public function indexDataTables_nonpns()
{
$users = User::with('master_agama','master_unit_kerja')->whereNotIn('nama',['admin'])->whereNotIn('roles_id',['2'])->get();
return Datatables::of($users)->addIndexColumn()
->addColumn('Nama', function ($users) {
return ''.$users->nama.'';
})
->rawColumns(['Nama' => 'Nama'])
->make(true);
}
My View
#push('scripts')
<script>
$(function() {
$('#table').DataTable({
processing: true,
serverSide: true,
responsive: true,
ajax: '{!! route('d_non_pns') !!}',
columns: [
{ data: 'DT_RowIndex', name: 'DT_RowIndex', orderable: false,searchable: false},
{ data: 'Nama', name: 'Nama'},
{ data: 'NIK', name: 'NIK'},
{ data: 'jenis_kelamin', name: 'jenis_kelamin'},
{ data: 'tempat_lahir', name: 'tempat_lahir'},
{ data: 'tanggal_lahir', name: 'tanggal_lahir'},
{ data: 'age', name: 'age'}, // i change this users.age ,but its didnt work
{ data: 'pendidikan', name: 'pendidikan'},
{ data: 'alamat', name: 'alamat'},
{ data: 'master_agama.agama', name: 'master_agama.agama'},
{ data: 'master_unit_kerja.unit_kerja', name: 'master_unit_kerja.unit_kerja'},
],
});
})
</script>
#endpush
someone can correct my fault ?
I have a customers table with each record linking to a customer contact:
http://localhost/untdchem/public/home/customers/contacts/1809
When I click on the above link, I want to display all the contacts for customer 1809 only in a datatable. I am trying to pass the customer ID somehow so I can filter for that customer only. I can fill the table with all the contacts but i want to just load for that customer.
Routes:
//Customer Contacts
Route::get('home/customers/contacts', ['as' => 'customers.contacts', 'uses' => 'CustomerContactsController#index']);
Route::get('home/customers/contacts/data', ['as' => 'customers.contacts.data', 'uses' => 'CustomerContactsController#anyData']);
In my controller:
public function index()
{
// GET request to index
return view('pages.customer_contacts.index');
}
public function anyData()
{
$contacts = customer_contact::select(['CustContactFName','CustContactLName','CustContactCountryCode','CustContactExtension','CustContactPhone','CustContactEmail','CustContactType']);
return Datatables::of($contacts)->make(true);
}
In my view:
<script>
$(function() {
$('#customer-contacts-table').DataTable({
processing: true,
serverSide: true,
ajax: '{!! route('customers.contacts.data') !!}',
columns: [
{ data: 'CustContactFName', name: 'CustContactFName'},
{ data: 'CustContactLName', name: 'CustContactLName'},
{ data: 'CustContactCountryCode', name: 'CustContactCountryCode'},
{ data: 'CustContactExtension', name: 'CustContactExtension'},
{ data: 'CustContactPhone', name: 'CustContactPhone'},
{ data: 'CustContactEmail', name: 'CustContactEmail'},
{ data: 'CustContactType', name: 'CustContactType'}
//{ data: 'action', name: 'action', orderable: false, searchable: false}
],
order: [[0, "desc" ]]
});
});
</script>
Routes
Route::get('home/customers/contacts/{id}', ['as' => 'customers.contacts', 'uses' => 'CustomerContactsController#index']);
Route::get('home/customers/contacts/data/{id}', ['as' => 'customers.contacts.data', 'uses' => 'CustomerContactsController#anyData']);
Controller
I am assuming there is CustId field that identifies which customer the contact record is assigned to. If your structure is different, adjust accordingly.
public function index($id) {
// GET request to index
return view('pages.customer_contacts.index', compact('id'));
}
public function anyData($id){
$contacts = customer_contact::select([
'CustContactFName',
'CustContactLName',
'CustContactCountryCode',
'CustContactExtension',
'CustContactPhone',
'CustContactEmail',
'CustContactType'
])
->where('CustId', '=', $id);
return Datatables::of($contacts)->make(true);
}
JavaScript
Update the line with ajax option:
ajax: '{!! route('customers.contacts.data', ['id' => $id]) !!}',
The correct solution below:
public function index($CustID = null, Request $request)
{
if ($request->ajax()) {
$contacts = customer_contact::select(['CustContactFName','CustContactLName','CustContactCountryCode','CustContactExtension','CustContactPhone','CustContactEmail','CustContactType']);
if ($CustID) {
$contacts->where('CustID', $CustID);
}
//dd($contacts);
return Datatables::of($contacts)
->addColumn('action', function ($contacts) {
$links="";
$links.='Edit | ';
$links.='<a class="delete" href="'.url('home/customers/contacts/delete', [$contacts->CustID]).'">Delete</a> | ';
return $links;
})->make(true);
}
return view('pages.customer_contacts.index', compact('CustID'));
}
<script>
$(function() {
$('#customer-contacts-table').DataTable({
processing: true,
serverSide: true,
ajax: '{!! route('customers.contacts', $CustID) !!}',
columns: [
{ data: 'CustContactFName', name: 'CustContactFName'},
{ data: 'CustContactLName', name: 'CustContactLName'},
{ data: 'CustContactCountryCode', name: 'CustContactCountryCode'},
{ data: 'CustContactExtension', name: 'CustContactExtension'},
{ data: 'CustContactPhone', name: 'CustContactPhone'},
{ data: 'CustContactEmail', name: 'CustContactEmail'},
{ data: 'CustContactType', name: 'CustContactType'},
{ data: 'action', name: 'action', orderable: false, searchable: false}
],
order: [[0, "desc" ]]
});
});
</script>
I have a Kendo UI grid which is set to use inline editing. One column in the grid uses a template and an editor. When I make changes to this column and I click Update for the row, the update in the datasource does not get called.
The column displays a comma-separated list of text in display mode and a multi-select box in edit mode.
Here is my datasource:
var userDataSource = new kendo.data.DataSource({
autoSync: true,
transport: {
read: {
url: "#Url.Action("ManagedUsers", "Manage")" + $("#suppliers").val(),
dataType: "json"
},
update: {
url: "#Url.Action("UpdateUser", "Manage")",
type: "POST"
},
destroy: {
url: "#Url.Action("DestroyUser", "Manage")",
type: "POST"
}
},
schema: {
model: { id: "Id" },
fields: {
Id: { editable: false, nullable: true },
Email: { validation: { required: true } },
IsAdmin: { type: "boolean" },
IsManager: { type: "boolean" },
SupplierRoles: { type: "object" }
}
}
});
And my grid:
var userGrid = $("#userGrid").kendoGrid({
columns: [{
field: "Email",
width: "35%"
},
{
field: "SupplierRoles",
title: "Roles",
template: "#= displayUserSupplierRoles(data.SupplierRoles) #",
editor: userSupplierRoleMultiSelectEditor,
filterable: false,
sortable: false
},
{
field: "IsAdmin",
title: "Admin",
hidden: "#{(!Model.User.IsAdmin).ToString().ToLower();}",
template: "#=IsAdmin ? 'Yes' : 'No' #",
width: "10%"
},
{
field: "IsManager",
title: "Manager",
hidden: "#{(!Model.User.IsManagerForCurrentSupplier).ToString().ToLower();}",
template: "#=IsManager ? 'Yes' : 'No' #",
width: "12%"
},
{ command: ["edit", "destroy"], width: "20%" }],
dataSource: userDataSource,
noRecords: true,
messages: {
noRecords: "There are no users to manage"
},
editable: "inline",
pageable: {
pageSize: 10
},
sortable: true,
filterable: true,
scrollable: true,
resizable: true
});
The editor function for the multi-select column is defined as:
function userSupplierRoleMultiSelectEditor(container, options) {
var selectedRoles = [];
for (var key in options.model.SupplierRoles) {
if (options.model.SupplierRoles[key].HasRole) {
selectedRoles.push(options.model.SupplierRoles[key].Id);
}
}
$("<select data-placeholder='Select roles...'></select>")
.appendTo(container)
.kendoMultiSelect({
dataTextField: "Name",
dataValueField: "Id",
dataSource: {
data: options.model.SupplierRoles,
schema: {
model: { id: "Id" }
}
}
}).data("kendoMultiSelect")
.value(selectedRoles);
}
The grid is populated based upon a user action and done so within this function:
function listUserManagedUsers() {
$.ajax({
url: "#Url.Action("ManagedUsers", "Manage")" + "?supplierName=" + $("#suppliers").val(),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$("#userGrid").data("kendoGrid").dataSource.data(data);
}
});
}
For completeness, I'll include the view model for the grid:
public class ManagedUserViewModel
{
public string Id { get; set; }
public string Email { get; set; }
public bool IsAdmin { get; set; }
public bool IsManager { get; set; }
public List<UserSupplierRole> SupplierRoles { get; set; }
}
public class UserSupplierRole
{
public int Id { get; set; }
public string Name { get; set; }
public bool HasRole { get; set; }
}
When in edit mode, changing the email and clicking on Update calls Update on the datasource. After altering the multiselect and pressing update does not trigger the update call on the datasource.
Can anyone help me with what am I doing wrong?
Thanks!
OK. So I figured out what was going wrong.
Essentially, it was when I bound to the multiselect widget.
Here is the new code:
function userSupplierRoleMultiSelectEditor(container, options) {
$("<select data-placeholder='Select roles...' multiple='multiple' data-bind='value:SupplierRoles'></select>")
.appendTo(container)
.kendoMultiSelect({
dataTextField: "Name",
dataValueField: "Id",
dataSource: {
transport: {
read: function(op) {
var roleCache = localStorage.getItem("roles");
if (roleCache != null || roleCache != undefined) {
op.success(JSON.parse(roleCache));
} else {
$.ajax({
url: "#Url.Action("Roles", "Manage")",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
localStorage.setItem("roles", JSON.stringify(data));
op.success(data);
}
});
}
}
}
}
});
}
I added the data-bind attribute to the select tag and I set it to the roles that the user has. I then set the read in the datasource to get all of the roles.
Once these two pieces were hooked up (with a slight change of the view model), the grid would stay synchronized with its state).
http://jsfiddle.net/bhoff/ZCyPx/50/
$("#grid").kendoGrid({
dataSource:{
data:entries,
schema:{
parse:function (response) {
$.each(response, function (idx, elem) {
if (elem.time && typeof elem.time === "string") {
elem.time = kendo.parseDate(elem.time, "HH:mm:ss");
}
if (elem.datetime && typeof elem.datetime === "string") {
elem.datetime = kendo.parseDate(elem.datetime, "HH:mm:ss");
}
});
return response;
}
}
},
columns:[
{ command: [ "edit" ] },
{ field:"type", title:"Cash Transation Type" },
{ field:"begintime", title:"Begin Time(CT)", format:"{0:hh:mm tt}", editor: timeEditor },
{ field:"endtime", title:"End Time(CT)", format:"{0:hh:mm tt}", editor: timeEditor },
],
editable:"inline",
navigatable:true
});
Based on my example how do I stop the user from editing my "Cash Transation Type" column?
Does it have something to do with this -> editable:"inline" ?
look here
you need to set in the datasource
<script>
var dataSource = new kendo.data.DataSource({
schema: {
model: {
id: "ProductID",
fields: {
ProductID: {
//this field will not be editable (default value is true)
editable: false,
// a defaultValue will not be assigned (default value is false)
nullable: true
},
ProductName: {
//set validation rules
validation: { required: true }
},
UnitPrice: {
//data type of the field {Number|String|Boolean|Date} default is String
type: "number",
// used when new model is created
defaultValue: 42,
validation: { required: true, min: 1 }
}
}
}
}
});
</script>
You would normally set this on your DataSource on the schema.model.fields.
var data = new kendo.data.DataSource({
schema: {
model: {
fields: {
type: { editable: "false" }
Add editable in the field you do not want to enable Edit,
columns:[
{ command: [ "edit" ] },
{ field:"type", title:"Cash Transation Type", editable: false },
{ field:"begintime", title:"Begin Time(CT)", format:"{0:hh:mm tt}", editor: timeEditor },
{ field:"endtime", title:"End Time(CT)", format:"{0:hh:mm tt}", editor: timeEditor },
],
editable:"inline",
navigatable:true
});
I have the following Kendo MVVM grid:
<div id="permissionTypeGrid" data-role="grid"
data-sortable="true"
data-scrollable="true"
data-editable="true"
data-toolbar="['create', 'save', 'cancel']"
data-bind="source: permissionTypes"
data-auto-bind="true"
data-columns="[
{ 'field': 'PermissionType', 'width': 60 },
{ 'field': 'Description', 'width': 300 },
{ 'field': 'DisplayOrder', 'width': 60 },
{ 'command': [{name: 'destroy', text: 'Delete'}], 'width': 40 }
]">
</div>
And the following view model:
self.permissionTypeGrid = kendo.observable({
isVisible: true,
permissionTypes: new kendo.data.DataSource({
schema: {
parse: function (results) {
var permissionTypes = [];
for (var i = 0; i < results.Data.Data.length; i++) {
var permissionType = {
PermissionType: results.Data.Data[i].SystemPermissionTypeCode,
Description: results.Data.Data[i].SystemPermissionTypeDescription,
DisplayOrder: results.Data.Data[i].DisplayOrder
};
permissionTypes.push(permissionType);
}
return permissionTypes;
}
},
transport: {
read: {
url: "/api/ServiceApi?method=Ref/SystemPermissionTypes",
},
create: {
url: "/api/ServiceApi?method=Ref/SystemPermissionTypes"
},
update: {
url: "/api/ServiceApi?method=Ref/SystemPermissionTypes"
},
destroy: {
url: "/api/ServiceApi?method=Ref/SystemPermissionTypes"
},
parameterMap: function (options, operation) {
if (operation !== "read" && options.models) {
return { models: kendo.stringify(options.models) };
}
}
}
})
});
kendo.bind($("#permissionTypeGrid"), self.permissionTypeGrid);
Transport.read works fine, but the url for transport.create is never executed, nor is the parameterMap function. If I add a new record to the grid and then click "Save Changes", shouldn't the parameterMap function always be called? Also, an http request for the read is made as expected, but none gets generated for a create.
You schema needs and ID.
If you add the line model: { id: "DisplayOrder" }, after schema your create will begin firing when you click save changes.
Of course this is not likely to be the field that you will want to use for an ID but it should get you working.
schema: {
model: { id: "DisplayOrder" },
parse: function (results) {
...
}