ngTable can't generate header - ngtable

I'm using ngTable with this code:
HTML:
<table data-ng-table="tableParams" class="table table-condensed table-bordered table-striped">
<tbody>
<tr data-ng-repeat="task in $data">
<td data-title="''">
<input type="checkbox" style="display: block; margin: auto;" ng-model="task.IsSelected" ng-change="optionToggled()">
</td>
<td data-title="''" style="text-align: center">
<i class="glyphicon glyphicon-flag" ng-show="task.IsToday"></i>
<i class="glyphicon glyphicon-ok" ng-show="task.IsCompleted"></i>
</td>
<td data-title="'Subject'" data-sortable="'Subject'">{{task.Subject}}</td>
<td data-title="'Priority'" data-sortable="'PriorityValue'">{{task.PriorityValue}}</td>
<td data-title="'Status'" data-sortable="'StatusValue'">{{task.StatusValue}}</td>
<td data-title="'Due Date'" data-sortable="'DueDate'">{{task.DueDate}}</td>
<td data-title="'Completed'" data-sortable="'CompletedValue'">{{task.CompletedValue}}</td>
<td data-title="'Date Completed'" data-sortable="'DateCompleted'">{{task.DateCompleted}}</td>
<td data-title="'Action'">
<button type="button" style="display: block; margin: auto;" class="btn btn-info btn-xs" ng-click="editRow(task)">
<i class="glyphicon glyphicon-edit"></i>
</button>
</td>
</tr>
</tbody>
</table>
Javascript:
$scope.tableData = [];
$scope.tableParams = new ngTableParams({
page: 1, // show first page
count: 10, // count per page
sorting: { DueDate: "asc" } // initial sort order,
},
{
paginationMaxBlocks: 10,
paginationMinBlocks: 2,
getData: function($defer, params) {
var sorting = params.sorting();
var keySorting = Object.keys(sorting)[0];
var valueSorting = sorting[keySorting];
var count = params.count();
var pageIndex = params.page() - 1;
var keySearch = angular.isDefined($scope.textSearch) ? $scope.textSearch : '';
taskService.pagingTasks(pageIndex * count, count, keySearch, keySorting, valueSorting).then(function(data) {
var obj = angular.fromJson(data);
params.total(obj.Total);
formatToDateTime(obj.Data);
$scope.tableData = obj.Data;
$defer.resolve(obj.Data);
});
}
});
But when I run my website I see ngTable generate
And my browser console show this error:
I have no idea why ngTable can't generate columns header.
Currently, I must create columns header by manually.

I found my answer:
You can fix this issues base on this post :
AngularJS: 'Template for directive must have exactly one root element' when using 'th' tag in directive template
Modified these lines in file "ng-table.js" and remove tr tag in : "filterRow.html", "groupRow.html", "sorterRow.html".
(template)
$templateCache.put('ng-table/header.html', '<tr ng-if="params.hasGroup()" ng-show="$groupRow.show" class="ng-table-group-header" ng-table-group-row></tr> <tr class="ng-table-sort-header headerrow" ng-table-sorter-row></tr> <tr ng-show="show_filter" class="ng-table-filters" ng-table-filter-row></tr> ');
(directive)
function ngTableGroupRow(){
var directive = {
restrict: 'A',
//replace: true,
templateUrl: 'ng-table/groupRow.html',
scope: true,
controller: 'ngTableGroupRowController',
controllerAs: 'dctrl'
};
return directive;
}
function ngTableSorterRow(){
var directive = {
restrict: 'A',
//replace: true,
templateUrl: 'ng-table/sorterRow.html',
scope: true,
controller: 'ngTableSorterRowController'
};
return directive;
}
function ngTableFilterRow(){
var directive = {
restrict: 'A',
//replace: true,
templateUrl: 'ng-table/filterRow.html',
scope: true,
controller: 'ngTableFilterRowController'
};
return directive;
}

Related

How can I use v-for tag to show elements in the data?

