PHP Datatable currency sorting - php

I got problem with my data table sorting in the currency tab. when i try to sort the currency/price column..
Ex
A - $ 10,0000
B - $ 4,000
C - $ 8,000
In Chrome:
it works fine it displays the correct answer. which is BCA Ascending Order.
In Mozilla and IE:
it doesn't display the correct answer instead it will display this answer ACB Ascending order. I believe it reads the second lowest number since moz and iE reads the $ sign as a part of the string.
Any solution for this?
you may try this sample link that I found
open it in Chrome and Mozilla

I just solve my problem.
Instead of creating a extended .js file for the currency plugin which causes error.. I write code together with the creating the datatable object. something like this:
$(document).ready(function(){
model_select();
$('.data_table').dataTable({
"bJQueryUI": true,
"sPaginationType": "full_numbers",
"bRetrieve":true,
"aoColumnDefs": [
{ "sType": "currency", "aTargets": [ 10 ] }
]
});
// Change this list to the valid characters you want
var validChars = "$£€c0123456789-,";
// Init the regex just once for speed - it is "closure locked"
var str = jQuery.fn.dataTableExt.oApi._fnEscapeRegex("$£€c0123456789-,");
var re = new RegExp('[^'+str+']');
jQuery.fn.dataTableExt.aTypes.unshift(
function ( data )
{
if ( typeof data !== 'string' || re.test(data) ) {
return null;
}
return 'currency';
}
);
});

Related

Owl Carousel Current Slide and Number of Slides WITH loop option (php)

So I've looked at a few questions so far, and none of these I've seen have really helped me get to my solution.
I need to get a counter on my slider that's using Owl Carousel. I need to get a current slide count and the number of items in the slider.
The thing is, that I am telling the slider to loop back to the beginning when it hits the last slide.
Some of the code examples I've looked at work, except for one thing. It seems Owl Carousel adds 2 items at the beginning and 2 items at the end, with the class cloned appended to them. That messes with the code counts I've been using.
I've tried to isolate the cloned count and that works, but the currentIndex is where I am falling into problems. Trying to get that count to be accurate isn't working. If I have say 4 slides, currentIndex starts at 3 and goes up to 8 while totalItems shows 4.
Any help is appreciated!
I am using OwlCarousel 2
Here is the code I am using:
var = mapSliderOptions = {
loop: true,
margin: 0,
items: 1,
autoWidth: false,
mouseDrag: true,
touchDrag: true,
dots: false,
onInitialized : counter, //When the plugin has initialized.
onTranslated : counter,
responsive: {
0: {
autoplay: true,
autoplayTimeout: 5000,
autoplayHoverPause: true
},
768: {
autoplay: false,
items: 1
}
}
},
function counter(event) {
var totalItems = $('.owl-item:not(.cloned)' ).length;
var currentIndex = $('div.active').index() + 1 ;
$('#counter').html("item "+ currentIndex +" of " + totalItems);
}
$('.map-hero-slider').owlCarousel( mapSliderOptions );
I have found this solution online which works great
https://codepen.io/maer2k/pen/qPVWEd
I broke it down to a more understandable code.
var gallery = $('.owl-carousel');
gallery.owlCarousel({
items: 1,
loop: true,
onInitialized: counter,
onChanged: counter,
});
function counter(event) {
if (!event.namespace) {
return;
}
var slides = event.relatedTarget;
$('.slider-counter').text(slides.relative(slides.current()) + 1 + '/' + slides.items().length);
}
It does what it promises. But i have no idea of what event.relatedTarget and .relative() actually do, it's the first time i see them implemented. Also the namespace related if statement isn't really required for it to work.
It doesnt look like it's owl-carousel base code. Would love if someone tryed to explain to me how this magic works :D
So this answer is for those who are using php and running a foreach loop.
What I did was I set the data-dot with the incremental number. I then took a count of the number of items in the array, and passed that through as the final count of items.
Then calling to the container and with some position absolute for the CSS, I was able to "trick" the front end viewer into the count in a sense.
Not very effective, but it works for me.

jQuery Datatables Ultimate Date/Time Sorting Plugin

We are using the Datatables ultimate date/time sorting plugin (https://datatables.net/blog/2014-12-18) to try and sort date columns, but not having any luck getting it to properly sort dates in the right format. When the page loads, the following script is run:
//sets the date format for datatables for sorting purposes
//reference: https://datatables.net/blog/2014-12-18
$.fn.dataTable.moment( 'M/D/YYYY' );
/* Datatables */
$('.datatable').DataTable({
language : {
search : "_INPUT_",
searchPlaceholder : "Search...",
paginate : {
"next" : '<i class="fa fa-chevron-right"></i>',
"previous" : '<i class="fa fa-chevron-left"></i>'
}
},
responsive : {
details : {
display : $.fn.dataTable.Responsive.display.childRowImmediate,
type : 'column'
}
},
order : [0, 'desc'],
//date sorting
columnDefs:
{
targets: 'date_sortable',
render: function ( data, type, full, meta ) {
if(type === 'display'){
if(data){
var mDate = moment(data);
data = (mDate && mDate.isValid()) ? mDate.format("M/D/YYYY") : "";
console.log('rewrote data to ' + data);
}
}
console.log('date_sortable rendered');
return data;
}
}
});
According to both the Datatables documentation and the details I found on this SO post (DataTables Ultimate date / time sorting plug-in not working with Intl formats), I added date_sortable as a class name on the <th /> element in my HTML, but it looks like the render function isn't called, as my console.log[...] entries never run. I can see in the generated HTML the class is on my <th /> element, and the dates being shown are in the proper format ('n/j/Y', in PHP) so I'm at a total loss.
Everything looks setup correctly, so any tips/pointers here? The date ordering seems to be rather random in nature, with entries that have dates such as 1/6/2016 showing up in the middle (see screenshot), which makes no sense at all.
I will say this table is showing ~2,055 records so is it possibly a performance thing? This isn't currently loading with API calls, so all records are in the generated HTML as a single file.
can you look at the unshifted Function in Datatables?
// Add type detection
types.detect.unshift( function ( d ) {
return moment( d, format, locale, true ).isValid() ?
'moment-'+format :
null;
} );
if it's the case, you should use this:
$.fn.dataTable.moment('YYYY-M-D');
Please try this fiddle (this works with your date format):
`http://jsfiddle.net/Marouen/9qdj53am`
Hope this will help.

How to preload <options> and <select> with Jquery-option-tree plugin

I am using Jquery-option-tree plugin on a standalone website not based on Wordpress as in example 7 on the demo page, except that I am not passing a .txt file but a PHP page is generating the array of < options > to be passed to the plugin.
http://kotowicz.net/jquery-option-tree/demo/demo.html
This perfectly works: so let's say that the user wants to select a category for a new product, the plugin suits the purpose generating a nice: " Food -> fruit -> apples " upon user clicks. (see demo page ex. 7)
What instead if a product already exists with its categories assigned? I want to show it to the user when he edit that product, preloading the tree.
I have the ids path coming from database, so it would just be a matter of having the plugin to run without the user interact, using the value I pass. I saw this question: jQuery simulate click event on select option
and tried to simulate user' click with this (and other) methods with no luck.
$('#select')
.val(value)
.trigger('click');
Here the call to the function:
$(function() {
var options = {
empty_value: '',
set_value_on: 'each',
indexed: true, // the data in tree is indexed by values (ids), not by labels
on_each_change: '/js/jquery-option-tree/get-subtree.php', // this file will be called with 'id' parameter, JSON data must be returned
choose: function(level) {
return 'Choose level ' + level;
},
loading_image: '/js/jquery-option-tree/ajax-load.gif',
show_multiple: 10, // if true - will set the size to show all options
choose: ''
};
$.getJSON('/js/jquery-option-tree/get-subtree.php', function(tree) { // initialize the tree by loading the file first
$('input[name=parent_category_id]').optionTree(tree, options);
});
});
Here you can see the plugin:
https://code.google.com/p/jquery-option-tree/
I don't know that plugin, but looking at the examples there seems to be one that fits your need; Example 6 - AJAX lazy loading & setting value on each level change.
This would, in theory, just require some config options:
preselect: {'demo6': ['220','226']}, // array of default values - if on any level option value will be in this list, it will be selected
preselect_only_once: true, // prevent auto selecting whole branch when user maniputales one of branch levels
get_parent_value_if_empty: true,
attr: "id" // we'll use input id instead of name
If this doesn't fit you need though, you could initiate it from an event, like change, keyup, etc.
$(document).on('change', '#select', function() {
$('#nextSelect').val($(this).val());
})
$(document).on('change', '#nextSelect', function() {
$('#finalInput').val($(this).val());
})
Yes, you are right Mackan ! I saw that "preselect" option but I was initially unable to use it transferring the path from database to javascript, I ended up with my "newbie" solution to match the syntax:
preselect: {'parent_category_id': [0,'2','22']},
PHP
$category_path comes from DB query and is like "0,2,76,140,"
$path = explode(',', $category_path);
$preselect="";
foreach ($path as $value) {
$int = (int)$value;
if ($int != 0) $preselect.= "'". $int ."',";
else $preselect.= $int.","; // have to do this as ZERO in my case has to be without apostrophes ''
}
$preselect = "{'parent_category_id':[".$preselect."]}"
JS
var presel= <?php echo($preselect); ?>;
var options = {
preselect: (presel),
}
Any suggestion for a better code ?
Thanks a lot !!

Loading encoded JSON into Dojo Grid

I am programming in php,
I want to take an array I have (which is extracted from mysql result set), convert it to JSON and then use it in dojox.grid.DataGrid.
I got an idea from this link:
I used the following on the array (in a file called getJSON.php)
echo $ajax = "{identifier: 'db_id', 'items':".json_encode($array)."}";
Then I try doing this (in my main page):
var store = new dojo.data.ItemFileWriteStore({ url: 'getJSON.php' });
Everything else is exactly as the Dojo documentation specifies.
The grid shows up, but doesn't load the data and instead writes Sorry, an error occurred
Does anyone know the reason? Hopefully I gave you enough to go on.
i don't use ItemFileWriteStore for that ! They changed a lot since Dojo 1.6 , so maybe you looked at something not up to date.
Try this code:
// Load the neccessary components (This is dojo with AMD ) !
require(["dojo/aspect",'dojo/_base/lang', 'dojox/grid/DataGrid'
,'dojo/dom' , 'dojo/store/JsonRest','dojo/data/ObjectStore',
'dojo/domReady!'],
function(aspect,lang, DataGrid, dom,JsonRest,ObjectStore){ // Map components to vars...
var store = new JsonRest({
target: "getJSON.php" // Use a URL that you can open up in a browser.
});
/*layout for the grid, you will have to adapt this to your columns !!!*/
var layout = [[
{'name': 'Filename', 'field': 'documentName', 'width': '300px'},
{'name': 'Size', 'field': 'fileSize', 'width': '100px'},
{'name': 'Id', 'field': 'id', 'width': '200px'}
]];
dataStore=ObjectStore({objectStore: store}); // Transform to Objectstore !
/*Now we create a new grid*/
var grid = new DataGrid({
id: 'grid',
store:dataStore, // Connect the store
autoWidth:false,
structure: layout, // Connect the layout
rowSelector: '0px'});
grid.placeAt("yourTargetDivId"); // Has to be an existing DOM Element with id !
grid.startup(); // START IT !
});
Please try this code by echoing something simple like this first:
echo '[{"id":"1","fileSize":"100kb","documentName":"Lucian !"},
{"id":"2","fileSize":"900kb","documentName":"Pew Pew !"}]';
And after that with your own JSON...

how to add custom columns to dataTables with server-side processing?

i have made this example work on my page http://datatables.net/examples/server_side/server_side.html, (using php5, jquery+ui and dataTables.net)
i would like to be able to add a Modify and Delete link on each row, how can i do that without sending two extra columns with the links from the server?
also how can i substitute the ids the rows have in the database and that are sent by the server with nice number starting from 1 till iTotalDisplayRecords...
thank you
found how
var controller_name = '<?php echo Zend_Controller_Front::getInstance()->getRequest()->getControllerName();?>';
"fnDrawCallback": function ( oSettings ) {
/* Need to redo the counters if filtered or sorted */
for ( var i=0, iLen=oSettings.aiDisplay.length ; i<iLen ; i++ )
{
var link = $(' Modifica Cancella');
$('td:eq(0)', oSettings.aoData[ oSettings.aiDisplay[i] ].nTr ).html( i+1 );
$('td:eq(0)', oSettings.aoData[ oSettings.aiDisplay[i] ].nTr ).append(link);
}
},

Categories