GithubHelp home page GithubHelp logo

stwe / datatablesbundle Goto Github PK

View Code? Open in Web Editor NEW
356.0 42.0 242.0 2.7 MB

This Bundle integrates the jQuery DataTables plugin into your Symfony application.

PHP 70.12% JavaScript 0.86% Twig 29.02%
grid table datagrid pagination data-table datatable datatables symfony symfony-bundle inline-editing

datatablesbundle's People

Contributors

bruce17 avatar celvin avatar dchabanenko avatar dustfeather avatar eloar avatar emullaraj avatar eugenekkh avatar fdelapena avatar imanalopher avatar jojo1981 avatar knallcharge avatar lmerotta avatar lsv avatar mbartok avatar migmolrod avatar mssimi avatar mwansinck avatar nicodmf avatar noles avatar philippemilink avatar pierredup avatar przemas55555 avatar samuel4x4 avatar seb33300 avatar silviomessi avatar stephanvierkant avatar stwe avatar tjveldhuizen avatar tnajanssen avatar zgoniaiko 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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

datatablesbundle's Issues

Can't find entity

If I have one entity named with tb (tblcatalog) the line autogenerated in the class thinks it is one tabular space:

I fixed it changing the " for '

/**
* {@inheritdoc}
*/
public function getEntity()
{
#return "Catalogos\Bundle\ListadoBundle\Entity\tblcatalogos";
return 'Catalogos\Bundle\ListadoBundle\Entity\tblcatalogos';
}

Error when searching (server side)

Hello,

do any of you get a "Invalid parameter number: number of bound variables does not match number of tokens" error when using the search field ? I'm in serverside mode. It happens for all my datatables, even the simpliest.

Thanks,
Minishlink

Improve filters

Enable (implement configuration wrapper) setting custom filter for individual columns.

Basic filters:

  • LIKE search
  • exact match search
  • select with options (provided by array or by one-to-many entity relation)

Advanced filters:

  • datetime
    • options: today, this week, this month, this year

How to add custom database functions/extensión

I'm editing DatatableQuery.php to get more results in Spanish global searches, I've created a unaccent extension un my database side but I'm getting the error "[Syntax Error] line 0, col 155: Error: Expected known function, got 'unaccent' "

    // global filtering
    if ("" != $globalSearch) {
        $orExpr = $pivot->expr()->orX();
        for ($i = 0; $i < $counter; $i++) {
            if ("true" == $this->requestParams["columns"][$i]["searchable"]) {
                $searchField = $this->allColumns[$i];

                /**************************/          
                // unaccent is my custom extensión created in PostgreSQL to remove accents
                $orExpr->add($pivot->expr()->like( 'LOWER(unaccent('.$searchField.'))', "?$i" ));
                /**************************/



                $string = preg_replace('/\s+/', '%', $globalSearch);

                /**************************/
                //cleanChars is a method to remove accents in PHP side
                $string = strtolower($this->cleanChars($string));
                /**************************/

                $searchTarget="%".$string."%";
                $pivot->setParameter($i, $searchTarget );
            }
        }

        $pivot->where($orExpr);

    }

Decoupling JS from HTML - functions have been forgotten

I try to use this bundle for several days. It seems really great.

I've got a first issue with it : I use the decoupling option (much more tidy) and try to render a boolean column.
Answer : Uncaught ReferenceError: render_boolean is not defined

In fact, I found no way to include "render_functions.html.twig" with this option. How can I do it ?

Invisible column property not working

According with documentation examples, this column shouldn't be rendered with this option:

// Server-side example
$this->getColumnBuilder()
    ->add('somecolumn', 'column', array('visible' => false));

In order to pass some column name to route_parameters these column names are needed to be provided to the column builder but sometimes are not desired to be rendered (e.g. remote column IDs), so fixing this feature without hiding it with class hacks is a nice one to have.

Also, doing display:none to th and td instead of skipping rendering "conflicts" with datatables-responsive extension, showing a "plus" to show this hidden column, which it is not desired too.

Custom query

Do you see a good way to get a custom query with server side enabled, like calculating stuff in the select and render this in the datatable?

custom function column

Hi,

