how can hide a column while printing from DataTable using TableTools - datatable

Code to print excel and pdf
I would like to hide a column from a datatable using tabletool.
var tableTools = new $.fn.DataTable.TableTools(table, {
'aButtons': [
{
'sExtends': 'xls',
'sButtonText': 'Excel',
'sFileName': 'Article.xls'
},
{
'sExtends': 'print',
},
{
'sExtends': 'pdf',
'sFileName': 'Article.pdf',
'bFooter': false
},
],
'sSwfPath': '//cdn.datatables.net/tabletools/2.2.4/swf/copy_csv_xls_pdf.swf'

You need to add "columns" to show (skipping as not to show) as example below:
{extend: 'print',
titleAttr: 'Print the results',
title: '',
exportOptions: {
columns: ':visible',
stripHtml: false,
**columns: [1, 2, 5, 6, 8, 9, 10]**,
},
text: '<i class="fa fa-print fa-lg text-success"></i>',
message: 'REPORT NAME' ,
customize: function (win) {
$(win.document.body)
.css('font-size', '10pt')
.prepend(
'<img src="" style="position:absolute; top:0; left:0;" />'
);
$(win.document.body).find('table')
.addClass('compact')
.css('font-size', 'inherit');
}
}

Related

How to show the detail in a Master-Detail form with Datatables Jquery

I am designing a system with Net Core 5 MVC, I have to show a Master-Detail, I already have the Master view that contains a Datatable, I would like that when clicking on the ID field (according to the image), the view with the detail would be displayed , but I don't know how to call the Detail view.
Header image
The code I have in the master is the following (Controller, JS, View):
This's the controller code:
[HttpPost]
public IActionResult LoadDataGrid()
{
var draw = Request.Form["draw"].FirstOrDefault();
var start = Request.Form["start"].FirstOrDefault();
var length = Request.Form["length"].FirstOrDefault();
var sortColumn = Request.Form["columns[" + Request.Form["order[0][column]"].FirstOrDefault() + "][name]"].FirstOrDefault();
var sortColumnDir = Request.Form["order[0][dir]"].FirstOrDefault();
var searchValue = Request.Form["search[value]"].FirstOrDefault().ToUpper();
pageSize = length != null ? Convert.ToInt32(length) : 0;
skip = start != null ? Convert.ToInt32(start) : 0;
recordsTotal = 0;
List<VDiagramaMasterModel> ListVDiagramaMasterModel = Singleton.Instance.EntityManager.GetEntities<VDiagramaMasterModel>();
ListVDiagramaMasterModel = (from d in ListVDiagramaMasterModel select d).ToList();
/* Si tenemos una cadena de busqueda */
if (searchValue != "")
{
ListVDiagramaMasterModel = ListVDiagramaMasterModel.Where(x => x.DiagramaId.ToString().Contains(searchValue) ||
x.FechaElaboracion.ToString().Contains(searchValue) ||
x.DiagramaNumber.ToUpper().ToString().Contains(searchValue) ||
x.DiagramaName.ToUpper().ToString().Contains(searchValue) ||
x.StatusProcesoName.ToUpper().ToString().Contains(searchValue)).ToList();
}
recordsTotal = ListVDiagramaMasterModel.Count;
/* Reordenar segun lo solicitado en el Grid */
switch (sortColumn)
{
case "diagramaId":
if (sortColumnDir == "asc")
ListVDiagramaMasterModel = ListVDiagramaMasterModel.OrderBy(x => x.DiagramaId).Skip(skip).Take(pageSize).ToList();
else
ListVDiagramaMasterModel = ListVDiagramaMasterModel.OrderByDescending(x => x.DiagramaId).Skip(skip).Take(pageSize).ToList();
break;
default:
break;
}
return Json(new { draw, recordsFiltered = recordsTotal, recordsTotal, data = ListVDiagramaMasterModel });
}
The Javascript File where I load the Master Datatable
$(document).ready(function () {
filter: true, // Filtrado de datos
info: true, // Resultado de busquedas
processing: true, // Muestra/Oculta la leyenda procesando
scrollX: true, // Scroll Horizontal
select: true, // Permite seleccionar el renglon
ordering: true, // Activa el ordenamiento
autoWidth: false, // Apaga el ancho automatico
scroller: { "loadingIndicator": true }, // Complemento de representación virtual para DataTables para mostrar muchos datos en la pantalla muy rápidamente.
serverSide: true, // Habilitar procesamiento del lado del servidor
deferRender: true, // Habilitar renderizado diferido para cargar con AJAX
responsivePriority: 1,
data: null,
ajax: {
url: "/DiagramaMaster/LoadDataGrid/",
type: "POST",
datatype: "json",
},
columns: [ // Definicion de columnas, ID's
{
data: "diagramaId", name: "diagramaId",
render: function (data) {
/* return "<a href='/DiagramaMaster/Details/" + data + "'>" + ("00000" + data).slice(-5) + "</a>"; */
return "<a href='/DiagramaDetail/Details/" + data + "'>" + ("00000" + data).slice(-5) + "</a>";
/*return "<a href ='#WinModal' data-id='" + data + "' data-bs-toggle='modal' class='btnGrdDetails'>" + ("0000" + data).slice(-4) + "</a>";*/
}
},
{
data: "tipoProcesoId", name: "tipoProcesoId",
render: function (data) {
return ("00" + data).slice(-2);
}
},
{ data: "tipoProcesoName", name: "tipoProcesoName"},
{
data: "fechaElaboracion", name: "fechaElaboracion",
render: function (value) {
var dt = new Date(value).toLocaleDateString('es-MX', { year: 'numeric', month: '2-digit', day: '2-digit' });
return dt; }
},
{ data: "diagramaNumber", name: "diagramaNumber"},
{ data: "diagramaName", name: "diagramaName"},
{ data: "diagramaDescripcion", name: "diagramaDescripcion"},
{ data: "diagramaNotas", name: "diagramaNotas" },
{
data: "totalTelaKilos", name: "totalTelaKilos",
render: $.fn.dataTable.render.number(',', '.', 3, '')
},
{
data: "incluirCuellos", name: "incluirCuellos",
render: function (data, type, row) {
if (data == true) { return '<input type="checkbox" checked disabled>'; }
else { return '<input type="checkbox" readonly>'; }
return data;
}
},
{
data: "incluirEstampe", name: "incluirEstampe",
render: function (data, type, row) {
if (data == true) { return '<input type="checkbox" checked disabled readonly>'; }
else { return '<input type="checkbox" readonly>'; }
return data;
}
},
{ data: "statusProcesoId", name: "statusProcesoId" },
{ data: "statusProcesoName", name: "statusProcesoName" },
{ data: "referenciaId", name: "referenciaId"},
{
data: "actionBar", name: "actionBar", title: "Acción", width: "100px", sortable: false,
render: function (data, type, full, meta) {
return "<button href='#WinModal' id='btnDetails' data-id='" + full.diagramaId + "' data-bs-toggle='modal' type='button' class='btnDetails btn btn-primary btn-sm' title='Ver'><i class='fa-solid fa-file-lines'></i></button> " +
"<button href='#WinModal' id='btnEdit' data-id='" + full.diagramaId + "' data-bs-toggle='modal' type='button' class='btnEdit btn btn-primary btn-sm' title='Editar'><i class='fa-solid fa-pencil'></i></button> " +
"<button href='#WinModal' id='btnDelete' data-id='" + full.diagramaId + "' data-bs-toggle='modal' type='button' class='btnDelete btn btn-danger btn-sm' title='Eliminar'><i class='fa-solid fa-trash'></i></button> ";
}
},
],
order: [[0, 'asc']],
// 0:diagramaId, 1:tipoProcesoId, 2:tipoProcesoName, 3:fechaElaboracion, 4:diagramaNumber, 5:diagramaName
// 6:diagramaDescripcion, 7:diagramaNotas, 8:totalTelaKilos, 9:incluirCuellos, 10:incluirEstampe,
// 11: statusProcesoId, 12:statusProcesoName, 13:referenciaId, 14:actionBar
columnDefs: [
{ visible: false, targets: [1, 6, 7, 11] },
{ searchable: false, targets: [1, 2, 6, 7, 8, 9, 10, 11, 12, 13, 14] },
{ sortable: false, targets: [1, 6, 7, 8, 9, 10, 11, 13, 14] },
{ className: "dt-body-center", targets: [0, 9, 10, 12, 13, 14] },
{ className: "dt-body-right", targets: [8] },
{ "width": "20px", "targets": [0] },
{ "width": "25px", "targets": [3, 9, 10] },
{ "width": "30px", "targets": [2, 13] },
{ "width": "70px", "targets": [8, 12] },
{ "width": "80px", "targets": [4] },
{ "width": "350px", "targets": [5] },
],
// Cargar el Idioma Español //
language: {
url: "/js/language_pack/es-ES.json"
},
});
/* ******************** */
/* Dibujar la DataTable */
/* ******************** */
tableBase.draw()
}); // Fin $(document).ready(function () {});
View to load the master
#* Archivo cshtml para cargar el Maestro #*
<div id="divContainer" class="container-fluid">
<h1>Listado de Diagramas</h1>
<hr/>
<div class="row">
<p><button href="#WinModal" id="btnNew" type="button" asp-action="Create" class="btnNew btn btn-primary btn-md" data-bs-toggle="modal" title="Nuevo Diagrama" ><i class="fa-solid fa-plus"></i> Nuevo</button></p>
</div>
<span class="text-danger">#ViewBag.ErrorMessage</span>
<div class="table table-responsive">
<table id="tableGrid" class="display cell-border"">
<thead style="font-size:12px; color: white; background-color: #2C3E50;">
<tr>
<th>#Html.DisplayNameFor(model => model.DiagramaId)</th>
<th>#Html.DisplayNameFor(model => model.TipoProcesoId)</th>
<th>#Html.DisplayNameFor(model => model.TipoProcesoName)</th>
<th>#Html.DisplayNameFor(model => model.FechaElaboracion)</th>
<th>#Html.DisplayNameFor(model => model.DiagramaNumber)</th>
<th>#Html.DisplayNameFor(model => model.DiagramaName)</th>
<th>#Html.DisplayNameFor(model => model.DiagramaDescripcion)</th>
<th>#Html.DisplayNameFor(model => model.DiagramaNotas)</th>
<th>#Html.DisplayNameFor(model => model.TotalTelaKilos)</th>
<th>#Html.DisplayNameFor(model => model.IncluirCuellos)</th>
<th>#Html.DisplayNameFor(model => model.IncluirEstampe)</th>
<th>#Html.DisplayNameFor(model => model.StatusProcesoId)</th>
<th>#Html.DisplayNameFor(model => model.StatusProcesoName)</th>
<th>#Html.DisplayNameFor(model => model.ReferenciaId)</th>
<th></th>
</tr>
</thead>
<tbody style="font-size:12px;">
</tbody>
</table>
</div>
</div>
#section scripts{
<!-- Para usar las funciones del grid -->
<script src="/js/dtg_config/diagramamaster.js"></script>
}
In order not to extend too much, the Detail is set up in a similar way (View, Controller, JS), but as I mentioned, I don't know how to do it so that when the ID is clicked, it brings me the view with the Detail and puts it in a DataTable, the following code is where I put together the DT of the detail.
// js para configurar la DataTable del detalle
$(document).ready(function () {
/* Nombre del Modelo con el que se trabajara, se */
/* pasa como parametro a la accion del controlador */
//var workingModel = { Name: "CatConsignatarioModel" };
/* *********************************************** */
$('#tableGrid').DataTable({
dom: "lfrtip", // DOM [B]: Butons (PDF, Excel, etc.), [l]:Cantidad [f]:Filtro, [r]:Visualizacion del proceso, [t]:Tabla [i]:Informacion, [p]:Paginación
//buttons: ["copy", "excel"], // Botones de "copy", "excel", "pdf", "csv" y "print"
filter: true, // Filtrado de datos
info: true, // Resultado de busquedas
processing: true, // Muestra/Oculta la leyenda procesando
scrollX: true, // Scroll Horizontal
select: true, // Permite seleccionar el renglon
ordering: true, // Activa el ordenamiento
autoWidth: false, // Apaga el ancho automatico
responsive: true, // Tabla responsiva
lengthMenu: [[50, 100, 150, -1], [50, 100, 150, "All"]],
responsivePriority: 1,
scroller: { "loadingIndicator": true }, // Complemento de representación virtual para DataTables para mostrar muchos datos en la pantalla muy rápidamente.
serverSide: true, // Habilitar procesamiento del lado del servidor
deferRender: true, // Habilitar renderizado diferido para cargar con AJAX
responsivePriority: 1,
data: null,
ajax: {
url: "/DiagramaDetail/LoadDataGrid/", //<<- This is where I don't know how to put the DiagramId
type: "POST",
datatype: "json",
},
columns: [ // Definicion de columnas, ID's
{
data: "diagramaId", name: "diagramaId",
render: function (data) {
/* return "<a href='/DiagramaMaster/Details/" + data + "'>" + ("00000" + data).slice(-5) + "</a>"; */
return "<a href ='#WinModal' data-id='" + data + "' data-bs-toggle='modal' class='btnGrdDetails'>" + ("0000" + data).slice(-4) + "</a>";
}
}
],
// corte la definicion de columnas para efectos de que no se haga tan extenso
});
/* ******************** */
/* Dibujar la DataTable */
/* ******************** */
tableBase.draw()
});

