Skip to content

Instantly share code, notes, and snippets.

@filhodanuvem
Last active December 11, 2015 07:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save filhodanuvem/4569011 to your computer and use it in GitHub Desktop.
Save filhodanuvem/4569011 to your computer and use it in GitHub Desktop.
DataTablesBundle - documentation

1 - Basic usage

Creating the DataTable Class

At first, we need create the entity that represents your datatables. This table will contain instances of a same type.

<?php    

// the simple entity (usage for doctrine, for example)  
class User
{
    // attributes, similiar on DataTable Class columns (below). 
    protected $id;
    protected $name;
    protected $date;

    public function __construct($id, $name, $date)
    {
        $this->id = $id;
        $this->name = $name;
        $this->date = $date;
    }

    /* 
    * IMPORTANT!!! Here, this class contains the set and get accessors, it's used in package instead of reflection 
    * to that pseudo attributes can be used on tables.
    */

}
<?php
// this is the DataTable class
Class UserTable extends \Saturno\DataTablesBundle\Element\Table
{
    public function configure()
    {
        $this->hasColumn('id','Code')
            ->hasColumn('name','Name' )
            ->hasColumn('date','Birthday');
    }
}

Coding your action

<?php 
        // into action controller  ...
        
        // Use factory service to get your DataTable 
        $factory = $this->get('saturno_datatables_factory');
        $table = $factory->getTable('AcmeDemoBundle:User');
        // create, get or search your entities, probably you use repositories for it 
        $user1 = new User(1,'Joseph','2013-05-23');
        $user2 = new User(2,'Hellena','1988-06-27');
        // insert the entities into datatable 
        $table->setBody(array(
            $user1,
            $user2
        ));

        // pass to table to the view, normally 
        $vars = array(
            'table' => $table,
        );
        $html = $this->renderView('SaturnoDataTablesBundle:examples:simple.html.twig', $vars);

        $response = new \Symfony\Component\HttpFoundation\Response();
        $response->setContent($html);

        return $response;

Magic in the view !!!

In the view, on twig, use the object table

    {# rendering the datable #}
    {{  table_render(table) }}

    {# using the magic javascript default #}
    {{ table_render_js(table) }}
    

2 - Entity with a aggregate

Probably, your entity contains other entity, to represent this case in a DataTable, we use the notation . (dot) to access other object. This is so easy.

<?php

Class ProductTable extends \Saturno\DataTablesBundle\Element\Table
{
    public function build()
    {
        $this->hasColumn('id','Code')
            ->hasColumn('name','Name' )
            ->hasColumn('user.name','User'); 
            //here, we see that Product entity contains a User entity, and this table will show User's name 
    }
     
     // ...others methdos
}

3 - Using Ajax

Maybe, you have many data in a table of database and you can't get all in one query. In DataTables we resolve this problem using ajax, when the each request, we have any entities, instead of all. This example uses doctrine orm, so, that entity User contains annotations right now!

Configuring the DataTable

<?php 
// ... into the DataTable Class

public function getDefaultOptions()
{
    return array(
        'url' => 'acme_example_datatables_ajax' // url is the target route 
	);
}

In controller, we need two actions, one that show the table normally (but without the body, obviously) and other that will return the content to DataTable. See bellow:

<?php

Class UserController 
{
    /**
    * @Route("/ajax")
    */
    public function ajaxAction()
    {
        $factory = $this->get('saturno_datatables_factory');
        $table = $factory->getTable('AcmeExampleDataTablesBundle:UserAjax');

        $vars = array(
            'table' => $table,
        );
        $html = $this->renderView('SaturnoDataTablesBundle:examples:simple.html.twig', $vars);

        $response = new \Symfony\Component\HttpFoundation\Response();
        $response->setContent($html);
        // show the table normally 
        return $response;
    }
    
    /**
    * see that this is a target of DataTable
    * @Route("/request", name="acme_example_dataTables_ajax");
    */
    public function requestAction()
    {

        // get table
        $factory = $this->get('saturno_datatables_factory');
        $table = $factory->getTable('AcmeExampleDataTablesBundle:UserAjax');

        // use table into request
        $request = $this->get('saturno_table_request');
        $request->format($table);

        // call the repository method
        $em = $this->getDoctrine()->getEntityManager();
        $repo = $em->getRepository('AcmeExampleDataTablesBundle:User');
        $users = $repo->getAll($request);

        // pass the data to the table and insert this table on response
        $table->setBody($users);
        $response = new \Saturno\DataTablesBundle\HTTP\Response($table);
        return $response;
    }

}

Notice that requestAction we use a Respositoy normally to catch users from database. the method getAll these repository receives a Request object, because interactions of user in browser change our query (for example, on clicking in a header, we need reorder the data =). DataTablesBundle contains a Trait Repository that provide many methods that resolve this problems of ordering, filtering, set limit and etc.

<?php
class UserRepository extends EntityRepository
{
	use \Saturno\DataTablesBundle\Traits\Repository; // insert trait

	public function getAll(Request $request)
	{
		$qb = $this->createQueryBuilder('t');
		// filter method make all, it's magic! =) 
		$this->filter($qb, $request);
		return $qb->getQuery()->getResult();
	}
}

DataTablesBundle

DataTablesBundle is a symfony package to create and manage (of easy way) tables using datatables jquery plugin and (mainly doctrine's) entities. For now, it's only project to fun in a alpha version. In the future, it will be in composer and ready to the production =)

Prerequisites

  • Doctrine 2.1+
  • PHP 5.4+

Documentation

The bulk of the documentation is stored in the Resources/doc/index.md file in this bundle:

Read the Documentation for master

License

Saturno\DataTablesBundle Copyright (C) 2013 Claudson Oliveira

This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/.

Getting start with DataTablesBundle

Configuring

Call the javascript plugins and styles in the twig template

{% javascripts
    '@SaturnoDataTablesBundle/Resources/public/js/jquery.min.js'    
    '@SaturnoDataTablesBundle/Resources/public/js/jquery.dataTables.min.js'
%}
    <script src="{{ asset_url }}"></script>
{% endjavascripts %}
{% stylesheets 'bundles/saturnodatatables/css/*' filter='cssrewrite'
    '@SaturnoDataTablesBundle/Resources/public/css/jquery.dataTables.css'
%}
    <link rel="stylesheet" href="{{ asset_url }}" />
{% endstylesheets %}

Usage guide

Roadmap

  • Work better with tests
  • Write the command cli that will to create DataTables classes
  • Improve Trait used by Repositories (resolve many problems with aliases)
  • Use Travis
  • Create the subpackage of filter (it's awesome and ready \o/ )
  • Install by composer
  • Write the JqGridTable using Saturno\Bridge\Table =)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment