Giter Site home page Giter Site logo

datatable's Introduction

Datatable

Important

This package will not receive any new updates! You can still use this package, but be preparared that there is no active development for this project.

This package is abandoned and not recommended for new projects. We recommend to use instead Yajra's Package which offers a nearly-similar API.

Introduction

This is a Laravel 4 package for the server and client side of datatables at http://datatables.net/

A Laravel 5 package is close to being completed. To install it:

    composer require chumper/datatable "dev-develop"

If you find any issues, please report them in the bug tracker!

Please Note, if you want Datatable 1.10 support & Laravel 5 support, try out our newest branch!

If you upgrade from version 2.1.* or below please make sure you adjust your app.php with the new alias:

    // aliases array:

    //old
    //'Datatable' => 'Chumper\Datatable\Facades\Datatable',

    //new
    'Datatable' => 'Chumper\Datatable\Facades\DatatableFacade',

Known Issues

  • none i know of so far

TODO

  • fix incoming bugs
  • code documentaion

Features

This package supports:

  • Support for Collections and Query Builder
  • Easy to add and order columns
  • Includes a simple helper for the HTML side
  • Use your own functions and presenters in your columns
  • Search in your custom defined columns ( Collection only!!! )
  • Define your specific fields for searching and ordering
  • Add custom javascript values for the table
  • Tested! (Ok, maybe not fully, but I did my best :) )

Please note!

There are some differences between the collection part and the query part of this package. The differences are:

Difference Collection Query
Speed - +
Custom fields + +
Search in custom fields + -
Order by custom fields + -
Search outside the shown data (e.g.) database - +

For a detailed explanation please see the video below. http://www.youtube.com/watch?v=c9fao_5Jo3Y

Please let me know any issues or features you want to have in the issues section. I would be really thankful if you can provide a test that points to the issue.

Installation

This package is available on http://packagist.org, just add it to your composer.json

"chumper/datatable": "2.*"

Alternatively, you can install it using the composer command:

    composer require chumper/datatable "2.*"

It also has a ServiceProvider for usage in Laravel4. Add these lines to app.php:

    // providers array:
	'Chumper\Datatable\DatatableServiceProvider',

    // aliases array:
    'Datatable' => 'Chumper\Datatable\Facades\DatatableFacade',

You can then access it under the Datatable alias.

To override the default configuration options you can publish the config file.

php artisan config:publish chumper/datatable

You may now edit these options at app/config/packages/chumper/datatable/config.php.

Basic Usage

There are two ways you can use the plugin, within one route or within two routes:

Two routes

  • Create two routes: One to deliver the view to the user, the other for datatable data, eg:
    Route::resource('users', 'UsersController');
    Route::get('api/users', array('as'=>'api.users', 'uses'=>'UsersController@getDatatable'));
  • Your main route will deliver a view to the user. This view should include references to your local copy of datatables. In the example below, files were copied from the datatables/media directories and written to public/assets. Please note that the scripts must be located above the call to Datatable:
    <link rel="stylesheet" type="text/css" href="/assets/css/jquery.dataTables.css">
    <script type="text/javascript" src="/assets/js/jquery.js"></script>
    <script type="text/javascript" src="/assets/js/jquery.dataTables.min.js"></script>

    {{ Datatable::table()
    ->addColumn('id','Name')       // these are the column headings to be shown
    ->setUrl(route('api.users'))   // this is the route where data will be retrieved
    ->render() }}
  • Create a controller function to return your data in a way that can be read by Datatables:
    public function getDatatable()
    {
        return Datatable::collection(User::all(array('id','name')))
        ->showColumns('id', 'name')
        ->searchColumns('name')
        ->orderColumns('id','name')
        ->make();
    }

You should now have a working datatable on your page.

One route

In your route you should use the Datatable::shouldHandle method which will check whether the plugin should handle the request or not.

    if(Datatable::shouldHandle())
    {
        return Datatable::collection(User::all(array('id','name')))
            ->showColumns('id', 'name')
            ->searchColumns('name')
            ->orderColumns('id','name')
            ->make();
    }

The plugin will then query the same url for information. The shouldHandle method just checks for an ajax request and if sEcho is set.

HTML Example

	Datatable::table()
    ->addColumn('id',Lang::get('user.lastname'))
	->setUrl(URL::to('auth/users/table'))
    ->render();

With seperate table and script:

		$table = Datatable::table()
        ->addColumn('Email2','Email', "Test")
        ->noScript();

        // to render the table:
        $table->render()

        // later in the view you can render the javascript:
        $table->script();

This will generate a HTML table with two columns (id, lastname -> your translation) and will set the URL for the ajax request.

Note: This package will NOT include the datatable.js, that is your work to do. The reason is that for example i use Basset and everybody wants to do it their way...

If you want to provide your own template for the table just provide the path to the view in laravel style.

	Datatable::table()
        ->addColumn('id',Lang::get('user.lastname'))
    	->setUrl(URL::to('auth/users/table'))
        ->render('views.templates.datatable');

Server Example

	Datatable::collection(User::all())
    ->showColumns('id')
    ->addColumn('name',function($model)
        {
            return $model->getPresenter()->yourProperty;
        }
    )->make();

This will generate a server side datatable handler from the collection User::all(). It will add the id column to the result and also a custom column called name. Please note that we need to pass a function as a second parameter, it will always be called with the object the collection holds. In this case it would be the User model.