I need the data ,according to the type I send

My view blade that displays the data of all types but I need the specific type only, where i send it by ajax: "{{ route('taxonomies.json',type) }}".How do I send the type that I want from the given type?
<div class="table">
<table id="taxonomyTable">
<thead>
<tr>
<th>SN</th>
<th>Title</th>
<th>Parent</th>
<th>Status</th>
<th>Action</th>
</tr>
</thead>
</table>
</div>
<div class="modal fade" id="quickModal" tabindex="-1" role="dialog" aria-labelledby="quickModal" aria-hidden="true">
</div>
<input type="hidden" id="type" value="{{ $type }}" />
and the js is:
<script>
$(document).ready(function () {
var type = $('#type').val();
$('#taxonomyTable').DataTable({
processing: true,
serverSide: true,
ajax: "{{ route('taxonomies.json') }}",
columns: [
{
data: 'id',
render: function (data, type, row) {
return '<strong> #' + data + '</strong>';
}
},
{
data: 'title', name: 'title',
render: function (data, type, row) {
return '<strong>' + data + '</strong>';
}
},
{
data: 'parent', name: 'parent',
render: function (data, type, row) {
return '<strong>' + data.title + '</strong>';
}
},
{
data: 'type', name: 'type',
render: function (data, type, row) {
return '<strong>' + data.type+ '</strong>';
}
},
{
data: 'status',
render: function (data, type, row) {
return data === 'Active' ? '<button class="btn btn-outline-success btn-update-status" data-id="' + row.id + '">Active</button>' : '<button class="btn btn-xs btn-outline-danger btn-update-status" data-id="' + row.id + '">Inactive</button>';
}
},
{data: 'action', name: 'action', orderable: false, searchable: false}
]
});
});
</script>
and my route is:
Route::get('/taxonomies/taxonomy-json/{type}', 'Admin\TaxonomyController#taxonomyJson')->name('taxonomies.json');
and my TaxonomyController has:
public function taxonomyJson()
{
$taxonomy = Taxonomy::with('parent')->toJson();
return DataTables::of($taxonomy)
->addIndexColumn()
->addColumn('action', function ($taxonomy) {
return '<div class="table-actions float-left">
<i class="ik ik-edit-2 green"></i>
<i class="ik ik-trash-2 red"></i>
</div>';
})->make();
}
The code mentioned above displays all of the types in the data but I only need the data of given type.Like my types are category, tag, videos,slider,etc and I need the data of types category only.
How can I fetch it?
Change You Input Hidden tag to which include whole route with it's parameters
<input type="hidden" id="type" value="{{ route('taxonomies.json', ['type' => $type]) }}" />
Now, In Your Ajax call pass input hidden type value directly to ajax as url.
var type_url = $('#type').val();
ajax: type_url
This way you don't have to worry about passing dynamic param. value to JS code from PHP code.
& In Your Controller Function
public function taxonomyJson($type=null)
{
$taxonomy = Taxonomy::with('parent')
if ($type) {
$taxonomy = $taxonomy->where('type', $type);
}
$taxonomy = $taxonomy->toJson();
return DataTables::of($taxonomy)
->addIndexColumn()
->addColumn('action', function ($taxonomy) {
return '<div class="table-actions float-left">
<i class="ik ik-edit-2 green"></i>
<i class="ik ik-trash-2 red"></i>
</div>';
})->make();
}
From your question as far I understood that you want filtered data, in order to get filtered data you needed to pass a filter type which you must use to filter your query. Here is an example for you
if ($request->ajax()) {
$users = User::select(
'users.id',
'users.name',
'users_details.first_name',
'users_details.last_name',
'users.email',
'users.membership_no',
'users.is_active',
'users.created_at'
)
->leftJoin('users_details', 'users.id', '=', 'users_details.users_id')
->where('user_group', '<>', 'admin')
->where(function ($query) use ($request) {
$genery = $request->get("genere");
$varsitySession = $request->get("varsity_session");
$yearOfPassing = $request->get("year_of_passing");
$department = $request->get("department");
$bloodGroup = $request->get("blood_group");
$membership = $request->get("membership");
if (isset($genery) && $genery) {
$query->where('users_details.genre', $genery);
}
if (isset($varsitySession) && $varsitySession) {
$query->where('users_details.varsity_session', $varsitySession);
}
if (isset($yearOfPassing) && $yearOfPassing) {
$query->where('users_details.year_of_passing', $yearOfPassing);
}
if (isset($department) && $department) {
$query->where('users_details.department', $department);
}
if (isset($bloodGroup) && $bloodGroup) {
$query->where('users_details.blood_group', $bloodGroup);
}
if (isset($membership) && $membership) {
$query->where('users_details.membership', $membership);
}
if (isset($request->requested) && $request->requested == 0) {
$query->where('users.membership_no', $request->requested);
}
})
->get();
return Datatables::of($users)
->editColumn('name', function ($users) {
return ($users->first_name) ? $users->first_name . ' ' . $users->last_name : $users->name;
})
->editColumn('is_active', function ($users) {
return ($users->is_active) ? 'Active' : 'De-active';
})
->editColumn('membership_no', function ($users) {
return ($users->membership_no) ? $users->membership_no : 'Not Assigned';
})
->editColumn('created_at', function ($users) {
return $users->created_at->toDayDateTimeString();
})
->make(true);
}
Here you can see that I'm generating a query with where clause which are generated from request data
$genery = $request->get("genere");
$varsitySession = $request->get("varsity_session");
$yearOfPassing = $request->get("year_of_passing");
$department = $request->get("department");
$bloodGroup = $request->get("blood_group");
$membership = $request->get("membership");
Here genere,varsity_session,year_of_passing,department,blood_group,membership are my filter data I'm sending with request.
here is my data table code
$('.dataTable').dataTable({
destroy: true,
paging: true,
searching: true,
sort: true,
processing: true,
serverSide: true,
"ajax": {
url: '{{ url('users/datatable')}}',
type: 'POST',
headers: {
'X-CSRF-TOKEN': '{{ csrf_token() }}'
},
'data': function (d) {
d.genere = $("#genere").val();
d.varsity_session = $("select[name = varsity_session]").val();
d.year_of_passing = $("select[name = year_of_passing]").val();
d.department = $("select[name = department]").val();
d.blood_group = $("input[name = blood_group]").val();
d.membership = $("select[name = membership]").val();
d.paymentStatus = $("select[name = paymentStatus]").val();
d.requested = $("select[name = requested]").val();
}
},
"columns": [
{data: 'id'},
{data: 'name'},
{data: 'email'},
{data: 'membership_no'},
{data: 'is_active'},
{data: 'varsity_session'},
{data: 'due_amount'},
{data: 'paid_amount'},
{data: 'created_at'},
{data: 'last_transaction_date'},
{data: 'action'},
],
"columnDefs": [
{"bSortable": false, "targets": [1, 6]},
{"searchable": false, "targets": [4, 6]}
],
lengthMenu: [[10, 50, 100, -1], [10, 50, 100, "All"]],
pageLength: 10,
"dom": 'Blfrtip',
buttons: [
{
extend: 'copy',
text: 'copy',
className: 'btn btn-primary',
exportOptions: {
columns: 'th:not(:last-child)'
}
},
{
extend: 'csv',
text: 'csv',
className: 'btn btn-warning',
exportOptions: {
columns: 'th:not(:last-child)'
}
},
{
extend: 'excel',
text: 'excel',
className: 'btn btn-danger',
exportOptions: {
columns: 'th:not(:last-child)'
}
},
{
extend: 'pdf',
text: 'pdf',
className: 'btn btn-success',
exportOptions: {
columns: 'th:not(:last-child)'
}
},
{
extend: 'print',
text: 'print',
className: 'btn btn-btn-info',
exportOptions: {
columns: 'th:not(:last-child)'
}
}
]
});
});
And my Static Html code
<div class="row">
<div class="col-lg-12">
<div class="table-responsive">
<table class="display compact dataTable">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
<th>Membership No</th>
<th>Status</th>
<th>Versity Session</th>
<th>Due Amount</th>
<th>Paid Amount</th>
<th>Created At</th>
<th>Last Transaction</th>
<th>Action</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<!-- /.col-lg-12 -->
</div>