I didn't manage to use a function form an entity instead of an attribute for a column. Is there a way to do it?

Thank you

Filtering non string attribute error (PostgreSQL)

Searching on column, that entity attribute is not string, LIKE operator is not working a throwing error:

SQLSTATE[42883]: Undefined function: 7 ERROR: operator does not exist: integer ~~ unknown

HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts.

(->setServerSide(true))

Relational error

DatatableData.php setAssociations change to:

if (!array_key_exists($targetTableName, $this->selectColumns)) {
$this->addSelectColumn($targetMeta, $targetRootIdentifier, $columnTableName);

            $this->addJoin(
                array(
                    'source' => $metadata->getTableName() . '.' . $column,
                    'target' => $columnTableName
                )
            );
        }

because if you try to get a relation of an relation, it will crash right now and with the new function not.

Multi-column filtering

I'm doing this {code} to replace blank spaces with '%' and casting, and unaccent the search string to improve the filtering:

 $orExpr->add($pivot->expr()->like( 'LOWER(unaccent(CAST('.$searchField.')))', "?$i" ));
      $string = preg_replace('/\s+/', '%', $globalSearch);
      $string = strtolower($this->cleanChars($string));
      $searchTarget="%".$string."%";
      $pivot->setParameter($i, $searchTarget );

but how could I concatenate all the columns to get more results? by example:

General Searbox: Lucas Andreea Smi th -----> %lucas%andreea%smi%th
column1 | column2
Lucas | Andreea Smith

new feature WaitFor rendering

datatableheaders

I had some problems when I wanted to see the datatable inside a bootstrap tabs or formWizard because by default datatable draws twice the headers when is inside certain kind of elements, I think the problem is because in the tabs plugin is running a new script to make the tabs works and it would be trying to recreate the datatable, I added a feature to wait "n" milliseconds before render sg/datatable, and it works pretty well, I want to share it and if you want you can send it to master branch.