You could now also access all relationship, so it would be easy for a book model to show the author relationship.

	Datatable::collection(User::all())
    ->showColumns('id')
    ->addColumn('name',function($model)
        {
            return $model->author->name;
        }
    )->make();

Note: If you pass a collection of arrays to the collection method you will have an array in the function, not a model.

The order of the columns is always defined by the user and will be the same order the user adds the columns to the Datatable.

Query or Collection?

There is a difference between query() and collection(). A collection will be compiled before any operation - like search or order - will be performed so that it can also include your custom fields. This said the collection method is not as performing as the query method where the search and order will be tackled before we query the database.

So if you have a lot of Entries (100k+) a collection will not perform well because we need to compile the whole amount of entries to provide accurate sets. A query on the other side is not able to perform a search or orderBy correctly on your custom field functions.

TLTR: If you have no custom fields, then use query() it will be much faster If you have custom fields but don't want to provide search and/or order on the fields use query(). Collection is the choice if you have data from somewhere else, just wrap it into a collection and you are good to go. If you have custom fields and want to provide search and/or order on these, you need to use a collection.

Please also note that there is a significant difference betweeen the search and order functionality if you use query compared to collections. Please see the following video for more details.

http://www.youtube.com/watch?v=c9fao_5Jo3Y

Available functions

This package is separated into two smaller parts:

  1. Datatable::table()
  2. Datatable::collection()
  3. Datatable::query()

The second and third one is for the server side, the first one is a helper to generate the needed table and javascript calls.

Collection & Query

collection($collection)

Will set the internal engine to the collection. For further performance improvement you can limit the number of columns and rows, i.e.:

$users = User::activeOnly()->get('id','name');
Datatable::collection($users)->...

query($query)

This will set the internal engine to a Eloquent query... E.g.:

$users = DB::table('users');
Datatable::query($users)->...

The query engine is much faster than the collection engine but also lacks some functionality, for further information look at the table above.

showColumns(...$columns)

This will add the named columns to the result.

Note: You need to pass the name in the format you would access it on the model or array. example: in the db: last_name, on the model lastname -> showColumns('lastname')

You can provide as many names as you like

searchColumns(..$fields)

Will enable the table to allow search only in the given columns. Please note that a collection behaves different to a builder object.

Note: If you want to search on number columns with the query engine, then you can also pass a search column like this

   //mysql
   ->searchColumns(array('id:char:255', 'first_name', 'last_name', 'address', 'email', 'age:char:255'))

   //postgree
   ->searchColumns(array('id:text', 'first_name', 'last_name', 'address', 'email', 'age:text'))

This will cast the columns int the given types when searching on this columns

orderColumns(..$fields)

Will enable the table to allow ordering only in the given columns. Please note that a collection behaves different to a builder object.

addColumn($name, $function)

Will add a custom field to the result set, in the function you will get the whole model or array for that row E.g.:

	Datatable::collection(User::all())
    ->addColumn('name',function($model)
        {
            return $model->author->name;
        }
    )->make();

You can also just add a predefined Column, like a DateColumn, a FunctionColumn, or a TextColumn E.g.:

	$column = new \Chumper\Datatable\Columns\TextColumn('foo', 'bar'); // Will always return the text bar
	//$column = new \Chumper\Datatable\Columns\FunctionColumn('foo', function($model){return $model->bar}); // Will return the bar column
	//$column = new \Chumper\Datatable\Columns\DateColumn('foo', DateColumn::TIME); // Will return the foo date object as toTimeString() representation
	//$column = new \Chumper\Datatable\Columns\DateColumn('foo', DateColumn::CUSTOM, 'd.M.Y H:m:i'); // Will return the foo date object as custom representation

	Datatable::collection(User::all())
    ->addColumn($column)
    ->make();