why react's babel throws duplicate object error, jqgrid on IE?

i have loaded the following jqGrid grid in regards to car annual check up for maintenance data.
On chrome this looks like this:
This was generated as a react object, the code as follows:
HTML:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/start/jquery-ui.css" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/free-jqgrid/4.13.6/css/ui.jqgrid.min.css" />
</head>
<body>
<div id="divContainer"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.0/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.0/react-dom.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.34/browser.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<script>
$.jgrid = $.jgrid || {};
$.jgrid.no_legacy_api = true;
$.jgrid.useJSON = true;
</script>
<script src="https://rawgit.com/free-jqgrid/jqGrid/master/js/jquery.jqgrid.src.js"></script>
<script type="text/babel" src="sample.jsx">
</script>
</body>
</html>
JSX code:
var SampleGrid = React.createClass({
componentDidMount:function(){
this.gridLoad();
},
gridLoad:function(){
var mydata = [
{ id: "1", test: "Engine checkup", teststart: "12/12/2016", testend: "12/30/2016", passed: true},
{ id: "2", test: "Electrical Checkup", teststart: "1/2/2017", testend: "1/3/2017", passed: false},
{ id: "3", test: "Chasis checkup", teststart: "1/4/2017", testend: "1/5/2017", passed: false},
{ id: "4", test: "Aerodynamics checkup", teststart: "1/6/2017", testend: "1/9/2017", passed: true},
{ id: "5", test: "Balance and stability checkup", teststart: "1/10/2017", testend: "1/12/2017", passed: true},
{ id: "6", test: "Report", teststart: "", testend: "", closed: false }
];
jQuery("#grid100").jqGrid({
colNames: ['test','passed','test started','test ended'],
colModel: [
{name: 'test', index: 'test', width: 220 },
{name: 'passed', index: 'passed', width: 60, align: 'center', formatter: 'checkbox',
edittype: 'checkbox', editoptions: {value: 'Yes:No', defaultValue: 'Yes'}, formatoptions: { disabled: false},
cellattr: function(rowId, tv, rawObject, cm, rdata) {
if (Number(rowId) == 6) { return ' colspan="3"' }},
formatter:function(cellvalue, options, rowObject)
{
if(rowObject.id==6)
{
return '<input type="text" id="txtnotes" ref="refnotes" />';
}
else
{
if(rowObject.passed===true)
{
return '<input type="checkbox" id="cbPassed-'+ rowObject.id +'" checked/>';
}
else
{
return '<input type="checkbox" id="cbPassed-'+rowObject.id+ '" />';
}
}
}
},
{name: 'teststart', index: 'teststart', width: 75, formatter: 'string', sorttype: 'string', align: 'center',
cellattr: function(rowId, tv, rawObject, cm, rdata) {
if (Number(rowId) == 6) { return ' style="display:none;"' }}},//return ' colspan="5"'
{name: 'testend', index: 'testend', width: 75, formatter: 'string', sorttype: 'string', align: 'center',
cellattr: function(rowId, tv, rawObject, cm, rdata) {
if (Number(rowId) == 6) { return ' style="display:none;"' }}}
],
rowNum: 10,
rowList: [5, 10, 20],
threeStateSort:true,
gridview: true,
rownumbers: false,
autoencode: true,
ignoreCase: true,
sortname: "id",
viewrecords: true,
sortorder: "desc",
shrinkToFit: false,
});
for(var i=0;i<=mydata.length;i++)
jQuery("#grid100").jqGrid('addRowData',i+1,mydata[i]);
jQuery("#grid100").jqGrid('setGroupHeaders', {
useColSpanStyle: true,
groupHeaders:[
{startColumnName: 'passed', numberOfColumns: 3, titleText: 'Test Duration'}
]
});
},
render:function(){
return(<div id="gridContainer" ref="refContainer">
<form>
<table id="grid100"></table>
</form>
</div>
)
}
})
ReactDOM.render(<SampleGrid />, document.getElementById('divContainer'));
But this behaves funny. when i ran the code in chrome it works perfectly fine but when i ran this on IE (my version is 10) it gives the following error on console
SCRIPT1046: Multiple definitions of a property not allowed in strict mode
At the moment i cannot figure out why the same code produces results in one browser and not in another. But i know this error raised since i have added the formater to the column passed
formatter:function(cellvalue, options, rowObject)
{
if(rowObject.id==6)
{
return '<input type="text" id="txtnotes" ref="refnotes" />';
}
else
{
if(rowObject.passed===true)
{
return '<input type="checkbox" id="cbPassed-'+ rowObject.id +'" checked/>';
}
else
{
return '<input type="checkbox" id="cbPassed-'+rowObject.id+ '" />';
}
}
}
How do i fix this issue?
The reason of the problem: the usage of multiple formatter property for the column passed (see formatter: 'checkbox', ..., formatter:function(cellvalue, options, rowObject) {...}). You should remove or comment the formatter: 'checkbox' from your code.
I'd recommend you additionally:
never fill the grid with data using addRowData in the loop. You should remove the lines for(var i=0;i<=mydata.length;i++) jQuery("#grid100").jqGrid('addRowData',i+1, mydata[i]); from your code. Additionally you should add data: mydata parameter and to remove unneeded sortorder: "desc" option.
to remove all index properties from colModel
remove unneeded options gridview: true, rownumbers: false, ignoreCase: true. All the values are already defaults in free jqGrid.