I am creating ec mock-up, and how can I use v-for tag
developing environment
Mac, Vue.js, Atom, Server hostname is https://euas.person.ee/
Rigth Now↓
What I want to do is showing Order ID and Option Image for each row like
Order ID | OrderDescription | Action
1 "OptionImage" Detail Button
OrderListingVue
<template>
<div class="OrderListing">
<h2>My Orders</h2>
<table class="table">
<tr>
<th>OrderId</th>
<th>OrderDescription</th>
<th>Action</th>
</tr>
<tr v-for="(cart, order) in this.orders" :key="order.id">
<td>{{order}}</td>
<td>{{cart}}</td>
<td>
<b-button variant="dark" :to=" '/orders/' + order">Detail</b-button>
</td>
</tr>
</table>
</div>
</template>
<script>
import axios from "axios";
export default {
name: 'OrderListing',
props: {
order: Object
},
data: function() {
return {
orders: []
}
},
mounted() {
axios.get("https://euas.person.ee/user/orders")
.then(response => {
this.orders = response.data;
});
}
}
</script>
<style scoped>
.option-image {
max-height: 50px;
max-width: 100px;
}
</style>
Addition
ShoppingCartVue↓
<template>
<div class="shopping-cart-page">
<h2>ShoppingCart</h2>
<table class="table">
<tr>
<th>Product</th>
<th>Price</th>
<th>qty</th>
<th>Amount</th>
<th>Actions</th>
</tr>
<tr v-for="(item, index) in this.items" :key="item.productId + '_' + index">
<td>
<img :src="item.optionImage" class="option-image" />
</td>
<td>{{ item.price }}</td>
<td>{{ item.qty }}</td>
<td>{{ item.total }}</td>
<td>
<b-button variant="danger" #click="removeItem(index)">Remove</b-button>
</td>
</tr>
<tr class="total-row">
<td>TOTAL:</td>
<td></td>
<td></td>
<td>{{ total }}</td>
<td></td>
</tr>
</table>
<b-button variant="success" size="lg" #click="orderNow" v-if="this.items.length">Order Now!</b-button>
</div>
</template>
<script>
import axios from "axios";
export default {
name: 'ShoppingCartPage',
computed: {
items: function() {
return this.$root.$data.cart.items || [];
},
total: function() {
let sum = 0
for (const item of this.items) {
sum += item.total
}
return sum
}
},
methods: {
removeItem: function(index) {
if (!this.$root.$data.cart.items) this.$root.$data.cart.items = []
this.$root.$data.cart.items.splice(index, 1);
console.log(this.$root.$data.cart.items);
this.$root.$data.saveCart();
},
orderNow: function() {
let data = this.$root.$data
axios.post("https://euas.person.ee/user/carts/" + this.$root.$data.cart.id + "/orders/",
this.$root.$data.cart).then(function() {
data.reinitCart();
})
}
}
}
</script>
<style scoped>
.option-image {
max-height: 50px;
max-width: 100px;
}
</style>
From what I understood you are looking for something like this:
<div v-for="order in orders" :key="order.id">
<div v-for="item in order.items" :key="item.productId">
<img :src="item.optionImage" class="option-image" />
</div>
</div>

Update partialview after Model updaton using Model popup