You can also overwrite the results returned by the QueryMethod by using addColumn in combination with showColumns. You must name the column exactly like the database column that you're displaying using showColumns in order for this to work.

	$column = new \Chumper\Datatable\Columns\FunctionColumn('foo', function ($row) { return strtolower($row->foo); }
	Datatable::query(DB::table('table')->select(array('foo')))
	         ->showColumns('foo')
	         ->addColumn($column)
	         ->orderColumns('foo')
	         ->searchColumns('foo')
	         ->make()

This will allow you to have sortable and searchable columns using the QueryEngine while also allowing you to modify the return value of that database column entry.

Eg: linking an user_id column to it's page listing

	$column = new \Chumper\Datatable\Columns\FunctionColumn('user_id', function ($row) { return link_to('users/'.$row->user_id, $row->username) }
	Datatable::query(DB::table('table')->select(array('user_id', 'username')))
	         ->showColumns('user_id')
	         ->addColumn($column)
	         ->orderColumns('user_id')
	         ->searchColumns('user_id')

Please look into the specific Columns for further information.

setAliasMapping()

Will advise the Datatable to return the data mapped with the column name. So instead of

	{
		"aaData":[
			[3,"name","2014-02-02 23:28:14"]
		],
		"sEcho":9,
		"iTotalRecords":2,
		"iTotalDisplayRecords":1
	}

you will get something like this as response

{
	"aaData":[
		{"id":2,"name":"Datatable","created_at":"Sun, Feb 2, 2014 7:17 PM"}
	],
	"sEcho":2,
	"iTotalRecords":2,
	"iTotalDisplayRecords":1
}

make()

This will handle the input data of the request and provides the result set.

Without this command no response will be returned.

clearColumns()

This will reset all columns, mainly used for testing and debugging, not really useful for you.

If you don't provide any column with showColumn or addColumn then no column will be shown. The columns in the query or collection do not have any influence which column will be shown.

getOrder()

This will return an array with the columns that will be shown, mainly used for testing and debugging, not really useful for you.

getColumn($name)

Will get a column by its name, mainly used for testing and debugging, not really useful for you.

Specific QueryEngine methods

setSearchWithAlias()

If you want to use an alias column on the query engine and you don't get the correct results back while searching then you should try this flag. E.g.:

		Datatable::from(DB::table("users")->select(array('firstname', "users.email as email2"))->join('partners','users.partner_id','=','partners.id'))
        ->showColumns('firstname','email2')
        ->setSearchWithAlias()
        ->searchColumns("email2")

In SQL it is not allowed to have an alias in the where part (used for searching) and therefore the results will not counted correctly.

With this flag you enable aliases in the search part (email2 in searchColumns).

Please be aware that this flag will slow down your application, since we are getting the results back twice to count them manually.

setDistinctCountGroup($value = true)

If you are using GROUP BY's inside the query that you are passing into the Datatable, then you may receive incorrect totals from your SQL engine. Setting setDistinctCountGroup (which most likely only works on MySQL) will ensure that the totals are based on your GROUP BY.

setSearchOperator($value = "LIKE")

With this method you can set the operator on searches like "ILIKE" on PostgreSQL for case insensitivity.

setExactWordSearch

Will advice the engines only to search for the exact given search string.

Specific CollectionEngine methods

setSearchStrip() & setOrderStrip()

If you use the search functionality then you can advice all columns to strip any HTML and PHP tags before searching this column.

This can be useful if you return a link to the model detail but still want to provide search ability in this column.

setCaseSensitive($boolean = 'false')

Set the search method to case sensitive or not, default is false

Table

noScript()

With setting this property the Table will not render the javascript part.

You can render it manually with

script($view = null)

Will render the javascript if no view is given or the default one and will pass the class name, the options and the callbacks.

Example:

		$table = Datatable::table()
        ->addColumn('Email2','Email', "Test")
        ->noScript();

        // to render the table:
        $table->render()

        // later in the view you can render the javascript:
        $table->script();

setUrl($url)

Will set the URL and options for fetching the content via ajax.

setOptions($name, $value) OR setOptions($array)

Will set a single option or an array of options for the jquery call.

You can pass as paramater something like this ('MyOption', 'ValueMyOption') or an Array with parameters, but some values in DataTable is a JSON so how can i pass a JSON in values? Use another array, like that: setOptions(array("MyOption"=> array('MyAnotherOption'=> 'MyAnotherValue', 'MyAnotherOption2'=> 'MyAnotherValue2')));

//GENERATE

jQuery(.Myclass).DataTable({
    MyOption: {
        MyAnotherOption: MyAnotherValue,
        MyAnotherOption2: MyAnotherValue2,
    }
});

As a sugestion, take a look at this 2 files javascript.blade.php && template.blade.php in vendor/Chumper/datatable/src/views. You'll understand all the logic and see why it's important to pass the parameter like an array (json_encode and others stuffs).

setCallbacks($name, $value) OR setCallbacks($array)

Will set a single callback function or an array of callbacks for the jquery call. DataTables callback functions are described at https://datatables.net/usage/callbacks. For example,

    ->setCallbacks(
        'fnServerParams', 'function ( aoData ) {
            aoData.push( { "name": "more_data", "value": "my_value" } );
        }'
    )

addColumn($name)

Will add a column to the table, where the name will be rendered on the table head. So you can provide the string that should be shown.

if you want to use the alias mapping feature of the server side table then you need to add an array like this

Datatable::table()
    ->addColumn(array(
        'id'            => 'ID',
        'name'          => 'Name',
        'created_at'    => 'Erstellt'
        ))
	->render();

Please note that passing an assosiative array to the addColumn function will automatically enable the alias function on the table

setAliasMapping(boolean)

Here you can explicitly set if the table should be aliased or not.

countColumns()

This will return the number of columns that will be rendered later. Mainly for testing and debugging.

getData()

Will return the data that will be rendered into the table as an array.

getOptions()

Get all options as an array.

render($view = template.blade)

Renders the table. You can customize this by passing a view name. Please see the template inside the package for further information of how the data is passed to the view.

setData($data)

Expects an array of arrays and will render this data when the table is shown.

setCustomValues($name, $value) OR setCustomValues($array)

Will set a single custom value, or an array of custom values, which will be passed to the view. You can access these values in your custom view file. For example, if you wanted to click anywhere on a row to go to a record (where the record id is in the first column of the table):

In the calling view:

{{ DataTable::table()
    ->addColumn($columns)
    ->setUrl($ajaxRouteToTableData)
    ->setCustomValues('table-url', $pathToTableDataLinks)
    ->render('my.datatable.template') }}

In the datatable view (eg, 'my.datatable.template'):

    @if (isset($values['table-url']))
        $('.{{$class}}').hover(function() {
            $(this).css('cursor', 'pointer');
        });
        $('.{{$class}}').on('click', 'tbody tr', function(e) {
            $id = e.currentTarget.children[0].innerHTML;
            $url = e.currentTarget.baseURI;
            document.location.href = "{{ $values['table-url'] }}/" + $id;
        });
    @endif

setOrder(array $order)

Defines the order that a datatable will be ordered by on first page load.

{{ DataTable::table()
    ->addColumn('ID', 'First Name', 'Last Name')
    ->setUrl($ajaxRouteToTableData)
    ->setOrder(array(2=>'asc', 1=>'asc')) // sort by last name then first name
    ->render('my.datatable.template') }}

Extras

Some extras features, using the Datatables api.

TableTools

To use TableTools you will need to add some files in your project (https://datatables.net/extensions/tabletools/), if you want some help download the datatable's package and inside the extension folder go to /tabletools and study the examples. After, all the files include, don't forget to pass the parameters like this:

//In view:

{{
    Datatable::table()
        ->addColumn('your columns here separated by comma')
        ->setUrl('your URL for server side')
        ->setOptions(
            array(
                'dom' =>"T<'clear'>lfrtip",
                'tableTools' => array(
                    "sSwfPath" => "your/path/to/swf/copy_csv_cls_pdf.swf",
                    "aButtons" => array("copy", "pdf", "xls")
                )
            )
        )
}}

If you want to get some properties like "which row did i click?", see the javascript.blade.php and the variable $values.

Contributors

  • jgoux for helping with searching on number columns in the database
  • jijoel for helping with callback options and documentation

Changelog

  • 2.0.0:
    • Seperated Query and Collection Engine
    • Added single column search
    • Code cleanup

Applications

https://github.com/hillelcoren/invoice-ninja (by Hillel Coren)

License

This package is licensed under the MIT License

datatable's People

Contributors

akaroot avatar alegalviz avatar aron-bordin avatar bruno-de-l-escaille avatar bryant1410 avatar c4pone avatar chumper avatar coolgoose avatar dlnsk avatar felipepastor avatar gcummins avatar jijoel avatar mgufrone avatar mmestrovic avatar mpaleo avatar mrsimonbennett avatar nbourguig avatar niklasdevries avatar peaceman avatar psychonetic avatar saaiful avatar sburkett avatar thienhung1989 avatar timgws avatar yaapis avatar yfktn avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

datatable's Issues

Cannot access protected property

Hi Chumper,

After comoser update I get the error below:
(I'm on PHP 5.3)

{"error":{"type":"Symfony\Component\Debug\Exception\FatalErrorException","message":"Cannot access protected property Chumper\Datatable\Engines\CollectionEngine::$rowClass","file":"C:\Users\Pieter\Documents\My Dropbox\Websites\www\laravel.dev\datatables2\vendor\chumper\datatable\src\Chumper\Datatable\Engines\CollectionEngine.php","line":234}}

Fix for setSearchOperator

Hi Chumper,
I think you forgot to return the instance of the QueryEngine class in the setSearchOperator method so it breaks method chaining.

    public function setSearchOperator($value = "LIKE")
    {
        $this->options['searchOperator'] = $value;
        return $this;
    }

Keep up the good work. :)

leftJoins mutilated

Hi yo.

leftJoins seem to get messed about in PHP 5.5. Something in the count() method is messing with the results. Overwriting joined ambiguous columns.

Fix seems to be changing in QueryEngine.php:

private function compile($builder, $columns)
{
    $this->counter = $builder->count();

to

private function compile($builder, $columns)
{
    $this->counter = $this->builder->count();

Compatibility with Dynatable

Hi,
you've built a great package, thank you for that !
I'm moving to Dynatable.js (http://os.alfajango.com/dynatable) because I prefer its configuration (so much easier than datatables !), do you think that you can add the compatibility to Dynatable ?
I think the processes on the server-side are really close. Maybe I could fork your repo to create a Dynatable package, but I'm a beginner with Laravel...

Thanks again for this great package ! ;)

js at bottom not working

Am running 2.2 but am unable to load the js files at the bottom of my page. When I put them in all works fine. It looks like this was something that you fixed a while ago, or am I wrong? I have only just started playing with Datatable. It looks like a great alternative to Datatables.

Table: setOptions() Issue

I'm trying to use your setOptions to set the bSortable to false for the 5th column.

I've tried various ways to set this using setOptions but it doesn't seem to work.
I hard coded the option into the template.blade.php just to check to see if it work which it did.

Here is the jQuery Datatables option setting:

"aoColumnDefs": [
{ "bSortable": false, "aTargets": [4] }
]

How do I set this option using your method?
Unfortunately PHP can't create an object on the fly.
Do I need to create the object in a separate line of code and pass it in that way?

-- Christopher Mullins

Using query() ignores order and search

When you use the query() method it ignores any search and order functionality entered by the user on the front-end.

This is because you need to re-assign the builder when adding new database queries to it.

E.g.

In QueryEngine.php line 110 change:

$this->builder->orWhere($c,'like','%'.$this->search.'%');

to:

$this->builder = $this->builder->orWhere($c,'like','%'.$this->search.'%');

Alternatively, in recent versions of Laravel you can avoid the need to constantly re-assign by initially assigning the builder property with a ->query() method on the chain. I'm not sure when this was introduced, so I don't know about backwards-compatibility.

E.g.

In QueryEngine.php line 35 change to:

$this->builder = $builder->query();

Serverside ordering Columns

Using ServerSide, only the first column of the DataTable can't be ordered.
The remaining columns order just fine.
If "bServerSide": false, all columns order as expected.

I took a look on debug but can't solve this issue.
Regards

custome columns and json settings

nice package how can we add custom column in it, for example i have 2 column coming from database id, name and want to add third custom column, action which will has anchor edit.

some more other features i don't want to use script from your package just generate only json settings for datatables which i can use in my javascript

Trying to get property of non-object

Hi, thanks for nice module.
I have some issue with custom column in my project. When I try to use relationship with model it produces "Trying to get property of non-object" error. Similar call in my views works like a charm and I get title of a producent. Do you have any suggestions where could be a problem?

Thanks
Tom

public function table()
    {
        return Datatable::collection($this->product->all())                       
        ->addColumn('producent', function($model) {
            return $model->producent->title;
        })
        ->make();
    }

iTotalDisplayRecords not working well with QueryEngine

Hello! First off, thanks you for coding this awesome tool!
Greetings from Chile, so excuse my bad english.

Well, I'm working with Query Engine with 50.000 data.
It works well, except that in search mode. It shows:

"Showing entries from 21 to 30 from a total of 50,000 entries"

It should show:

"Showing entries from 21 to 30 from a total of 47 entries
(filtered from a total of 50000 entries)"

I have made my own solution. In QueryEngine.php class I added this new variable:

private $counter = 0;

Then i rewrote the function count()

public function count()
{
    return $this->counter;
}

And last i added the following line inside compile() function (at top of code):

$this->counter = $builder->count();

Thanks

DB::raw() with alias

It looks like the Laravel forum thread is no longer active, so am asking here. This is quite a great plug-in you've made. I'm wondering how I might use a DB:raw call in the select with a group by, like below. It is currently returning a 500 error:

 $query = $this->user
            ->select('users.id', 'users.username','users.email',   DB::raw('GROUP_CONCAT( roles.name) AS roles'), 'users.confirmed', 'users.created_at')
            ->leftjoin('assigned_roles', 'assigned_roles.user_id', '=', 'users.id')
            ->leftjoin('roles', 'roles.id', '=', 'assigned_roles.role_id')
            ->groupBy('users.id')
            ->get();

    $table = Datatable::collection($query

     return $table

        ->showColumns('id', 'username', 'email','roles')
        ->setSearchWithAlias()
        ->searchColumns("roles") ...

UPDATE: I think it's better to do this query without group by and instead get the roles per user via something like

->addColumn('roles', function($model) { return $model->currentRoleIds(); })

But are DB::raw() queries allowed?

One other minor question -- I notice that after setting orderColumns, the columns that don't sort still show the asc/desc arrow images, and the arrows are still selectable even though they don't do anything. Is this intended?

The setSearchOperator() method is missing.

Has this method been removed from the query engine for some reason. I'm testing with both MySQL and Postgres databases. When I tried to use this method with Datatable::query() I got a missing method error.

I searched the code for this method and could not find it either.

-- Christopher Mullins

ILIKE on MySQL

Getting ILIKE statements through doInternalSearch() on a MySQL Query.

:(

Please and thank you.

Datatable::table()->setOptions() Issue

Minor Bug: Generation of Javascript is incorrect for the following option:

Option:

->setOptions('aaSorting', array(
  array(
    1 => 'asc'
  )
))

Should generate an Array of Arrays:

  "aaSorting": [[1, 'asc']]

But instead generates an Array of Objects:

  "aaSorting": [{'1': 'asc'}]

-- Christopher Mullins

Case insensitive searches on server side?

Does Datatables Plugin handle this on the server side?

I've set the option bCaseInsensitive for Datatables but it only seems to affect the first word of every column and not the entire content.

  jQuery(document).ready(function(){
    // dynamic table
    jQuery('.IgflooDr').dataTable({
      "sPaginationType": "full_numbers",
      "bProcessing": false,
      "bJQueryUI": false,
      "oSearch": {"bCaseInsensitive":true},
      "aaSorting": [[1,"asc"]],
      "aoColumnDefs": [{"bSortable":false,"aTargets":[0,5,6]},{"sClass":"center","aTargets":[0,5,6]}, "sClass":"nowrap","aTargets":[1,4]}],
      "bStateSave": true,
      "sAjaxSource": "http:\/\/versicatalog.herokuapp.com\/account\/catalog\/api",
      "bServerSide": true,
    });
    // custom values are available via $values array
  });

-- Christopher Mullins

Table name

Hello,

I am really liked this bundle, and work with it in a large CRM System.

My question is: Have any chance to set the table id?

Like

<table id="myTable">

Thanks!

Ordering on relationships

Is there a way to order on relationships?

            return \Datatable::from($this->job->query())
            ->showColumns('title', 'freelance', 'budget')
            ->addColumn('category',function($model)
            {
                return $model->category->name;
            })
            ->searchColumns('title')
            ->orderColumns('title', 'category', 'budget')
            ->make();

When I order on category it says the column doesn't exist on jobs table.

Possible option in searching?

Hello Chumper,

I wanted to know if you package has the capablity to allow for exact word matches? For example I search Complete but Incomplete and Complete will be shown from the search. Is it possible for just Complete to be shown after a search?

Change css classes

Hello,

First I would like to thank you for this great job!

But I have a question: Is there any way to change the class of the element table.
example:

Thank you for your attention!

Strange Issue on a Model

I have a model that has a column called "ass_active", it's using a connection called "mysql_superdepot".

Here is what I'm building prior to handing it off to Datatables:

$model = SuperDepotSuperfund::select(array('superfundname', 'datesold'))->where('clientid', '=', $id); if (Input::has('status')) { if (Input::get('status') == 'active') { $model = $model->where('ass_active', '=', 'True'); } if (Input::get('status') == 'inactive') { $model = $model->where('ass_active', '!=', 'True'); } if (Input::get('status') == 'terminated') { $model = $model->where('ass_terminated', '=', 'True'); } }

If I call return $model->get(); - it works and returns the normal json model no probs. However if I call:

return Datatables::of($model)->make();

It throws the following error:

 SQLSTATE[42S22]: Column not found: 1054 Unknown column 'ass_active' in 'where clause' (SQL:      select count(*) as aggregate from (select `superfundname`, `datesold` from `tblclientsuperfunds` where `clientid` = 13412 and `ass_active` = True) AS count_row_table)'`

Any ideas?

I think it might be related to the fact it's not using the default connection as I have another table in the database with the same name, but using the default connection.

ErrorException Datatable::collection() should not be called statically

just got this ErrorException after updating to 2.1.x:

exception 'ErrorException' with message 
'Non-static method Chumper\Datatable\Datatable::collection() should not be called statically, assuming $this from incompatible context'
return Datatable::collection(User::all())
            ->showColumns('user_id', 'email', 'login_locked', 'confirmed', 'actions')
            ->addColumn('user_id', function($model) {
                return $model->getPresenter()->id;
            })
            ->addColumn('email', function($model) {
                return $model->getPresenter()->email;
            })
            ->addColumn('login_locked', function($model) {
                return ($model->getPresenter()->is_locked) ? Lang::get('general.yes') : Lang::get('general.no');
            })
            ->addColumn('confirmed', function($model) {
                return ($model->getPresenter()->is_confirmed) ? Lang::get('general.yes') : Lang::get('general.no');
            })
            ->addColumn('actions', function($model) {
                return '<div class="btn-toolbar btn-group-sm">' . $model->getPresenter()->edit_link.$model->getPresenter()->login_link.'</div>';
            })
            ->orderColumns('id', 'email', 'login_locked', 'confirmed')
            ->make();

rolling back to 2.0.x "solves" the issue.

Iterate through a collection in an addColumn

In a Users list, where users have many roles, I'd like to list all of those roles for each user. This works fine, but does Datatable give me another option?

        ->addColumn('roles', function($model) { 

            $roles = '';

            $model->roles->each(function($role) use (&$roles)
                {
                    $roles .= $role->name . '<br>';
                });

            return $roles;
        })

FatalErrorException

Heya,

Thanks for the package! Getting an error when doing the following:

return Datatable::collection(ClientType::all(array('id', 'type'))) ->showColumns('id', 'type') ->searchColumns('type') ->orderColumns('id', 'type') ->make();

I get:

Symfony \ Component \ Debug \ Exception \ FatalErrorException Using $this when not in object context

It's highlighted line 217.

if(!is_null($this->rowClass) && is_callable($this->rowClass))

Update: 2.0.x works no probs.

Any ides why this would happen?

Search in DB::raw Count

I have in my eloquent result a column created by a DB:raw like this:

$result = Atendimento::Join('cliente', 'atendimento.a_cliente_id', '=', 'cliente.c_id')
    ->leftJoin('telefones', 'cliente.c_id', '=', 'telefones.t_id_cliente')  
    ->leftJoin('usuario', 'a_corretor_id', '=', 'usuario.id')
    ->leftJoin('repiques_favoritos', 'a_id', '=', 'repf_id_atendimento')
    ->leftJoin('cliente_imovel', 'a_cliente_id', '=', 'imob_cliente_id')
    ->leftJoin('imob_imoveis', 'imob_imovel_id', '=', 'imovel_id')
    ->leftJoin('imovel', 'imob_imoveis.imovel_id', '=', 'imovel.imovel_codigo')
    ->groupBy('a_id')
    ->Select('a_id', 'a_updated_at', 'c_nome', 't_cod_area', 't_telefone', 'usuario.nome', 'imovel.imovel_nome', 'imovel.imovel_bairro', 
    DB::Raw('(SELECT COUNT(r_id_atendimento) FROM atendimento_repique WHERE r_id_atendimento = a_id ) AS Total'), 'c_id')
    ->whereRaw('(repf_tipo <> 3 OR repf_tipo is null)');

If I try to filter or search by the "Total" (Yes I know O need a having clause to make this filter) It's not work.

Can you implement it or can you give me the steps where I need to modify to have this search work?

Not Sorting Properly On Date Columns

Heya!

I'm defining an accessor on one of my date columns to reformat it to UK format:

public function getInvoicedateAttribute($invoicedate) { if ($invoicedate != '') { return Carbon::createFromFormat('Y-m-d', $invoicedate)->format('d/m/Y'); } else { return ''; } }

The problem I'm having is when I use the following:

return Datatable::collection(Invoice::where('clientid', '=', $id)->get()) ->showColumns('invoicenumber', 'cstname', 'invoicedate') ->addColumn('status', function ($model) { if ($model->paidinfull == 'True') { return "<label class='label label-success'>Paid</label>"; } else { return "<label class='label label-danger'>Outstanding</label>"; } }) ->addColumn('actions', function ($model) { return "<a ui-sref='client.invoice-edit({invoicenumber:" . $model->invoicenumber . "})' class='btn btn-primary btn-xs' title='Edit invoice'><i class='fa fa-edit'></i></a> <a href='javascript:void(0);' opendialog url='" . Config::get('angularjsvars.partialsUrl') . "invoices/partials/reprint-invoice.html' update-id='" . $model->nvoicenumber . "' class='btn btn-info btn-xs' title='Reprint invoice'><i class='fa fa-print'></i></a>"; }) ->searchColumns('invoicenumber', 'cstname', 'invoicedate') ->orderColumns('invoicenumber', 'cstname', 'invoicedate') ->make();

It won't sort correctly. If I remove the accessor it works properly but the date format is back to being mysql date format.

Any ideas?

I'm using 2.0.x as 2.1.x has some issues. Many thanks :)

Pagination error

Hello Nils,

I am experiencing weird behavior with the plugin. I have two pages worth of data (with showing 15 per page)

this is the first page of the data:
selection_010

then when going to the second page I am getting:
selection_011

(notice the 0151)

When this happens, for instance I see the data gets "jumbled" up I see the same rows from the first page on the second page even though I am using a orderBy clause in my query.

The third button as well can not be clicked. The cursor changes, but nothing happens when page 3 is requested.

{{ Datatable::table()   
                    ->setURL(route('allApplicationsJson'))
                    ->addColumn('', 'Recieved', 'Status', 'First Name', 'Last Name', 'Student ID', 'Aid Year', 'Type')
                    ->setOptions('bProcessing', true)
                    ->setOptions('bSort', false)
                    ->setOptions('iDisplayLength', '15')
                    ->setOptions('aLengthMenu', [5, 10, 15, 20, 25, 30, 35, 40, 45, 50])
                    ->setOptions('bAutoWidth', false)
                    ->setOptions('aoColumns', array(
                        array('sWidth' => '1%'),
                        array('sWidth' => '1%'),
                        array('sWidth' => '5%'),
                        array('sWidth' => '5%'),
                        array('sWidth' => '1%'),
                        array('sWidth' => '1%'),
                        array('sWidth' => '2%'),
                        array('sWidth' => '1%'),
                    ))
                    ->render() }}

I don't really know where to go from here to debug this issue I am having. Any tips? I will continue to play around with this hopefully it is something small. - I am loving the plug in. Thanks in advanced.

no order columns

how can I do that the no ordering colums not show the icons (up and down) on hover to set order??

Creating CRUD operations - Question

Hello Chumper,

I am currently trying to create CRUD operations within the datatable using your library.

I have a actions Column that will hold a user-id (for example) how do I create links within the datatable? Could you help point me in the right direction?

Actions column:

http://i.imgur.com/VPXM7kW.png

bSearchable has no effect

Hi,

It looks like setting the option

"bSearchable" => false 

does not have any effect. Setting

"bSortable" => false 

does work as expected, though. Is this a bug of am I overlooking something?

Thanks for your help!

Retrieve last query

Have any chances to retrieve the last query with filters and order?

I tryed

$queries = DB::getQueryLog();
$last_query = end($queries);

but this returning an empty array.

Thanks.

Separate the rendering of the script from the table()

Hi,
it's a good practise to put all the javascript just before the < / body> tag.
The problem is that when you call the Datatable::table() function, the script is put right after the table, and Jquery isn't declared yet.
In my opinion, we should be able to have a separate function like Datatable::script() to be able to append the script wherever we want. (Still after the Datatable::table() declaration, but not right after)
I see several options to do it :
Datatable::table()->noScript() which don't include the script part
Datatable::script() to append the script

QueryEngine sorting

on line 226 you have:

if($i === $this->orderColumn)

looks like $this->orderColumn isn't being cast as an int.

fix is to go:

$this->orderColumn = (int) $column; 

on line 60 of QueryEngine.php

HTML Stripping

When adding a column via addColumn() and placing that column in orderColumns()

The sort does not strip HTML or obey sTypes.

EG:
->addColumn('title', function($row)
{
return link_to_route('admin.organisations.show', $row->title, ['organisations' => $row->id]);
})

Laravel 4 JSON parsing error

When I use the example there is a warning message send with the json Response;

string 'select \* from "accounts"' (length=24)
{"aaData":[["1","109411"],["2","134088"],["3","127194"],["4","136775"],["5","100849"],["6","136932"],["7","117070"],["8","135844"],["9","106640"],["10","105231"],["11","134366"],["12","119389"],["13","137035"],["14","120082"],["15","126106"],["16","137951"],["17","132864"],["18","129717"],["19","114318"],["20","123645"],["21","133949"],["22","108770"],["23","134096"],["24","131160"],["25","137027"],["26","137455"],["27","105713"],["28","106074"],["29","107168"],["30","107092"],["31","105671"],["32","137971"],["33","136614"],["34","114753"],["35","132397"],["36","130927"],["37","120823"],["38","130378"],["39","134395"],["40","119698"],["41","106147"],["42","105987"],["43","138056"],["44","112951"],["45","130839"],["46","104996"],["47","133153"],["48","125909"],["49","105213"],["50","109776"],["51","111832"],["52","128303"],["53","133842"],["54","126889"],["55","106229"],["56","126195"],["57","113879"],["58","134230"],["59","137941"],["60","123114"],["61","129734"],["62","130801"],["63","134730"],["64","106007"],["65","114383"],["66","113570"],["67","104859"],["68","126259"],["69","104208"],["70","134791"],["71","140941"],["72","133844"],["73","128676"],["74","120179"],["75","113942"],["76","114651"],["77","104664"],["78","104132"],["79","915462"],["80","123164"],["81","128039"],["82","135366"],["83","129796"],["84","126884"],["85","127631"],["86","124756"],["87","132720"],["88","119599"],["89","123333"],["90","137952"],["91","106254"],["92","131219"],["93","114091"],["94","121367"],["95","125684"],["96","104082"],["97","138844"],["98","133653"],["99","114609"],["100","139527"]],"sEcho":0,"iTotalRecords":100,"iTotalDisplayRecords":100}

Null count on join query

Hi, a join query return a null count on paginate : "iTotalRecords":null,"iTotalDisplayRecords":null

1st page is ok but other ones return null values.

No problem with a simple select query.

Search on integer or float

Hi,
when I try to search on a float column value, the query fails because of the "LIKE" statement.
Maybe we could CAST the integer and float value to be able to use the search feature on them, but it supposes that we have to indicate the column type somewhere.
What do you think ?

Passing fnServerParams

Thanks for the awesome plugin . can you please guide me how can i pass a additional parameter from client side and get in server side
for example in client site I want to pass this value in a ajax request so can i get in server side
fnServerParams": function (aoData) {
aoData.push(
{ "name": "firstcriteria", "value": $("#txtParameter1").val() },
{ "name": "secondcriteria", "value": $("#txtParameter2").val() }
);
}

Data being received but table does not populate

Hello sir,

I love the simplicity of your package. It saves me a lot of time as a developer. However I am at the end of my wits here and I need help from the creator.

I am :
-Using Query engine
-Using server side processing (->setURL(route('allUsersJson')) and "bServerSide": true,)
-When not using server side processing my data comes just fine no issues

My controller :

public function allUsersJson()
{
$user = DB::table('user');
return Datatable::query($user)
->showColumns('userId', 'name', 'email', 'active', 'yearFrom', 'yearTo')
->searchColumns('name', 'email')
->make();
}

my view :
{{ Datatable::table()
->setURL(route('allUsersJson'))
->addColumn('Actions','Name', 'Email', 'Status', 'From', 'To')
->setOptions('bProcessing', true)
->setOptions('bSort', false)
->setOptions('iDisplayLength', '5')
->setOptions('aLengthMenu', [5,10,15,20])
->setOptions('bAutoWidth', false)
->setOptions('sAjaxDataProp', 'aaData')
->render() }}

and in my chrome dev tools I send :

Request URL:https://www.learnlaravel.com/api/users?sEcho=1&iColumns=6&sColumns=&iDisplayStart=0&iDisplayLength=5&mDataProp_0=0&mDataProp_1=1&mDataProp_2=2&mDataProp_3=3&mDataProp_4=4&mDataProp_5=5&sSearch=&bRegex=false...............(and so on - its a very long URL)

and I receive:

{"aaData":[["1","_","_[email protected]","1","08/2012","08/2014"],["5","RixA","_**@gmail.com","1","02/2012","03/2015"]],"sEcho":0,"iTotalRecords":"2","iTotalDisplayRecords":"2"}

I don't understand what I am missing here. Any help would be great. I also asked on the laravel 4 forums as well. Thanks in advanced.

setAliasMapping error rendering

When I add at controller
->setAliasMapping();

I see this error on render:
DataTables warning (table id = 'DataTables_Table_0'): Requested unknown parameter '0' from the data source for row 0

Class 'DataTable' not found

I only get that on my production server, not locally. And I have loads of other packages installed that works well. Servers are nearly identical, and I've done the usual tricks clearing composer cache and what not.

order default by custom field?

I have at server side

return Datatable::collection(Mymodel::orderBy('type')->get())
->showColumns('id','type','order','title','about')
->searchColumns('title','about')
->orderColumns('type','order','title')
->addColumn('type',function($model)
{
return Mymodel::Typename($model->type); //show the name of type number
})->make()

I want the first ordering default be 'type', but if y show 'type' like a custom field the order (in this example), the order default is by 'id', in fact, if I debug, the getOrder() return
["id","type","order","title","about"]

How can I establish a default order ?

If you supply created_at or updated_at in showColumns it will return the object, not the string.

Time for a fix maybe ? This is pretty annoying, while your example in the documentation shows you can show the date-time-stamps.

I developed this package because i was not happy with the only existing package at https://github.com/bllim/laravel4-datatables-package so i developed this package with in my opinion is superior.

Well... this output seems not superior at all to me :-)

ID Email Created At Updated At
2 [email protected] [object Object] [object Object]
17 [email protected] [object Object] [object Object]

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.