popup kendo window when clicked on grid data

I have created a kendo grid for 10 number of products in my project. I want the kendo window containing the details of the product to popup when I click on the productname displayed in the kendo grid.
I have looked into the demos of the kendo grid but I don't want the details of the product selected to be edited and also I don't want to use a separate column for details button as shown in the examples and demo.
I also looked into the music store demo of kendo ui but I couldn't understand its code as its in jQuery and I am using asp.net mvc with razor syntax for my project
Note:
I want window to appear only when I click on the name of the product and display its details.
You can use:
$('#grid').on("click", "tr.k-state-selected", function (e) {
// open window here
// you have i.e. Id here $('#grid').dataItem($('#grid').select()).Id
});
For this you must set option selectable: "row" in grid configuration.
Otherwise you can use just:
$('#grid').on("click", "tr", function (e) { ... }
You can make use of the detailTemplate for achieving it.
<script>
var wnd,
detailsTemplate;
$(document).ready(function () {
var grid = $("#grid").kendoGrid({
dataSource: {
pageSize: 20,
data: createRandomData(50)
},
pageable: true,
height: 550,
columns: [
{ field: "FirstName", title: "First Name", width: "140px" },
{ field: "LastName", title: "Last Name", width: "140px" },
{ field: "Title" },
{ command: { text: "View Details", click: showDetails }, title: " ", width: "180px" }]
}).data("kendoGrid");
wnd = $("#details")
.kendoWindow({
title: "Customer Details",
modal: true,
visible: false,
resizable: false,
width: 300
}).data("kendoWindow");
detailsTemplate = kendo.template($("#template").html());
});
function showDetails(e) {
e.preventDefault();
var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
wnd.content(detailsTemplate(dataItem));
wnd.center().open();
}
</script>
<script type="text/x-kendo-template" id="template">
<div id="details-container">
<h2>#= FirstName # #= LastName #</h2>
<em>#= Title #</em>
<dl>
<dt>City: #= City #</dt>
<dt>Birth Date: #= kendo.toString(BirthDate, "MM/dd/yyyy") #</dt>
</dl>
</div>
</script>
Go to this fiddle for a working demo
[UPDATE]
Here's the code snippet for showing the window while clicking on the Product Name
<script>
var wnd,
detailsTemplate;
$(document).ready(function () {
var grid = $("#grid").kendoGrid({
dataSource: {
pageSize: 20,
data: createRandomData(50)
},
pageable: true,
height: 550,
columns: [
{ field: "FirstName", title: "First Name", width: "140px",attributes: { "class": "FirstName"} },
{ field: "LastName", title: "Last Name", width: "140px" },
{ field: "Title" }]
}).data("kendoGrid");
wnd = $("#details")
.kendoWindow({
title: "Customer Details",
modal: true,
visible: false,
resizable: false,
width: 300
}).data("kendoWindow");
detailsTemplate = kendo.template($("#template").html());
$('#grid').on("click", ".FirstName", function (e) {
e.preventDefault();
var dataItem = $("#grid").getKendoGrid().dataItem($(e.currentTarget).closest("tr"));
wnd.content(detailsTemplate(dataItem));
wnd.center().open();
});
});
</script>
<script type="text/x-kendo-template" id="template">
<div id="details-container">
<h2>#= FirstName # #= LastName #</h2>
<em>#= Title #</em>
<dl>
<dt>City: #= City #</dt>
<dt>Birth Date: #= kendo.toString(BirthDate, "MM/dd/yyyy") #</dt>
</dl>
</div>
</script>
Working demo is here

Kendo UI Grid One column changes it effects to the another column

I have grid. In that grid, i have 3 columns like name, qty1 and qty2.
Both qty1 and qty2 will be NumericText Boxes.
here my question is if i change qty1 values this value effects to the qty2.
Example:
qty1 has a max value will be 10. based on this value qty2 will not exceed 10.
qty1 has a max value will be 20. based on this value qty2 will not exceed 20.
How i can give validation here.
You should define custom rules/messages in the kendo validator widget to check the values inputted into the second textbox against the first:
e.g.
html:
<div id="form-stuff">
<input id="Value1" name="Value1" type="number" />
<div style="clear"></div><br />
<input id="Value2" name="Value2" type="number" />
<div style="clear"></div><br />
<div class="validation-tooltip-wrapper"><span class="k-invalid-msg" data-for="Value2" style="position:relative;"></span></div>
<div style="clear"></div><br />
<button id="btn-submit" type="button" class="k-button k-button-icontext"><span class="k-icon k-update"></span>Submit</button>
<span id="results"></span>
</div>
JS:
$('#Value1').kendoNumericTextBox({
min: 0,
max: 10,
value: 0,
format: '#'
});
$('#Value2').kendoNumericTextBox({
value: 0,
min: 0,
format: '#'
});
$('#form-stuff').kendoValidator({
rules: {
qty2: function(input) {
if(input.is('[name=Value2]')) {
var input1 = $('#Value1').data('kendoNumericTextBox'), maxAmount = input1.max();
return (Number(input.val()) <= maxAmount);
}
return true;
}
},
messages: {
qty2: 'amount exceeded'
}
});
$('#btn-submit').on('click', function() {
var validator = $('#form-stuff').data('kendoValidator');
if(validator.validate()) {
$('#results').text('Valid!');
} else {
$('#results').text('Invalid!');
}
});
The jsFiddle for this can be seen here:
http://jsfiddle.net/d6R4X/7/
I hope this helps...
Finally, I solved my self. I am given the following example in JSFiddle.
html:
js:
var data = [
{ Name: "Ranga Reddy", MaxMarks: 10, MinMarks:6 },
{ Name: "Vinod Reddy", MaxMarks: 9, MinMarks:7 }
]
var dataSource = new kendo.data.DataSource({
pageSize: 20,
data: data,
autoSync: true,
schema: {
model: {
fields: {
Name: { validation: { required: true } },
MaxMarks: { type: "number", validation: { required: true, min: 0, max: 10} },
MinMarks: { type: "number", validation: { required: true} }
}
} // fields
} // model
});
$("#grid").kendoGrid({
dataSource: dataSource,
pageable: true,
height: 430,
toolbar: ["create"],
columns: [
{ field:"Name",title:"Name", width:"40%" },
{ field: "MaxMarks", title:"Max Marks", width: "20%" },
{ field: "MinMarks", title:"Min Marks", width: "20%",
editor: function (container, options) {
// create an input element
var input = $("<input name='" + options.field + "'/>");
// append it to the container
input.appendTo(container);
// initialize a Kendo UI numeric text box and set max value
input.kendoNumericTextBox({
max: options.model.MaxMarks,
min:0
});
}
},
{ command: "destroy", title: " ", width: "20%" }],
editable: true
});
see the example in jsfiddle http://jsfiddle.net/rangareddy/SJ85S/28/

Resources