GithubHelp home page GithubHelp logo

waldo2188 / datatablebundle Goto Github PK

View Code? Open in Web Editor NEW
17.0 5.0 16.0 1.32 MB

Symfony2 Ajax Datatable Bundle to simplify the use of http://datatables.net/ (and Doctrine entity inside)

License: MIT License

PHP 94.81% HTML 5.19%

datatablebundle's Introduction

DatatableBundle

Fork of AliHichem/DatatableBundle, this bundle will add some great features and evolve in a different way than it source.

Build Status SensioLabsInsight

Warning: The jQuery Datatable plugin has evolved (version 1.10) with a all new API and option.
You MUST use the version 2 of DatatableBundle with the jQuery Datatable plugin version lower than 1.10.
You MUST use the version 3 of DatatableBundle with the jQuery Datatable plugin version equal or greater than 1.10.

The Datatable bundle for symfony2 allow for easily integration of the jQuery Datatable plugin with the doctrine2 entities. This bundle provides a way to make a projection of a doctrine2 entity to a powerful jquery datagrid. It mainly includes:

  • datatable service container: to manage the datatable as a service.
  • twig extension: for view integration.
  • dynamic pager handler : no need to set your pager.
  • support doctrine2 association.
  • support of Doctrine Query Builder.
  • support of doctrine subquery.
  • support of column search.
  • support of custom twig/phpClosure renderers.
Screenshot

Summary


Installation

Installation is a quick (I promise!) 3 step process:

  1. Download DatatableBundle using Composer
  2. Enable the Bundle
  3. Configure the Bundle

Download DatatableBundle using Composer

Using Composer

Install with this command : composer require waldo/datatable-bundle

Generate the assets symlinks :

php app/console assets:install --symlink web

Enable the Bundle

Add the bundle to the AppKernel.php

$bundles = array(
    \\...
    new Waldo\DatatableBundle\WaldoDatatableBundle(),
    )

Configure the Bundle

In this section you can put the global config that you want to set for all the instance of DataTable in your project.

To keep it to default

# app/config/config.yml
waldo_datatable:
    all:    ~
    js:     ~

The js config will be applied to DataTable exactly like you do with $().datatable({ your config }); in a javascript part.