I have index page which contains 2 partial views.One for displaying Roles and another for displaying corresponding privileges.
#model IEnumerable<sample.Models.Role_Privilege_Map>
#{
ViewBag.Title = "RolePrivilgeMapping";
}
<h2>RolePrivilgeMapping</h2>
<script>
$(document).ready(function () {
registerTableClick();
//$("#tblRole tbody tr:first").trigger();
});
function registerTableClick() {
$("#tblRole tbody tr").on("click", function () {
$(this).siblings().removeClass('selected_row');
$(this).addClass("selected_row");
var roleId = parseInt($(this).find("td:eq(0)").text());
loadPrivilege(roleId);
});
function loadtrackPrivilege(roleId) {
$("#PrivilegeWrapper").load("#Url.Action("PrivilegesPartial", "RolePrivilegeMapping")",
{ 'roleID': roleId },
function (response, status, xhr) {
if (status == "error") {
alert("An error occurred while loading privileges.");
}
});
}
}
</script>
<div id="RolePrivilgeMappingWrapper">
<div class="float-left" id="roleWrapper">
#Html.Partial("_Role", sample.Models.DataProvider.DataProvider.GetRoleNames())
</div>
<div class="float-left" id="PrivilegeWrapper">
#Html.Partial("_Privilege", sample.Models.DataProvider.Provider.GetPrivilegeNames())
</div>
</div>
Here is my _Role.cshtml
#model IEnumerable<sample.Models.webpages_Roles>
#{
ViewBag.Title = "Index";
}
<script type="text/ecmascript">
$(document).ready(function () {
$.ajaxSetup({ cache: false });
$(".editDialog").live("click", function (e) {
var url = $(this).attr('href');
$("#dialog-edit").dialog({
title: 'Edit Role',
autoOpen: false,
resizable: false,
height: 255,
width: 400,
show: { effect: 'drop', direction: "up" },
modal: true,
draggable: true,
open: function (event, ui) {
$(this).load(url);
},
close: function (event, ui) {
$(this).dialog('close');
}
});
$("#dialog-edit").dialog('open');
return false;
});
});
</script>
<div class="settingsTable" style="position: relative; width: 100%; margin: 0 auto">
<div style="width: 50%; margin: 0 auto">
<div style="width: 50%; margin: 0 auto">
<h2>Role</h2>
</div>
</div>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<table id="tblRole">
<tr>
<th>
#Html.DisplayNameFor(model => model.RoleId)
</th>
<th>
#Html.DisplayNameFor(model => model.RoleName)
</th>
<th>Action</th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.RoleId)
</td>
<td>
#Html.DisplayFor(modelItem => item.RoleName)
</td>
<td>
#Html.ActionLink("Edit", "OpenEditRoleDialog", "RolePrivilegeMapping", new { id = item.RoleId }, new { #class="editDialog"}) |
#Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
</td>
</tr>
}
</table>
<div id="dialog-edit" style="display: none">
</div>
</div>
On Role partial view I have edit link for every row displayed.
here is my _editrole.cshtml
#model sample.Models.webpages_Roles
#{
ViewBag.Title = "Edit";
}
<h2>Edit</h2>
#using (Ajax.BeginForm("EditRole", "RolePrivilegeMapping", new AjaxOptions { HttpMethod = "POST" }))
{
#Html.ValidationSummary(true)
<fieldset>
<legend>webpages_Roles</legend>
#Html.HiddenFor(model => model.RoleId)
<div class="editor-label">
#Html.LabelFor(model => model.RoleName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.RoleName)
#Html.ValidationMessageFor(model => model.RoleName)
</div>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
}
Now while I click on edit link a jquery modal box gets displayed for editing details.I submit the changes asychronously as
#using (Ajax.BeginForm("EditRole", "RolePrivilegeMapping", new AjaxOptions { HttpMethod = "POST" }))
And the edit method is
public ActionResult EditRole(webpages_Roles webpages_roles)
{
if (ModelState.IsValid)
{
db.Entry(webpages_roles).State = EntityState.Modified;
db.SaveChanges();
}
return View("index");
}
My problem is
1. The dialog box is not getting closed. I have to manually click the cross
bar.
2. The Role partial view is not getting updated until I have to refresh the page.
I followed this link http://www.mindstick.com/Articles/279bc324-5be3-4156-a9e9-dd91c971d462/CRUD%20operation%20using%20Modal%20dialog%20in%20ASP%20NET%20MVC#.VVlyBLmqpHx

kendo sortable widget mvvm UI glitch