datatable.html.twig

     setTimeout(function(){....

            if ( $.fn.dataTable.isDataTable(selector) ) {
                //DataTable named (selector) already exists 
            }else {
                var oTable = $(selector).DataTable(defaults);
            }

full twig view: http://paste.ubuntu.com/8405905/

/****************/

features.html.twig

{% if view_features.waitFor %}
    "waitFor": "{{ view_features.waitFor }}",
{% else %}
    "waitFor": "5",

{% endif %}

/*******************/

Features.php

http://paste.ubuntu.com/8405953/

/***************_/ USE /_*************/

$this->getFeatures()
->setServerSide(true)
->setProcessing(true)
->setwaitFor(500); /Waiting for 500 miliseconds to before start to render/

Pagination isn't working

Hi, I'm trying to use your bundle in my project but I get a weird pagination even if I only get 3 results from DB and that is wrong. See the attached image for further info:

7-31-2014 12-03-58 am

Did I miss something from docs or is this a issue from Bundle? Also I get this message:

Showing 0 to 0 of 0 entries (filtered from NaN total entries)

How I can fix that? This is my composer.json just in case you need it:

"require": {
    "php": ">=5.3.3",
    "symfony/symfony": "2.5.*",
    "doctrine/orm": "~2.2,>=2.2.3",
    "doctrine/doctrine-bundle": "~1.2",
    "twig/extensions": "~1.0",
    "symfony/assetic-bundle": "~2.3",
    "symfony/swiftmailer-bundle": "~2.3",
    "symfony/monolog-bundle": "~2.4",
    "sensio/distribution-bundle": "~3.0",
    "sensio/framework-extra-bundle": "~3.0",
    "incenteev/composer-parameter-handler": "~2.0",
    "ob/highcharts-bundle": "1.1.*",
    "friendsofsymfony/user-bundle": "~2.0@dev",
    "friendsofsymfony/jsrouting-bundle": "~1.1",
    "doctrine/doctrine-fixtures-bundle": "dev-master",
    "fresh/doctrine-enum-bundle": "v2.5",
    "mopa/bootstrap-bundle": "dev-master",
    "twbs/bootstrap": "dev-master",
    "knplabs/knp-paginator-bundle": "dev-master",
    "knplabs/knp-menu-bundle": "dev-master",
    "knplabs/knp-menu": "2.0.*@dev",
    "datatables/datatables": "dev-master",
    "moment/moment": "dev-master",
    "sg/datatablesbundle": "dev-master"
}

Any help or advice?

Change abstractColumn setOptions

Hi,

The setOptions method doesn't allow to set everything(like MRender), why not use something like:
/**
* {@inheritdoc}
*/
public function setOptions(array $options)
{
foreach ($options as $name => $value) {
$method = "set".$name;
if (method_exists($this, $method)) {
$this->$method($value);
}
}
return $this;
}

or add more options.

[Insight] Usage of a function in loops should be avoided

in Datatable/Data/DatatableData.php, line 245

This loop uses a function. To avoid the overhead of executing the function n times, you should precalculate it before the loop.

    {
        // start with the tableName and the primary key e.g. 'Season' and 'id'
        $this->addSelectColumn($this->metadata, $this->rootEntityIdentifier);
        $this->addAllColumn($this->tableName . '.' . $this->rootEntityIdentifier);

        for ($i = 0; $i < count($this->requestParams["columns"]); $i++) {

            if ($this->requestParams["dql_" . $i] != null) {
                // Get the name of the column
                $column = $this->requestParams["dql_" . $i];

Posted from SensioLabsInsight

A way to translate cell values

Which could be the best way to pass cell contents to getTranslator for specified columns?

Something like:

        $this->getColumnBuilder()->set
                ->add("status.name", "column", array(
                    // (...)
                    "translate" => "optional_catalog_name" // or true for default
                    // (...)
                ))

Or having a special column type name, from "column" to "translate" then optionally set a "catalog" property in the array.

I could develop this feature and request a pull if interested.

Icon does not display in action column

Hello,

I'm trying for few times to display the "glyphicon glyphicon-edit" with the same way of your example but in vain.
Indeed, the icon does not want to display and the column still stay empty without any button inside.

There is my code :

$this->getColumnBuilder()
        ->add("username", "column", array(
            "title" => "Username",
            "searchable" => true,
            "orderable" => true,
            "visible" => true,
            "class" => "active",
        ))
        ->add("email", "column", array(
            "title" => "E-mail",
            "searchable" => true,
            "orderable" => true,
            "visible" => true,
            "class" => "active",
        ))
        ->add(null, "action", array(
            "title" => "Actions",
            "start" => '<div class="wrapper">',
            "end" => '</div>',
            "actions" => array(
                array(
                    "route" => "user_list",
                    "icon" => "glyphicon glyphicon-edit",
                    "attributes" => array(
                        "rel" => "tooltip",
                        "title" => "Edit",
                        "class" => "btn btn-primary btn-xs",
                        "role" => "button"
                    ),
                    "confirm" => true,
                    "confirm_message" => "Are you sure?",
                    "role" => "ROLE_ADMIN",
                    "renderif" => array(
                        "visible"
                    )
                ),
            )
        ));

Do you know where might be my mistake ?

Thanks by advance,

Getting property from join table

Hi,
There is single table inheritance hierarchy of classes. I have removed getters and setters here to make source code shorter

/**
 * @ORM\Entity
 * @ORM\InheritanceType("SINGLE_TABLE")
 * @ORM\DiscriminatorColumn(name="entity_class", type="string")
 * @ORM\DiscriminatorMap({
 *      "AppBundle\KnowledgeBase\Entity\Log": "LogEntity",
 *      "AppBundle\KnowledgeBase\Entity\Article": "ArticleLogEntity",
 *      "AppBundle\Entity\KnowledgeBase\Template": "TemplateLogEntity"
 * })
 *
 *
 * @ORM\Table(name="knowledge_base_log")
 */
class LogEntity
{
    use ORMBehaviors\Timestampable\Timestampable;

    protected $entity;
    /**
     * @ORM\Id
     * @ORM\GeneratedValue
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="integer")
     */
    private $entity_id;

    /**
     * @ORM\Column(type="text", nullable=true)
     */
    protected $changes;

    /**
     * @ORM\Column(type="string", nullable=true)
     */
    protected $locale;

    /**
     * @ORM\Column(type="string")
     */
    protected $author;

    /**
     * @ORM\Column(type="string")
     */
    protected $action;   
}


/**
 * @ORM\Entity
 */
class ArticleLogEntity extends LogEntity
{
    /**
     *
     * @ORM\ManyToOne(
     *      targetEntity="AppBundle\Entity\KnowledgeBase\Article",
     *      inversedBy="AppBundle\Entity\KnowledgeBase\Log\LogEntity"
     * )
     *
     * @ORM\JoinColumn(
     *     name="entity_id",
     *     referencedColumnName="id",
     *     nullable=false
     * )
     */
    protected $entity;

}


/**
 * @ORM\Entity
 */
class TemplateLogEntity extends LogEntity {
    /**
     *
     * @ORM\ManyToOne(
     *      targetEntity="AppBundle\Entity\KnowledgeBase\Template",
     *      inversedBy="AppBundle\Entity\KnowledgeBase\Log\LogEntity"
     * )
     *
     * @ORM\JoinColumn(
     *      name="entity_id",
     *      referencedColumnName="id",
     *      nullable = false
     * )
     */
    protected $entity;
}

db

Here TemplateLogEntity and ArticleLogEntity have $entity property, which joins to different target entities.
I want to get properties of those target entities in datatable somehow like this.

$this->getColumnBuilder()
->add("entity.entityTitle", "column", array(
                    "title" => "Entity title"
                ))

Is it possible and how should it be done? I killed a week on this, and help is really appreciated, thanks

Translator instead of TranslatorInterface

In Twig/DatatableTwigExtension.php and Datatable/View/AbstractDatatableView.php
you must use Symfony\Component\Translation\TranslatorInterface
instead of Symfony\Bundle\FrameworkBundle\Translation\Translator to make it work with Symfony 2.6

Improve flexibility

Hello. First of all thanks for the bundle.
It would be great if you review architecture, because for now its very hard to replace or improve some features. For example, I can't easy add new column types, because most classnames are hardcoded and also there are a lots of private properties.
Thanks.

command datatable:generate:class error/bug

When I use:
app/console datatable:generate:class --entity=CatalogosInstitucionBundle:catinstitucion

I get this message:
[Twig_Error_Loader] The "../vendor/sg/datatablesbundle/Sg/DatatablesBundle/Command/../Resources/views/skeleton" directory does not exist.

That's because GNU/Linux is key-sensitive and the folder "skeleton" in the vendors folder is "Skeleton" I just made one copy in lowercase but I think the problem comes from other place maybe the command line structure.

2 Datatables on the same view

I'm using your DatatablesBundle, great work. It is really useful.

I was looking at the documentation, and didn't see any mention on how to insert two or more Datatables on one view. Is this possible? if not, what would I need to do this?

This is my first project in Symfony 2.

Thank you

Ordering by a datetime as 'timeago'

Hi, this is a great bundle - I got some useful results very quickly. However, I'm having an issue with the sorting of a date/time field that I'm displaying as a 'timeago' (eg: '2 hours ago').

How can I have a timeago field sort by the underlying date?

Translation not working

Hello,

I successfully managed to install and use this bundle, but translation of datatable elements doesn't work.
I have the name of the text (for example datatables.datatable.lengthMenu or datatables.datatable.search) instead of the translation.

In app/config/config.yml I have :
translator: { fallback: %locale% }
default_locale: "%locale%"

Thanks for your help!

multiselect checkbox assumes the first ajax column corresponds to the first data column

e.g.: Doctrine for the /results JSON data can return id column in another place when the relation has some inheritance and this can't be controlled: {username="foo", email="bar", id=1} . In this case it will assign foo (username) instead of 1 (id) to the checkbox, even when the first column is "id", making the repository->find() for bulk actions fail.

ErrorException

ErrorException: Catchable Fatal Error: Argument 1 passed to Sg\DatatablesBundle\Twig\DatatableTwigExtension::__construct() must be an instance of Symfony\Bundle\FrameworkBundle\Translation\Translator, instance of Symfony\Component\Translation\IdentityTranslator given

any idea where is a problem ? im trying install your bundle in dev-master version with sf 2.5

How to render or not a button?

using "renderif" is only if a column exists no?

but I want to render or no a button if a role has a special flag activated, or evaluate if a function returns true or false.

Customization support for multiselect column

(Enhancement)
Support a mechanism to set some values like width or className (apart of the existing class set) to the column, as currently looks difficult to customize it when set on server side.

Datatable service class

Hi,

what about registrating datatable class as service ?

In example i see only:

    sg_datatables.media:
        class: Component\MediaBundle\Datatable\MediaDatatable
        tags:
            - { name: sg.datatable.view }

there is no any registered service with name sg.datatable.view

but i have :

class MediaDatatable extends AbstractDatatableView

and AbstractDatatableView constructor looks like this:

public function __construct(TwigEngine $templating, Translator $translator, RouterInterface $router, array $defaultLayoutOptions)

so i give logicaly error like this:

An exception has been thrown during the rendering of a template ("Catchable Fatal Error: Argument 1 passed to Sg\DatatablesBundle\Twig\DatatableTwigExtension::datatableRender() must be an instance of Sg\DatatablesBundle\Datatable\View\AbstractDatatableView, null given .......

probably i missed something.. any idea please ? thx

How can I set a limit to the query?

I'm trying to use this bundle on a pretty big db table. It takes ages to load, so I was trying to set a limit in the default query.

I tried to add a "setMaxResult" on the callback function (inside the indexResultsAction()), but seems like it's ignored and it still returned all data. I'm not sure if this is the right approach.

Does anyone know how to add a limit to the result in order to speed up the data retrieval?

// Callback example
$function = function($qb)
{
//$qb->andWhere("Post.visible = true");
$qb->setMaxResults(100);
};

Thanks very much in advance.

Mauro

Define the good entity manager

Hi, i use multiple entity manager. In my controller i don't use the default entity manager, how can i use the good entity mangager in indexResultsAction() function in my controller?
Thanks

Actions column not rendering actions in wrapper block

After trying master which merges the 0.5.2 multiaction column with single action by following documentation examples and columns documentation, looks like it does not render HTML content inside the wrapper, just showing the empty Actions column with the start and end wrapper code only. I've verified route and parameters exist, tried to add/remove role and renderif but still renders nothing.

Use datatables with non entity datas

Hi there,

First of all, I use Datatables bundle and it works great, thanks for your job.

However, I've a question.
I need to display in a datatable datas which are not coming from an entity but from a LDAP.
So I need to create a method which will build an array or object containing every entries returned by the LDAP.
So is it possible to display datas from a custom method and not an entity ?
If it is, could you give me the way to do it right please ?

Thanks by advance,

Regards,

responsive table

Hi, i want to use datatable with responsive option, how can i add this option?
Thanks :)

Setup multiselect fails

when I did enable the multiselect option, the grid stop working, I don't know if it is a bug or I have to do something special, but I fixed it adding:

{% if view_multiselect.enabled %}
d.dql_{{ counter }} = "";
{% endif %}

in vendor/sg/datatablesbundle/Sg/DatatablesBundle/Resources/views/Datatable/ajax.html.twig

{% if view_features.serverSide %}
"serverSide": true,
"ajax": {
"url": "{{ view_ajax.url }}",
"data": function(d) {
{% set counter = 0 %}
{% for column in view_columns %}
d.dql_{{ counter }} = "{{ column.property }}";
{% set counter = counter + 1 %}
{% endfor %}

        {% if view_multiselect.enabled %}
            d.dql_{{ counter }} = "";
        {% endif %}

    },
    "type": "{{ view_ajax.type }}"
},

{% else %}
"serverSide": false,
"data": {{ view_data|raw }},
{% endif %}

How to add custom where?

I have a field in entity to filter the state of the record
$qb->andWhere("tblsolicitudes.state = '1' "); //It works very well

but now I need to filter using a related entity.
something like this:

$qb->andWhere("tblsolicitudes.cservId.cservPrice > 0 "); // It doesn't works, how should I do it?

Thanks for you help.

Looks good!

Hi,

way of using datatables in this bundle look very good. What is the current status?

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.