Note: all your js config have to be string typed, make sure to use (") as delimiters.

Config sample

waldo_datatable:
    all:
        search:           false
    js:
        pageLength: "10"
        lengthMenu: [[5,10, 25, 50, -1], [5,10, 25, 50, 'All']]
        dom: '<"clearfix"lf>rtip'
        jQueryUI: "false"

How to use DatatableBundle ?

Assuming for example that you need a grid in your "index" action, create in your controller method as below :

Warning alias as is case-sensitive, always write it in lower case

/**
 * set datatable configs
 * @return \Waldo\DatatableBundle\Util\Datatable
 */
private function datatable() {
    return $this->get('datatable')
                ->setEntity("XXXMyBundle:Entity", "x")                          // replace "XXXMyBundle:Entity" by your entity
                ->setFields(
                        array(
                            "Name"          => 'x.name',                        // Declaration for fields:
                            "Address"       => 'x.address',                     // "label" => "alias.field_attribute_for_dql"
                            "Total"         => 'COUNT(x.people) as total',      // Use SQL commands, you must always define an alias
                            "Sub"           => '(SELECT i FROM ... ) as sub',   // you can set sub DQL request, you MUST ALWAYS define an alias
                            "_identifier_"  => 'x.id')                          // you have to put the identifier field without label. Do not replace the "_identifier_"
                        )
                ->setWhere(                                                     // set your dql where statement
                     'x.address = :address',
                     array('address' => 'Paris')
                )
                ->setOrder("x.created", "desc");                                // it's also possible to set the default order
}


/**
 * Grid action
 * @Route("/", name="datatable")
 * @return Response
 */
public function gridAction()
{
    return $this->datatable()->execute();                                      // call the "execute" method in your grid action
}

/**
 * Lists all entities.
 * @Route("/list", name="datatable_list")
 * @return Response
 */
public function indexAction()
{
    $this->datatable();                                                         // call the datatable config initializer
    return $this->render('XXXMyBundle:Module:index.html.twig');                 // replace "XXXMyBundle:Module:index.html.twig" by yours
}

Rendering inside Twig

You have the choice, you can render the HTML table part and Javascript part in just one time with the Twig function datatable, like below.

<!-- XXX\MyBundle\Resources\views\Module\index.html.twig -->

<!-- include the assets -->
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/r/dt/dt-1.10.9/datatables.min.css"/>
<script type="text/javascript" src="//code.jquery.com/jquery-2.1.4.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/r/dt/dt-1.10.9/datatables.min.js"></script>

{{ datatable({
        'js' : {
            'ajax' : path('route_for_your_datatable_action')
        }
    })
}}

Or, render each part separatly.

datatable_html is the Twig function for the HTML part.
datatable_js is the Twig function for the Javascript part.

{% block body %}
    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/r/dt/dt-1.10.9/datatables.min.css"/>
    {{ datatable_html({
            'id' : 'dta-offres'
        })
    }}

{% endblock %}

{% block javascripts %}
<script type="text/javascript" charset="utf8" src="//code.jquery.com/jquery-1.10.2.min.js"></script>
<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/1.10.9/js/jquery.dataTables.js"></script>
{{ datatable_js({
        'id' : 'dta-offres',
        'js' : {
            'dom': '<"clearfix"lf>rtip',
            'ajax': path('route_for_your_datatable_action'),
        }
    })
}}
{% endblock javascripts %}

Advanced Use of DatatableBundle

Advanced php config

Assuming the example above, you can add your joins and where statements.

/**
 * set datatable configs
 *
 * @return \Waldo\DatatableBundle\Util\Datatable
 */
private function datatable()
{
    return $this->get('datatable')
                ->setEntity("XXXMyBundle:Entity", "x")      // replace "XXXMyBundle:Entity" by your entity
                ->setFields(
                        array(
                            "Name"          => 'x.name',    // Declaration for fields:
                            "Address"       => 'x.address', // "label" => "alias.field_attribute_for_dql"
                            "Group"         => 'g.name',
                            "Team"          => 't.name',
                            "_identifier_"  => 'x.id')      // you have to put the identifier field without label. Do not replace the "_identifier_"
                        )
                ->addJoin('x.group', 'g', \Doctrine\ORM\Query\Expr\Join::INNER_JOIN)
                ->addJoin('x.team', 't', \Doctrine\ORM\Query\Expr\Join::LEFT_JOIN)
                ->addJoin('x.something', 's', \Doctrine\ORM\Query\Expr\Join::LEFT_JOIN, \Doctrine\ORM\Query\Expr\Join::WITH, 's.id = :someId')
                ->setWhere(                                // set your dql where statement
                     'x.address = :address',
                     array('address' => 'Paris')
                )
                ->setOrder("x.created", "desc")            // it's also possible to set the default order.
                ->setParameter('someId', 12)
                ;
}

Use of search filter

Activate search globally

The searching functionality that is very useful for quickly search through the information from the database. This bundle provide two way of searching, who can be used together : global search and individual column search.

By default the filtering functionality is disabled, to get it working you just need to activate it from your configuration method like this :

private function datatable()
{
    return $this->get('datatable')
                //...
                ->setSearch(true); // for individual column search
                // or
                ->setGlobalSearch(true);
}

Set search fields

You can set fields where you want to enable your search. Let say you want search to be active only for "field 1" and "field3 ", you just need to activate search for the approriate column key and your datatable config should be :

/**
 * set datatable configs
 *
 * @return \Waldo\DatatableBundle\Util\Datatable
 */
private function datatable()
{
    $datatable = $this->get('datatable');
    return $datatable->setEntity("XXXMyBundle:Entity", "x")
                    ->setFields(
                            array(
                                "label of field 1" => 'x.field1',   // column key 0
                                "label of field 2" => 'x.field2',   // column key 1
                                "label of field 3" => 'x.field3',   // column key 2
                                "_identifier_" => 'x.id')          // column key 3
                    )
                    ->setSearch(true)
                    ->setSearchFields(array(0,2))
    ;
}

Multiple actions, how to had checkbox for each row ?

Sometimes, it's good to be able to do the same action on multiple records like deleting, activating, moving ... Well this is very easy to add to your datatable: all what you need is to declare your multiple action as follow.

/**
 * set datatable configs
 * @return \Waldo\DatatableBundle\Util\Datatable
 */
private function datatable()
{
    $datatable = $this->get('datatable');
    return $datatable->setEntity("XXXMyBundle:Entity", "x")
                    ->setFields(
                            array(
                                "label of field1" => 'x.field1',   // column key 0
                                "label of field2" => 'x.field2',   // column key 1
                                "_identifier_" => 'x.id')          // column key 2
                    )
                    ->setMultiple(
                                array(
                                    'delete' => array(
                                        'title' => 'Delete',
                                        'route' => 'multiple_delete_route' // path to multiple delete route action
                                    ),
                                    'move' => array(
                                        'title' => 'Move',
                                        'route' => 'multiple_move_route' // path to multiple move route action
                                    ),
                                )
                        )
    ;
}

Then all what you have to do is to add the necessary logic in your "multiple_delete_route" (or whatever your route is for). In that action, you can get the selected ids by :

$data = $this->getRequest()->get('dataTables');
$ids  = $data['actions'];

Custom renderer for cells

Twig renderers

To set your own column structure, you can use a custom twig renderer as below : In this example you can find how to set the use of the default twig renderer for action fields which you can override as your own needs.

/**
 * set datatable configs
 * @return \Waldo\DatatableBundle\Util\Datatable
 */
private function datatable()
{
    $datatable = $this->get('datatable');
    return $datatable->setEntity("XXXMyBundle:Entity", "x")
                    ->setFields(
                            array(
                                "label of field1" => 'x.field1',
                                "label of field2" => 'x.field2',
                                "_identifier_" => 'x.id')
                    )
                    ->setRenderers(
                            array(
                                2 => array(
                                    'view' => 'XXXMyBundle:Renderers:_actions.html.twig', // Path to the template
                                    'params' => array( // All the parameters you need (same as a twig template)
                                            'edit_route'    => 'route_edit',
                                            'delete_route'  => 'route_delete'
                                        ),
                                ),
                            )
                    );
}

In a twig renderer you can have access the the field value using dt_item variable,

// XXXMyBundle:Renderers:_actions.html.twig
{{ dt_item }}

or access the entire entity object using dt_obj variable.

// XXXMyBundle:Renderers:_actions.html.twig
<a href="{{ path('route_to_user_edit',{ 'user_id' : dt_obj.id }) }}">{{ dt_obj.username }}</a>

NOTE: be careful of Doctrine's LAZY LOADING when using dt_obj !

PHP Closures

Assuming the example above, you can set your custom fields renderer using PHP Closures.

/**
 * set datatable configs
 * @return \Waldo\DatatableBundle\Util\Datatable
 */
private function datatable() {

    $controller_instance = $this;
    return $this->get('datatable')
                ->setEntity("XXXMyBundle:Entity", "x")          // replace "XXXMyBundle:Entity" by your entity
                ->setFields(
                        array(
                            "Name"          => 'x.name',        // Declaration for fields:
                            "Address"        => 'x.address',    // "label" => "alias.field_attribute_for_dql"
                            "_identifier_"  => 'x.id')          // you have to put the identifier field without label. Do not replace the "_identifier_"
                        )
                ->setRenderer(
                    function(&$data) use ($controller_instance) {
                        foreach ($data as $key => $value) {
                            if ($key == 1) {            // 1 => address field
                                $data[$key] = $controller_instance
                                        ->get('templating')
                                        ->render(
                                               'XXXMyBundle:Module:_grid_entity.html.twig',
                                               array('data' => $value)
                                        );
                            }
                        }
                    }
                );
}

DataTable Callbacks options

If you need to put some Javascript Callbacks like drawCallback, you can do it localy with the Datatable js option. See the two examples below:

// XXXMyBundle:Welcome:list.html.twig
{{ datatable_js({
        'id' : 'datable-id',
        'js' : {
            'ajax': "/some/path",
            'createdRow': 'function(){console.log("Do something useful here");}'
        }
    })
}}

{# or #}

{{ datatable_js({
        'id' : 'datable-id',
        'js' : {
            'ajax': "/some/path",
            'createdRow': 'myUsefullThing'
        }
    })
}}
<script type="text/javascript">
var myUsefullThing = function() {
    // Do something here
};
</script>

You can also define a Callback globally by setting it up in the config.yml like below :

waldo_datatable:
    js:
        createdRow: |
            function(){console.log("Do something useful here");}

Translation

You can set your own translated labels by adding in your translation catalog entries as define in Resources/translations/messages.en.yml

You can also get the translated labels from official DataTable translation repository, by configuring the bundle like below :

waldo_datatable:
    all:    ~
    js:
        language:
            url: "//cdn.datatables.net/plug-ins/1.10.9/i18n/Chinese.json"

This bundle includes nine translation catalogs: Arabic, Chinese, Dutch, English, Spanish, French, Italian, Polish, Russian and Turkish To get more translated entries, you can follow the official DataTable translation

Doctrine Query Builder

To use your own query object to supply to the datatable object, you can perform this action using your own "Doctrine Query object": DatatableBundle allow to manipulate the query object provider which is now a Doctrine Query Builder object, you can use it to update the query in all its components except of course in the selected field part.

This is a classic config before using the Doctrine Query Builder:

private function datatable()
{
    $datatable = $this->get('datatable')
                ->setEntity("XXXBundle:Entity", "e")
                ->setFields(
                        array(
                            "column1 label" => 'e.column1',
                            "_identifier_" => 'e.id')
                        )
                ->setWhere(
                    'e.column1 = :column1',
                    array('column1' => '1' )
                )
                ->setOrder("e.created", "desc");

     $qb = $datatable->getQueryBuilder()->getDoctrineQueryBuilder();
     // This is the Doctrine Query Builder object, you can
     // retrieve it and include your own change

     return $datatable;
}

This is a config that uses a Doctrine Query object a query builder :

private function datatable()
{
    $qb = $this->getDoctrine()->getEntityManager()->createQueryBuilder();
    $qb->from("XXXBundle:Entity", "e")
       ->where('e.column1 = :column1')
       ->setParameters(array('column1' = 0))
       ->orderBy("e.created", "desc");

    $datatable = $this->get('datatable')
                ->setFields(
                        array(
                            "Column 1 label" => 'e.column1',
                            "_identifier_" => 'e.id')
                        );

    $datatable->getQueryBuilder()->setDoctrineQueryBuilder($qb);

    return $datatable;
}

Multiple DataTable in the same view

To declare multiple DataTables in the same view, you have to set the datatable identifier in you controller with setDatatableId : Each of your DataTable config methods ( datatable() , datatable_1() .. datatable_n() ) needs to set the same identifier used in your view:

In the controller

protected function datatable()
{
    // ...
    return $this->get('datatable')
                ->setDatatableId('dta-unique-id_1')
                ->setEntity("XXXMyBundle:Entity", "x")
    // ...
}

protected function datatableSecond()
{
    // ...
    return $this->get('datatable')
                ->setDatatableId('dta-unique-id_2')
                ->setEntity("YYYMyBundle:Entity", "y")
    // ...
}

In the view

{{
    datatable({
        'id' : 'dta-unique-id_1',
        ...
            'js' : {
            'ajax' : path('route_for_your_datatable_action_1')
            }
    })
}}

{{
    datatable({
        'id' : 'dta-unique-id_2',
        ...
        'js' : {
            'ajax' : path('route_for_your_datatable_action_2')
        }
    })
}}

Use specific jQuery DataTable options

Some time we need to apply some specific options to a grid, like a specific width for the second column. DataTable comes with a lot a feature that you can always use, even with this bundle.

In the code below, we use the columnDefs option to fix the width of the second column.

{{
    datatable({
        'id' : 'dta-id',
        'js' : {
            'ajax' : path('route_for_your_datatable_action'),
            'columnDefs': [
                { "width": "15%", "targets": 1 }
            ]
        }
    })
}}

You really can play with all the DataTable's options.

datatablebundle's People

Contributors

76200 avatar alex-msk avatar alexmocanu avatar alihichem avatar andycowan avatar aricem avatar gchokeen avatar iandroogmans avatar jonmchan avatar juanperi avatar matthieu2607 avatar nightfox7 avatar stephanebakhos avatar waldo2188 avatar

Stargazers

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

Watchers

 avatar  avatar  avatar  avatar  avatar

datatablebundle's Issues

Records are not formatted

This is how my records came out

{"draw":0,"recordsTotal":"1","recordsFiltered":"1","data":[["Hillary","Test",1]]}

What is causing this problem?

Embeddable field problem

Hello,
When using embeddables the getData fucntion at Waldo\DatatableBundle\Util\Factory\Query\DoctrineBuilder doesn't work.

We think that this could be solved:

Embeddables: Fields thats comes like alias.address.zipcode then the 331 line not work.

We suggest replace the line 331 inside the get_scalar_key function:

$_f = str_replace('.', '_', $_f);

by:

$pos = strpos($_f,'.');
if ($pos !== false) {
    $_f = substr_replace($_f,'_',$pos,strlen('.'));
}

What's do you oppinnion about it?

Thanks

Route parameters on setMultiple

Hi,

I can not pass parameters to the route on function setMultiple.

I'm trying:

//...
->setMultiple(
      array(
            'delete' => array(
                  'title' => 'Delete',
                  'route' => [
                        'my_route' => [
                              'id' => 1
                        ]
                  ] 
            )
      )
)
//...

But I get:

An exception has been thrown during the rendering of a template ("Notice: Array to string conversion") in WaldoDatatableBundle:Snippet:multipleRaw.js.twig at line 2.`

Could you give me an example of how to do it?

thanks a lot

Variable "not_filterable_fields" does not exist.

Hi,
I've an issue when implementing the datatable bundle.
I've followed the doc, set up the bundle with composer etc.

In my controller :
/**

  • set datatable configs
  • @return \Waldo\DatatableBundle\Util\Datatable
    */
    private function datatable()
    {
    return $this->get('datatable')
    ->setDatatableId('produits')
    ->setEntity("AppBundle:Produit", "x")
    ->setFields(
    array(
    "Name" => 'x.name',
    "Description" => 'x.description',
    "price" => 'x.price' ,
    "quantity" =>'x.quantity',
    "identifier" => 'x.id'
    )
    )
    ->setHasAction(true);
    }

/**

  • Grid action
    *@route("/grid", name="produit_grid")
    */
    public function gridAction()
    {
    return $this->datatable()->execute();
    }

    /**

    • Lists all produit entities.
    • @route("/", name="produit_index")
    • @method("GET")
      */
      public function indexAction()
      {
      $this->datatable();
      return $this->render('AppBundle:produit:index.html.twig');
      }

In my view:

<script type="text/javascript" src="//code.jquery.com/jquery-2.1.4.min.js"></script> <script type="text/javascript" src="https://cdn.datatables.net/r/dt/dt-1.10.9/datatables.min.js"></script>

{{ datatable({
'id' :'produits',
'edit_route' : 'produit_edit',
'delete_route' : 'produit_delete',
'js' : {
'sAjaxSource' : path('produit_grid')
}
})
}}

the result of the grid action is fine:
{"sEcho":0,"iTotalRecords":"2","iTotalDisplayRecords":"2","aaData":[["pc","ordinateur portable",15,25,1],["ss","sqs",45,45,2]]}

but when i try to show my product's list page this error appears:

Variable "not_filterable_fields" does not exist.

Please any help? thank u

Problem with js defaults for number of entries

At least in DatatableBundle version 4.0.1 the "show number of entries combo" is generated wrong in the final html, it looks like:

<select class="">
<option value="[">[</option>
<option value="[">[</option>
<option value="1">1</option>
<option value="0">0</option>
<option value=",">,</option>
<option value=" "> </option>
. . . .

Could be fixed by changing the line

"lengthMenu" => '[[10, 25, 50, -1], [10, 25, 50, "All"]]',

by

"lengthMenu" => array(array(10, 25, 50, -1), array(10, 25, 50, "All")),

in vendor/waldo/datatable-bundle/DependencyInjection/WaldoDatatableExtension.php

I've made a mostly default install, jquery is 1.10.2, DataTables.min 1.10.9.

Thanks for the bundle - at least my first steps were rather easy!

Matthias

Twig 2.0?

Currently bundle locks on using twig ~1.8, is there any specific reason to stay at this version?

After aliasing 2.0 as 1.89 I didn't find any blockers - DatatableBundle seems to be working ok.

Individual column searching subquery syntax error

I tested your bundle with this code:

return $this->get('datatable')->setEntity('CRMBundle:Company', 'x')->setFields([
            'name' => 'x.name',
            'street' => 'x.street',
            "surname"         => '(SELECT MIN(u.surname) FROM CRMBundle:Contact u WHERE u.company = x.id) as surname',
            "_identifier_"  => 'x.id'
        ])->setSearch(true)->setSearchFields(array(0, 2))->setGlobalSearch(true);

and if i tried to filtering by surname I got this error:
[Syntax Error] line 0, col 164: Error: Expected =, <, <=, <>, >, >=, !=, got 'LIKE'
The QueryException:
SELECT COUNT(x.id) FROM CRMBundle:Company x WHERE (SELECT MIN(u_840532410.surname) FROM CRMBundle:Contact u_840532410 WHERE u_840532410.company = x.id) LIKE :sSearch_2 AND (x.name LIKE :sSearch_global_0 OR x.street LIKE :sSearch_global_1 OR (SELECT MIN(u_840532410.surname) FROM CRMBundle:Contact u_840532410 WHERE u_840532410.company = x.id) = :sSearch_global_2)

How to access a method of the repository?

Example I need get record for

$res=$qb->getQuery()->getResult();
$email=$res[0]->getOrderCustomer()->getEmail();

but I do not know how to access the method from: setFields()
if I try this I get this error

Notice: Undefined index: o_getOrderCustomer_getEmail

`$datatable = $this->get('datatable')
->setFields(
array(

                "Id" => 'o.id',
                "Email" => 'o.getOrderCustomer.getId()',// error
                "_identifier_" => 'n.id')
        )->setGlobalSearch(true);`

Help Please

Renderer and global search

Is it possible that the global search is not working on columns where I use a renderer?
This is my Code:

`$query = $this->get('datatable')
->setEntity("AppBundle:Logs", "lg")
->setFields(
array(
"Modul" => 'lg.module',
"Log" => 'lg.id',
"Datum" => 'lg.when', // Declaration for fields:
"Von" => 'lg.id', // "label" => "alias.field_attribute_for_dql"
"identifier" => 'lg.id') // you have to put the identifier field without label. Do not replace the "identifier"
)

                ->setWhere(                                                     // set your dql where statement
                     'lg.domain = :domain',
                     array('domain' => 'log')
                )
                
                //set a renderer for a specific column(index) 
                ->setRenderers(
                        array(
                            1 => array('view' => 'logs/renderers/log_renderer.html.twig'),
                            2 => array('view' => 'default/renderers/datetime.html.twig'),
                            3 => array('view' => 'logs/renderers/user.html.twig')
                        )
                )
                ->setOrder("lg.when", "desc")                                // it's also possible to set the default order
                ->setGlobalSearch(true);`

This is my log_renderer.html.twig for example:
{{ dt_obj.message }} ({{ dt_obj.module }}) <br />Standort: {{ dt_obj.hierarchyId }} <br />{{dt_obj.user }} {{ dt_obj.when|date('d.m.Y H:i') }}

I have a renderer for 3 columns. The only global search that works is for the first column, where is no renderer. Any suggestions?

Issues when search with aggregation SQL

When i try to enable search i have this problems
`
An exception occurred while executing 'SELECT COUNT(DISTINCT s0_.id) AS sclr_0 FROM shipment s0_ LEFT JOIN delivery_options d1_ ON s0_.deliveryoption_id = d1_.id LEFT JOIN address_book a2_ ON s0_.sender_addressbook_id = a2_.id LEFT JOIN address_book a3_ ON s0_.recipient_addressbook_id = a3_.id LEFT JOIN package p4_ ON s0_.id = p4_.shipment_id LEFT JOIN shipment_status s5_ ON s0_.shipment_status_id = s5_.id WHERE s0_.shipment_number LIKE ? OR s0_.control_number LIKE ? OR s0_.service_type LIKE ? OR d1_.delivery_option LIKE ? OR a2_.first_name LIKE ? OR a3_.first_name LIKE ? OR COUNT(p4.id) LIKE ?_ OR s0_.chargeable_weight LIKE ? OR s0_.grand_total LIKE ? OR s5_.name LIKE ? OR s0_.id LIKE ?' with params ["%%", "%%", "%%", "%%", "%%", "%%", "%%", "%%", "%%", "%%", "%%"]:

SQLSTATE[HY000]: General error: 1111 Invalid use of group function
`

As I see that the sql script is generated is wrong when have aggregation. It should be
Having COUNT(p4_.id) LIKE ? ...

Inject Parameters into Multiple Route

Is it be possible for params to be injected in setMultiple so that the route can be built using them in twig?

ExampleController.php
$dt->setMultiple(
array(
'delete' => array(
'title' => 'delete',
'route' => 'delete',
'params' => array('id' => $id),
),
)
)

multipleRaw.js.twig
{% for key,item in multiple %}
<option value="{{ path(item.route), item.params }}">{{ item.title }}</option>
{% endfor %}

Refresh Table Data After Multiple Select

When following the 'Multiple Actions how do I add a checkbox for each row?' example I experienced an issue where the datatable was not refreshing after the record had been updated in database.

Seems that the success function in multipleRaw.js.twig was not working for me.

 success: function(msg) {
                    $('#{{ id }}').trigger('dt.draw');
                },

It was replaced with;

success: function(msg) {
                    $('#{{ id }}').DataTable().ajax.reload(null, false );
                },

which solved it for me (and refreshed the table keeping the current pagination.

More information about how to add actions on each row

Hello @waldo2188 can you give more information about how to add some actions in a ceil for each row?

Using the solution in the README is not really working for me, maybe I'm missing something...

Using version 4.0.2 with dataTable version 1.10.12 from their CDN.

Filtering / Searching / order : nothing works

I am using Symfony 3.1.3 and Waldo 4.0.2 and filtering / sorting /order, brief, all ajax callings after first display of DataTable still return the exactly same JSON array.

It appears as Waldo DatatableBundle ignores parameters in request.

Someone had the same issue ?

I followed git instructions.

Datatables configuration not working

Datatables js configuration are not working in config.yml

Here is my configuration:

# Ajax Datatables configuration
waldo_datatable:
    all:
        search:           false
    js:
        pageLength: "10"
        lengthMenu: [[5,10, 25, 50, -1], [5,10, 25, 50, 'All']]
        dom: '<"clearfix"lf>rtip'
        jQueryUI: "false"
        bFilter: "false"

I am unable to see any JS and datatables changes as per those configurations

The changes are also not reflected by specifying them on twig options as well

{{ datatable({
    'js' : {
        'ajax' : path('datatable'),
        'bFilter':false
    }
})
}}

any work around on this issue please ?

Datetime field

It is possible to set a datetime in column with a specific format? Something like:

$this->get('datatable')
            ->setEntity("AppBundle:EmailEntity, "e")
            ->setFields(
                array(
                    'Created On' => 'date_format(e.createdOn, "%M")',
                    "_identifier_" => 'e.id',
                )
            )

Maximum number of datatables?

I am currently using three datatables.
When I want to create a fourth, it takes over the settings + header of the third datatable.

Display a Datetime Value

I have a problem with displaying a datetime Object. I have a field which is declared as "datetime" in my entity. When I put this field in the "setFields" Value ("StartDtTm" => 'csm.startdttm') I get this in my table:
[object Object]
When I look at the json return it is an array:
{"date":"2015-12-05 02:01:54","timezone_type":3,"timezone":"Europe/Berlin"}

But I have no idea how to get the "date" value from this array. 'csm.startdttm.date' is not working.
Please help me

Setting custom entityManger

I had to switch from AliDatabundle to another which is compatible with Symfony 3.

Unfortunatly, and don't understand why, customizing "entityManager" has not be forked here.. Why that ?

I have several entityManagers and, obviously, the one I have to use for my DataTable is not the one set by default.

Is this a missing ? Does it exist another way (in config.yml for example) to set which entityManger using ?

No results with eg code

Hi,

Now it's works with symfony3, I get no results with my test.

the json is valid :

{"draw":1,"recordsTotal":"0","recordsFiltered":"0","data":[]}

If you have an idea why I get no results ;-)

thanks.

twig file is

<!-- include the assets -->
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/r/dt/dt-1.10.9/datatables.min.css"/>
<script type="text/javascript" src="//code.jquery.com/jquery-2.1.4.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/r/dt/dt-1.10.9/datatables.min.js"></script>

{{ datatable({
        'js' : {
            'ajax' : path('datatable')
        }
    })
}}

My Controller:

class DatatableController extends Controller
{
    /**
     * set datatable configs
     * @return \Waldo\DatatableBundle\Util\Datatable
     */
    private function datatable()
    {
        return $this->get('datatable')
            ->setEntity("MyBundle:Task\Task", "x")// replace "XXXMyBundle:Entity" by your entity
            ->setDatatableId('dta-offres')
            ->setFields(
                array(
                    "name" => 'x.name',                        // Declaration for fields:
                    "identifiant" => 'x.identifiant',                    //      "label" => "alias.field_attribute_for_dql"
                    "_identifier_" => 'x.id')                          // you have to put the identifier field without label. Do not replace the "_identifier_"
            )
            ->setWhere(                                                     // set your dql where statement
                'x.error = :error',
                array('error' => 0)
            )
            ->setOrder("x.dateCreated", "desc");                                // it's also possible to set the default order
    }


    /**
     * Grid action
     * @Route("/ajax-datable-reports", name="datatable")
     * @return Response
     */
    public function gridAction()
    {
        return $this->datatable()->execute();                                      // call the "execute" method in your grid action
    }

    /**
     * Lists all entities.
     * @Route("/list", name="datatable_list")
     * @return Response
     */
    public function indexAction()
    {
        $respository = $this->getDoctrine()->getRepository('MyBundle:Task\Task');
        $r = $respository->findAll();
        // this works correctly and I get 92 results


        $this->datatable();                                                   // call the datatable config initializer
        return $this->render('MyBundle:layouts/rapports:datatable.html.twig');                 // replace "XXXMyBundle:Module:index.html.twig" by yours
    }
}

My Entity

/**

namespace MyBundle\Entity\Task;

 * @ORM\Entity
 * @ORM\Table(name="task")
 * @ORM\Entity(repositoryClass="MyBundle\Repository\TaskRepository")
 */
class Task
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @ORM\Column(type="string")
     */
    private $name;

    /**
     * @ORM\Column(type="boolean")
     */
    private $error;

    /**
     * @ORM\Column(type="string")
     */
    private $identifiant;

    /**
     * @ORM\Column(type="string")
     */
    private $data;

    /**
     * @ORM\Column(type="string")
     */
    private $message;

    /**
     * @ORM\Column(type="datetime")
     */
    private $dateCreated;

    public function __construct()
    {
        $this->dateCreated = new \DateTime();
    }

    /**
     * @return mixed
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * @param mixed $id
     */
    public function setId($id)
    {
        $this->id = $id;
    }

    /**
     * @return mixed
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * @param mixed $name
     */
    public function setName($name)
    {
        $this->name = $name;
    }

    /**
     * @return mixed
     */
    public function getError()
    {
        return $this->error;
    }

    /**
     * @param mixed $error
     */
    public function setError($error)
    {
        $this->error = $error;
    }

    /**
     * @return mixed
     */
    public function getIdentifiant()
    {
        return $this->identifiant;
    }

    /**
     * @param mixed $identifiant
     */
    public function setIdentifiant($identifiant)
    {
        $this->identifiant = $identifiant;
    }

    /**
     * @return mixed
     */
    public function getData()
    {
        return $this->data;
    }

    /**
     * @param $data
     * @return $this
     */
    public function setData($data)
    {
        $this->data = $data;
        return $this;
    }

    /**
     * @return mixed
     */
    public function getMessage()
    {
        return $this->message;
    }

    /**
     * @param mixed $message
     */
    public function setMessage($message)
    {
        $this->message = $message;
    }

    /**
     * @return \DateTime
     */
    public function getDateCreated()
    {
        return $this->dateCreated;
    }

    /**
     * @param $dateCreated
     * @return $this
     */
    public function setDateCreated($dateCreated)
    {
        $this->dateCreated = $dateCreated;
        return $this;
    }
}

extend row-rendering (add class and data-id)

Hi,
I use DataTables and combined it with "open dialog on doubleclick". Because of lots of Entities (>20k) I switched to your Bundle. Everything works fine but I have to extend the of each row with css classes and a data-id property.

Old Code:
`{% for h in entities %}

{{ h.name }}
{{ h.description }}

{% endfor %}

<script> $(document).on("dblclick", ".opdia", function () { var editId = $(this).data('id'); var res = ""; var success = false; var url = "XXXXXXXXXX?xid=" + editId; $.when( $.ajax({ type: 'GET', url: url, success: function (response) { res = response; success = true; }, error: function () { //handle error }, })).then(function () { if (success) { $("#myModal").html(res).modal("show"); } }); }); </script>

`

Is it possible to customize the row-rendering?

Twig Problem

Hi,
if i use this format

<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/r/dt/dt-1.10.9/datatables.min.css"/>
<script type="text/javascript" src="//code.jquery.com/jquery-2.1.4.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/r/dt/dt-1.10.9/datatables.min.js"></script>

{{ datatable({
        'js' : {
            'ajax' : path('route_for_your_datatable_action')
        }
    })
}}
{{ datatable({
        'js' : {
            'ajax' : path('route_for_your_datatable_action')
        }
    })
}}

I don't see any

If i use this

% block body %}
    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/r/dt/dt-1.10.9/datatables.min.css"/>
    {{ datatable_html({
            'id' : 'dta-offres'
        })
    }}

{% endblock %}

{% block javascripts %}
<script type="text/javascript" charset="utf8" src="//code.jquery.com/jquery-1.10.2.min.js"></script>
<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/1.10.9/js/jquery.dataTables.js"></script>
{{ datatable_js({
        'id' : 'dta-offres',
        'js' : {
            'dom': '<"clearfix"lf>rtip',
            'ajax': path('route_for_your_datatable_action'),
        }
    })
}}
{% endblock javascripts %}

I see the results but i have the reinitialise datatable error
DataTables warning: table id=dta-offres - Cannot reinitialise DataTable. For more information about this error, please see http://datatables.net/tn/3

Second question
how can I have a rendering as in your example image?

Symfnoy3 - compatible ?

hello, can we using bundle with symfony3 ๐Ÿ‘
because after installing bundle i have this error :

Unable to parse file "/var/www/html/Symfony/vendor/waldo/datatable-bundle/DependencyInjection/../Resources/config/services.xml".

how fix it please ?

Datatable editor

Hello, I am using your DatatableBundle and I want to be able to edit it, I would appreciate any help
Thank you

Alias detection does not respect "AS"

Took me an hour to find out, why simple field

$x->setFields([
 'Entities' => 'SIZE(x.entities)'
]);

Throws an error.

Notice: Undefined index: SIZE(x_entities)

According to docs, it needs to be aliased, so I tried

$x->setFields([
 'Entities' => 'SIZE(x.entities) AS entities'
]); 

to receive:

Notice: Undefined index: SIZE(x_entities) AS entities

Had to read the code to find out that this is not DQL, it is case-sensitive and to work - aliasing keyword has to be written lowercase:

$x->setFields([
 'Entities' => 'SIZE(x.entities) as entities'
]); 

I believe that aliasing should be respected case-insensitive. Or, at least, there should be a bold statement in the docs ๐Ÿ˜‰

You should set a datatable id in your action with "setDatatableId" using the id from your view

Hi,
I've an issue when implementing the datatable bundle.
I've followed the doc, set up the bundle with composer etc.

In my controller :

public function userInformationsAction(Request $request, $mode = null') {
        $this->initManagerAndSession();
        $user = $this->getUser();

        if ($mode == 'showInvoices') {
            return $this->render('NutriFitBundle:User:userInformations.html.twig', [
                'user' => $user
            ]);
        } else {
            throw $this->createNotFoundException();
        }
    }

/**
     * Create DataTable for invoices list
     * 
     * @return unknown
     */
    private function computeDataTable() {
        $dt = $this->get('datatable')
                    ->setEntity('NutriFitBundle:Facture', 'f')
                    ->setDatatableId('invoice')
                    ->setFields(
                            [
                                'Reference' => 'f.reference',
                                'Date' => 'f.creationDate',
                                'Amount' => 'f.amount',
                                'Shipping Data' => 'f.shippingDate',
                                'Payment Type' => 'f.paymentType',
                                "_identifier_"  => 'f.id'
                            ]
                    )
                    ->setWhere('f.user = :user',
                            ['user' => $this->getUser()]
                    )
                    ->setOrder('f.creationDate', 'desc');

        return $dt;
    }

    /**
     * Build datatable view for user invoices
     * 
     * @param Request $request
     */
    public function invoicesDataTableAction(Request $request) {
        return $this->computeDataTable()->execute();
    }

In my twig :

{{ datatable({
                    'js' : {
                        'ajax' : path('invoices_datatables')
                    }
                })
            }}

When I'm accessing to this view, I've the following error :
An exception has been thrown during the rendering of a template ("No instance found for datatable, you should set a datatable id in your action with "setDatatableId" using the id from your view")

When I'm trying to query the url action directly, I've a correct JSON :

{"draw":0,"recordsTotal":"1","recordsFiltered":"1","data":[["jrgoireg-21",{"date":"2012-01-01 00:00:00","timezone_type":3,"timezone":"Europe\/Berlin"},25.5,{"date":"2012-01-02 00:00:00","timezone_type":3,"timezone":"Europe\/Berlin"},"CB",1]]}`

Could you help me for doing it work please ?

Thanks by advance,

Regards,

Support for Responsive extension

Hi,

I'm trying to make the responsive extension work but I'm having a javascript error when activating the responsive trigger either through class or using the constructor approach as instructed on the responsive extension guide. Does this bundle support this.

Here is the js error:
TypeError: s is null

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.