I am using kendo's mvvm and sortable widget to allow a user to sort multiple tables with data binded to it. I have implemented the following code. It works, but the data seems to be logging correctly to the console. However, the data in the UI jumps around.
$(".sortable-handlers").kendoSortable({
handler: ".move",
hint:function(element) {
return element.clone().addClass("sortable-hint");
},
change: function(e) {
var services = viewModel.get("services");
console.log(e.oldIndex);
var oldIndex = e.oldIndex;
var newIndex = e.newIndex;
services.splice(newIndex, 0, services.splice(oldIndex, 1)[0]);
//Set it back to the original list
viewModel.set("services", services);
console.log(JSON.stringify(viewModel.get("services")));
}
});
It's been a long time but adding .trigger("change") works for me (I'm using jquery ui sortable instead of kendo ui sortable).
// Define model with dependent method
var MyModel = kendo.data.Model.define({
fields: {
left: "number",
right: "number"
},
total: function() {
return this.get("left") + this.get("right");
}
});
// Create view model
var viewModel = kendo.observable({
items: []
});
// bindings
kendo.bind($("#myView"), viewModel);
// using $.ui.sortable when list changes
var timeout = null;
viewModel.items.bind("change", function(e) {
clearTimeout(timeout);
timeout = setTimeout(function() {
$("#sortable").sortable({
update: function(e, ui) {
// get UID of sorting target
var targetUid = ui.item.attr("uid");
// list before
var beforeIndexes = _.map(viewModel.items, _.iteratee("uid"));
// target's original index
var fromIdx = _.indexOf(beforeIndexes, targetUid);
// list after
var afterIndexes = $("#sortable").sortable("toArray", {
attribute: "uid"
});
// target's new index
var toIdx = _.indexOf(afterIndexes, targetUid);
var changeItem = viewModel.items[fromIdx];
viewModel.items.splice(fromIdx, 1);
if (toIdx >= viewModel.items.length) {
viewModel.items.push(changeItem);
} else {
viewModel.items.splice(toIdx, 0, changeItem);
}
// refresh
viewModel.items.trigger("change");
}
});
}, 500);
});
// add some items to list
viewModel.items.push(new MyModel({
left: 1,
right: 2
}));
viewModel.items.push(new MyModel({
left: 6,
right: 3
}));
viewModel.items.push(new MyModel({
left: 5,
right: 7
}));
<link href="https://code.jquery.com/ui/1.12.0-beta.1/themes/smoothness/jquery-ui.css" rel="stylesheet" />
<link href="https://kendo.cdn.telerik.com/2016.1.112/styles/kendo.common.min.css" rel="stylesheet" />
<link href="https://kendo.cdn.telerik.com/2016.1.112/styles/kendo.default.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.0-beta.1/jquery-ui.min.js"></script>
<script src="https://kendo.cdn.telerik.com/2016.1.112/js/kendo.all.min.js"></script>
<script src="http://underscorejs.org/underscore-min.js"></script>
<div id="myView">
<div class="k-grid k-widget">
<div class="k-grid-header">
<div class="k-grid-header-wrap">
<table>
<thead>
<tr>
<th class="k-header">SORTABLE</th>
</tr>
</thead>
</table>
</div>
</div>
<div class="k-grid-content">
<table>
<tbody id="sortable" data-bind="source: items" data-template="template-item">
</tbody>
</table>
</div>
</div>
<div class="k-grid k-widget">
<div class="k-grid-header">
<div class="k-grid-header-wrap">
<table>
<thead>
<tr>
<th class="k-header">NOT-SORTABLE</th>
</tr>
</thead>
</table>
</div>
</div>
<div class="k-grid-content">
<table>
<tbody id="sortable" data-bind="source: items" data-template="template-item">
</tbody>
</table>
</div>
</div>
</div>
<script type="text/x-kendo-template" id="template-item">
<tr data-bind="attr: {uid: uid}">
<td>
<span data-bind="text: left" />+
<span data-bind="text: right" />=
<span data-bind="text: total" />
</td>
</tr>
</script>

Button redirecting to the grid page

I have a custom module 'banner' and in which I have added a button in its second tab(only two tabs for the module). when click on that button, it is submitting my banner automatically and then go to the grid page(i e it acts as just another save button). But the function of this button is to add an uploading image field.ie whenever the button is clicked, it should add an image form field to my tab file. This is my tab file.
<?php
class Karaokeshop_Banner_Block_Adminhtml_Banner_Edit_Tab_Image extends Mage_Adminhtml_Block_Widget_Form
{
protected function _prepareForm()
{
$form = new Varien_Data_Form();
$this->setForm($form);
$fieldset = $form->addFieldset('banner_image', array('legend'=>Mage::helper('banner')->__('Banner Image')));
//declaring a new custom form field and adding
$fieldset->addType('add_button', 'Karaokeshop_Banner_Block_Adminhtml_Banner_Edit_Tab_Field_Custom');
$fieldset->addField('banner_img_add_button', 'add_button', array(
'title' => Mage::helper('banner')->__('Add Banner Image'),
'id' => 'add_banner_img_button',
'class' => 'scalable save',
'style' => '',
'onclick' => 'banner.add(this)',
'type' => 'button',
));
return parent::_prepareForm();
}
}
this is my button defining file
<?php
class Karaokeshop_Banner_Block_Adminhtml_Banner_Edit_Tab_Field_Custom extends Varien_Data_Form_Element_Abstract
{
public function __construct($attributes=array())
{
parent::__construct($attributes);
}
public function getElementHtml()
{
$value = $this->getTitle();
$onclick=$this->getOnclick();
$class=$this->getClass();
$id=$this->getId();
$style=$this->getStyle();
$type=$this->getType();
$html='<button id="'.$id.'" class="'.$class.'" style="'.$style.'" onclick="'.$onclick.'" type="'.$type.'" title="'.$value.'">'.$value.' </button>';
$html .= '<p id="' . $this->getHtmlId() . '"'. $this->serialize($this->getHtmlAttributes()) .'>
<script type="text/javascript">
//<![CDATA[
var banner =
{
add : function(obj)
{
},
};
//]]>
</script>
</p>';
return $html;
}
}
what should i do to change my button to an add button? what should I do to avoid this submitting functionality of the button. Please help me. Thanks in advance
First you need to call your phtml from block like this :
class My_Moudles_Block_Adminhtml_Image_Edit_Tab_Form extends Mage_Adminhtml_Block_Widget_Form
{
public function __construct()
{
parent::__construct();
$this->setTemplate('modules/imageupload.phtml');
$this->setFormAction(Mage::getUrl('*/*/imageupload'));
}
then create file in adminhtml/default/default/template/yourmodule/imageupload.phtml and put this code there.
<div class="entry-edit">
<div class="entry-edit-head">
<h4 class="icon-head head-edit-form fieldset-legend"><?php echo $this->__('General')?></h4>
<div class="form-buttons"></div>
</div>
<form id="imageform" method="post" action="<? echo $this->getFormAction(); ?>">
<div id="rules_form" class="fieldset ">
<div class="hor-scroll">
<table cellspacing="0" class="form-list">
<tbody>
<tr>
<td class="label"><?php echo $this->__('Add Image')?></td>
<td class="grid tier" colspan="10">
<table cellspacing="0" id="chain_tiers" class="chain border" style=" width:465px; ">
<thead>
<tr class="headings">
<th><?php echo $this->__('Image')?></th>
<th class="last"><?php echo $this->__('Action')?></th>
</tr>
<tr class="template no-display" id="email_chain_add_template">
<td class="nobr">
<input type="file" id="chain_Image" value="0" name="imageg" class="requried-entry input-text">
</td>
<td class="last"><input type="hidden" value="" disabled="no-template" class="delete" name="email_chain[__index__][delete]"><button onclick="emailsControl.deleteItem(event);return false" class="scalable delete icon-btn delete-product-option" title="Delete Image"><span><?php echo $this->__('Delete')?></span></button></td>
</tr>
</thead>
<tfoot>
<tr>
<td></td>
<td class="a-right" colspan="6">
<button style="" onclick="emailsControl.addItem()" class="scalable add" type="button" title="Add email" id="id"><span><span><span><?php echo $this->__('Add Image')?></span></span></span></button></td>
</tr>
</tfoot>
<tbody id="email_chain_container">
<tr>
<td class="nobr">
<input type="file" id="chain_Image" value="" name="Image[]" class="input-text">
</td>
<td class="last"><input type="hidden" value="" class="delete" name="email_chain[delete][]"><button onclick="emailsControl.deleteItem(event);return false" class="scalable delete icon-btn delete-product-option" title="Delete Image"><span><?php echo $this->__('Delete')?></span></button></td>
</tr>
</tbody>
</table>
<script type="text/javascript">
//<![Cchain[
var emailsControl = {
itemsCount : 0,
deleteButton : false,
addItem : function () {
var chain = {};
chain.TEMPLATE_ID = 0;
chain.index = this.itemsCount++;
if (arguments.length == 1) {
chain.TEMPLATE_ID = arguments[0];
}
var s = '<tr>' + $('email_chain_add_template').innerHTML.replace(/__index__/g, '#{index}').replace(/\sdisabled="?no-template"?/g, ' ').replace(/disabled/g, ' ').replace(/="'([^']*)'"/g, '="$1"') + '</tr>';
var template = new Template(s);
Element.insert($('email_chain_container'), {'bottom': template.evaluate(chain)});
$('chain_row_'+chain.index+'_TEMPLATE').value = chain.TEMPLATE_ID;
maxItemsCount++;
},
deleteItem : function(event) {
var tr = Event.findElement(event, 'tr');
if (tr) {
jQuery(tr).remove();
}
}
}
var maxItemsCount = 2;
//]]>
</script>
</td>
</tr>
</tbody>
</table>
</div></form>
</div>
</div>
Hopes this will solve your issue.
For edit you can do it like this :
<tbody id="email_chain_container">
<?php foreach($images as $row){ ?><tr>
<td class="nobr">
your image code
</td></tr>

Refresh datatable on Ajax success

I am using datatables and jquery dialog. Overall I have 3 forms and 3 datatables.
My script is working great but the thing I am struggling with is updating the correct datatable on success of ajax save (It doesn't even have to be the correct corresponding table, it could update all 3 tables on any of the 3 form saves.)
Any guidance would be greatly appreciated.
Page with buttons for showing datatable/forms in dialog
<div style="float:left;">
<button class="menubutton" id="view_academic">Academic</button>
<button class="menubutton" id="view_business">Business/Suppport</button>
<button class="menubutton" id="line_managers">Managers/Divisions</button>
<br/>
<br/>
</div>
<div style="float:right;">
Add Managers/Divisions
Add Academic
Add Business/Suppport
<br/>
<br/>
</div>
<div style="clear:both"></div>
<div id="academic_list">
<h2>Academic Entitlements</h2>
<table class="dataTable" id="academic_table" cellpadding="2" cellspacing="2" width="100%">
<thead>
<tr>
<th>Year</th>
<th>Employee</th>
<th>Division</th>
<th>Contract</th>
<th>Entitlement</th>
<th>Line Manager</th>
</tr>
</thead>
<tbody>
<tr>
<td colspan="4" class="dataTables_empty">Loading data from server</td>
</tr>
</tbody>
</table>
</div>
<div id="business_list" class="the_options" style="display:none;">
<h2>Business & Manual Entitlements</h2>
<table class="dataTable" id="business_table" cellpadding="2" cellspacing="2" width="100%">
<thead>
<tr>
<th>Year</th>
<th>Employee</th>
<th>FT/PT</th>
<th>Weekly Hours</th>
<th>Division</th>
<th>Commencement</th>
<th>Entitlement</th>
<th>Line Manager</th>
</tr>
</thead>
<tbody>
<tr>
<td colspan="4" class="dataTables_empty">Loading data from server</td>
</tr>
</tbody>
</table>
</div>
</div>
<div id="line_managers_list" class="the_options" style="display:none;">
<h2>Line Managers & Divisions</h2>
<table class="dataTable" id="line_managers_table" cellpadding="2" cellspacing="2" width="100%">
<thead>
<tr>
<th>Division</th>
<th>Name</th>
<th>Line Manager</th>
</tr>
</thead>
<tbody>
<tr>
<td colspan="4" class="dataTables_empty">Loading data from server</td>
</tr>
</tbody>
</table>
</div>
initialise Datatables
$(function() {
// Implements the dataTables plugin on the HTML table
var $acTable= $("#academic_table").dataTable( {
"oLanguage": {
"sSearch": "Filter:"
},
"bProcessing": true,
"bServerSide": true,
"sAjaxSource": "scripts/academic_serverside.php",
"iDisplayLength": 10,
"bJQueryUI": false,
"sPaginationType": "scrolling",
"sDom": '<"top"iflp<"clear">>rt>',
"sScrollX": "100%",
"sScrollXInner": "100%",
"bScrollCollapse": true
});
});
$(function() {
// Implements the dataTables plugin on the HTML table
var $buTable= $("#business_table").dataTable( {
"oLanguage": {
"sSearch": "Filter:"
},
"bProcessing": true,
"bServerSide": true,
"sAjaxSource": "scripts/business_serverside.php",
"iDisplayLength": 10,
"bJQueryUI": false,
"sPaginationType": "scrolling",
"sDom": '<"top"iflp<"clear">>rt>',
"sScrollX": "100%",
"sScrollXInner": "100%",
"bScrollCollapse": true
});
});
$(function() {
// Implements the dataTables plugin on the HTML table
var $lmTable= $("#line_managers_table").dataTable( {
"oLanguage": {
"sSearch": "Filter:"
},
"bProcessing": true,
"bServerSide": true,
"sAjaxSource": "scripts/line_managers_serverside.php",
"iDisplayLength": 10,
"bJQueryUI": false,
"sPaginationType": "scrolling",
"sDom": '<"top"iflp<"clear">>rt>'
});
});
$(document).ready(function() {
$(".the_options").hide();
});
Dialogs/datatables show/hide/open/close and AJAX save form:
$(document).ready(dialogForms);
function dialogForms() {
$('a.menubutton').click(function() {
var a = $(this);
$.get(a.attr('href'),function(resp){
var dialog = $('<div>').attr('id','formDialog').html($(resp).find('form:first').parent('div').html());
$('body').append(dialog);
dialog.find(':submit').hide();
dialog.dialog({
title: a.attr('title') ? a.attr('title') : '',
modal: true,
buttons: {
'Save': function() {
submitFormWithAjax($(this).find('form'));
$(this).dialog('close');
$lmTable.fnDraw('');
},
'Cancel': function() {$(this).dialog('close');}
},
close: function() {$(this).remove();},
width: 600,
height: 500
});
}, 'html');
return false;
});
}
function submitFormWithAjax(form) {
form = $(form);
$.ajax({
url: form.attr('action'),
data: form.serialize(),
type: (form.attr('method')),
dataType: 'script',
success: function(data){
$(this).dialog('close');
$lmTable.fnDraw('');
}
});
return false;
}
$(function() {
$("#add_academic")
.button()
.click(function() {
$("#academic-form").dialog( "open" );
});
$("#add_line_managers")
.button()
.click(function() {
$("#line-managers-form").dialog( "open" );
});
$("#add_business")
.button()
.click(function() {
$("#business-form").dialog( "open" );
});
$("#view_academic")
.button()
.click(function() {
$('#academic_list').show();
$('#business_list').hide();
$('#line_managers_list').hide();
});
$("#view_business")
.button()
.click(function() {
$('#academic_list').hide();
$('#business_list').show();
$('#line_managers_list').hide();
});
$("#line_managers")
.button()
.click(function() {
$('#academic_list').hide();
$('#business_list').hide();
$('#line_managers_list').show();
});
});
To update a table simply call fnDraw() on it. Since you are not using global variables, you must retrieve the table first
var $lmTable = $("#line_managers_table").dataTable( { bRetrieve : true } );
$lmTable.fnDraw();
EDIT - to show only the right table you could do something like:
function dialogForms() {
$('a.menubutton').click(function() {
var id = this.id;// Save the id of the clicked button
var a = $(this);
$.get(a.attr('href'),function(resp){
var dialog = $('<div>').attr('id','formDialog').html($(resp).find('form:first').parent('div').html());
$('body').append(dialog);
dialog.find(':submit').hide();
dialog.dialog({
title: a.attr('title') ? a.attr('title') : '',
modal: true,
buttons: {
'Save': function() {
submitFormWithAjax($(this).find('form'), id);// Pass the id to the function
function submitFormWithAjax(form, id) {
form = $(form);
var table_id;
// Choose the table to display depending on the id, i made some guesses but adjust this
switch(id){
case 'view_academic': table_id = '#academic_table';
break;
case 'view_business': table_id = '#business_table';
break;
case 'line_managers': table_id = '#line_managers_list';
break;
}
$.ajax({
url: form.attr('action'),
data: form.serialize(),
type: (form.attr('method')),
dataType: 'script',
success: function(data){
$(this).dialog('close');
// Refresh table
var oTableToUpdate = $(table_id).dataTable( { bRetrieve : true } );
$oTableToUpdate .fnDraw();
// Hide all tables
$('table').hide();
// Show the refreshed
$(table_id).show();
}
});
return false;
}