Git Product home page Git Product logo

zfc-datagrid's Introduction

Datagrid/Datatable module for Laminas Framework (formerly Zend Framework)

Master Branch Build Status Coverage Status Scrutinizer Code Quality

Latest Stable Version Latest Unstable Version License

Join the chat at https://gitter.im/zfc-datagrid/Lobby Total Downloads Monthly Downloads

A datagrid for Laminas where the data input and output can be whatever you want...:-)

Over 400 tests and 1000 assertions testing the stability currently!

If you need help, please use following ressources

If you want to help out on this project:

Features

  • Datasources: Doctrine2 (QueryBuilder + Collections), Laminas\Db, PhpArray, ... (others possible)
  • Output types: jqGrid, Bootstrap table, PDF, Excel, CSV, console, ... (others possible)
    • Bootstrap table with Daterange Filter need to load manually js and css
  • different column types
  • custom formatting, type based formatting (string, date, number, array...)
  • column/row styling for all or based on value comparison
  • column filtering and sorting
  • external data can be included to the dataset (like gravator or any other)
  • pagination
  • custom toolbar / view
  • ...

Installation

Install it with composer

composer require zfc-datagrid/zfc-datagrid -o

NOTE: with 1.x we dropped support for other installation technics. Especially the ZF2 autoloading was dropped. You just need to switch to composer installation, which will make your life easier, since it comes with all needed features

Add ZfcDatagrid to your config/application.config.php

Finally create the folder: data/ZfcDatagrid

You can continue

Test if it works

NOTE: This needs the additional module ZfcDatagridExamples https://github.com/ThaDafinser/ZfcDatagridExamples ####Browser####

Attention! Only PhpArray works out of the box! For Laminas\Db\Sql\Select and Doctrine2 you need to install DoctrineORMModule (Doctrin2 creates the database for Laminas\Db\Sql\Select)

####Console#### If you just type php index.php a help for all commands will be shown

cd YOUR-PROJECT/public/
php index.php datagrid person
php index.php datagrid person --page 2
php index.php datagrid person --sortBys=age
php index.php datagrid person --sortBys=age,givenName --sortDirs=ASC,DESC

Continue with your own datagrid

Please read Documentation

You can also use the zfc-data-grid-plugin to create columns with an array configuration, instead of objects!

Screenshots

ScreenShot ScreenShot

zfc-datagrid's People

Contributors

alessandropietrobelli avatar bitdeli-chef avatar blacktemplar avatar cbastienbaron avatar e-belair avatar fragote avatar igorhaf avatar imonteiro avatar jonathangreco avatar keanor avatar kokspflanze avatar locutusofpenguin avatar lorenzoferrarajr avatar nsenkevich avatar olexp avatar popovserhii avatar prolic avatar rezix avatar thadafinser avatar vex avatar vixriihi avatar webdevilopers avatar weckx avatar zeineddin avatar

Stargazers

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

Watchers

 avatar  avatar  avatar  avatar  avatar

zfc-datagrid's Issues

jqGrid: Custom-Filtering

From @creifferscheid on June 30, 2014 9:15

Hey,
thanks for the great bundle, but I got stuck with a small bug?!

We want to use the jqGrid multipleSearch - function:

multipleSearch:true,
multipleGroup:true

But it doesn't work because the POST is different to a normal search-operation.
This is a piece of POST Data using the multipleSearch-filtering

isSearch: true
filters:{"groupOp":"AND","rules":[{"field":"title","op":"cn","data":"ff"}]}
searchField:
searchString:
searchOper:

And for the simple Search

isSearch:true
title:fff

I think there's an error in the Renderer?

Copied from original issue: ThaDafinser/ZfcDatagrid#123

Cannot inject custom formatter

From @webdevilopers on May 22, 2014 14:54

Though a column can use translation setting the setTranslationEnabled() method to true I need to translate my value inside a custom formatter.

This is more of Question than an Issue.

Since this is my DI attempt I tried to inject the viewRenderer into my custom formatter inside my module.config.php:

    'service_manager' => array(
        'factories' => [
            'ContractStateFormatter' => function($sm) {
                $viewRenderer = $sm->get('ViewRenderer');
                $contractStateFormatter = new \Application\Datagrid\Column\Formatter\ContractState();
                $contractStateFormatter->setView($viewRenderer);
                return $contractStateFormatter;
            }
        ]
    ),

Successfully setting the formatter on the column:

        $col = new Column\Select('state_name');
    $col->setLabel('State');
        $col->setWidth(5);
        $contractState = $this->getServiceLocator()->get('ContractStateFormatter');
        $col->setFormatter($contractState);
        #$col->setFormatter(new Formatter\ContractState()); // working fine
        $col->setFilterDefaultValue($state);
        $col->setTranslationEnabled(true);
        $grid->addColumn($col);

As you can see before the DI the formatter was working fine.

Here is the formatter:

<?php
namespace Application\Datagrid\Column\Formatter;

use ZfcDatagrid\Column\Formatter\AbstractFormatter;
use ZfcDatagrid\Column\AbstractColumn;

class ContractState extends AbstractFormatter
{
    protected $validRenderers = array(
        'jqGrid',
        'bootstrapTable'
    );

    protected $view;

    public function setView($view)
    {
        #echo $view->translate('Home');        
        #$this->view = 'test';
        $this->view = $view;
    }

    public function getView()
    {
        return $this->view;
    }

    public function getFormattedValue(AbstractColumn $column)
    {
        $row = $this->getRowData();

$this->view->translate($row['state_name']));
        $html = sprintf('<span class="state_name">%s</span><br>', $row['state_name']); // translation getTranslator()
        // some custom formatting
        return $html;
    }
}

The setting works fine, the translation works fine. But though everything worked fine before I now get the following error:
Could not save the datagrid cache. Does the directory "/home/.../Zend/workspaces/DefaultWorkspace10/PQ2/data/ZfcDatagrid" exists and is writeable?

This actually makes no sense, right? Maybe the problem is caused by some kind of overhead or conflict with the view attribute. But I couldn't find any conflict inside the formatter.

Again, this is my first DI attempt. Please tell me if my approach is wrong.
Thanks

Copied from original issue: ThaDafinser/ZfcDatagrid#111

Doctrine OneToMany related entities are displayed as a single row each instead of one combined row only

From @webdevilopers on May 5, 2014 12:32

I have an contract entity with many items:

/**
 * @ORM\Entity(repositoryClass="Application\Entity\Repositories\ContractRepository")
 * @ORM\Table(name="contracts")
 */
class Contract
{
...
    /**
     * @ORM\OneToMany(targetEntity="Application\Entity\ContractItem", mappedBy="contract")
     */
    private $items;
...
}

/**
 * @ORM\Entity
 * @ORM\Table(name="contract_items")
 */
class ContractItem
{
...
    /**
     * @ORM\ManyToOne(targetEntity="Application\Entity\Contract", inversedBy="items")
     * @ORM\JoinColumn(name="contract_id", referencedColumnName="id")
     */
    private $contract;  
}

The items column uses the phpArray type:

        $col = new Column\Select('id', 'ci');
        $col->setType(new Type\PhpArray());
        $grid->addColumn($col);

My repository uses this query:

        $queryBuilder = $this->_em->createQueryBuilder();
        $queryBuilder->select('c')
            ->from('Application\Entity\Contract', 'c')
            ->leftJoin('c.items', 'ci')
            ->andWhere('c.id = 2')
            ->orderBy('c.' . $orderBy, $order)
        ;

        $q = $queryBuilder->getDql();
        #return $query = $this->_em->createQuery($q);
        return $queryBuilder;  

Instead of return a single row per contract entity and filling the items column with an pre-formatted array of items, jqgrid renders a single per each per item.

For debugging I reduced my query to a single ID with 163 items.
My jqgrid genereates 163 rows.

When doing a count on the Doctrine query I get 1 item.
In the background we know that Doctrine would indeed select 163 rows but build one object.

Is my configuration wrong?

Maybe related to issue ThaDafinser/ZfcDatagrid#76.

Copied from original issue: ThaDafinser/ZfcDatagrid#98

Package phpoffice/phpexcel is abandoned

Package phpoffice/phpexcel is abandoned, you should avoid using it. Use phpoffice/phpspreadsheet instead.

maybe someone has time for this migration.

PS: please for develop, that will be 2.0+

Allow changing column type's `filterDefaultOperation`

The column types are pretty strict when it comes to the filterDefaultOperation. If you want to change that operator you're gonna have to create your own, custom type. That's a bit too strict if you ask me so I want to propose the following change:

Allow changing the column type's filterDefaultOperation with a setter. I believe there is no harm in doing so and it makes the column type that more flexible and more easy to use.

I'll be making a PR for this.

Configuration conflict when set non-default cache adapter

Exception thrown when I try to set memcache adapter for ZfcDatagrid in my app:

Zend\Stdlib\Exception\BadMethodCallException: The option "cache_dir" does not have a callable "setCacheDir" ("setcachedir") setter method which must be defined in C:\zend\zf2app\vendor\zendframework\zend-stdlib\src\AbstractOptions.php:110

I am trying to configure adapter in my local config/autoload/zfcdatagrid.local.php

            'adapter' => [
                'name' => Zend\Cache\Storage\Adapter\Memcache::class,
                'options' => [
                    'ttl' => 720000, // cache with 200 hours,
                    'servers' => [['host' => '127.0.0.1']],
                ],
            ],

Default configuration in module.config.php

            'adapter' => [
                'name'    => 'Filesystem',
                'options' => [
                    'ttl'       => 720000, // cache with 200 hours,
                    'cache_dir' => 'data/ZfcDatagrid',
                ],
            ],

When all configurations loaded by Zend Framework, adapter settings are merged and 'cache_dir' is set for Memcache adapter which leads to exception about setter. I temporary commented 'cache_dir' in vendor. Could you fix or suggest permanent solution for this issue.

Support native ZF Event

From @popovsergiy on June 14, 2017 19:2

Add support native ZF Event Driven Architect functionality for easy functionality expansion.

use Zend\EventManager\EventManagerAwareInterface;
use Zend\EventManager\EventManagerAwareTrait;

class Datagrid implements ServiceLocatorAwareInterface, EventManagerAwareInterface
{
    use EventManagerAwareTrait;
    //...
    public function render()
    {
        $this->getEventManager()->trigger(__FUNCTION__ . '.pre', $this); // arise event
        
        if ($this->isDataLoaded() === false) {
            $this->loadData();
        }

        /**
         * Step 4) Render the data to the defined output format (HTML, PDF...)
         * - Styling the values based on column (and value)
         */
        $renderer = $this->getRenderer();
        $renderer->setTitle($this->getTitle());
        $renderer->setPaginator($this->getPaginator());
        $renderer->setData($this->getPreparedData());
        $renderer->prepareViewModel($this);

        $this->response = $renderer->execute();

        $this->isRendered = true;

        $this->getEventManager()->trigger(__FUNCTION__, $this); // arise event
    }
    //...
}

Copied from original issue: ThaDafinser/ZfcDatagrid#279

Add column does not work with array specification and QueryBuilder

From @olexp on December 31, 2014 20:48

There is a bug when I try to add column with array specification for QueryBuilder. It appears because of setSelect method run on created instance which switches selectPart1 and selectPart2 values.

thadafinser/zfc-datagrid (0.9.1)

To reproduce (in action):

        $em = $this->getServiceLocator()->get('doctrine.entitymanager.orm_default');
        $data = $em->getRepository('Application\Entity\Product')->createQueryBuilder('p');
        $grid = $this->getServiceLocator()->get('ZfcDatagrid\Datagrid');
        $grid->setTitle('Product');
        $grid->setDataSource($data);
        $grid->addColumn(array(
            'colType' => 'Select',
            'select' => array(
                'column' => 'name',
                'table' => 'p',
            ),
            'label' => 'Name',
        ));

        $grid->render();

        return $grid->getResponse();

Action failed with exception Doctrine\ORM\Query\QueryException

    [Semantical Error] line 0, col 7 near 'name.p p_name,': Error: 'name' is not defined.
    SELECT name.p p_name FROM Application\Entity\Product p

When I skip $key with 'select' value in foreach loop in Datagrid.php:652 everything works correctly.

Copied from original issue: ThaDafinser/ZfcDatagrid#151

Adding postData to / changing URL in jqGrid

From @webdevilopers on June 16, 2014 13:55

My grid starts on an URL that depends on a week GET param from an HTML5 element:
http://localhost:8000/timekeeping/overview?week=2010-W50

First I tried to add the week param to the postData:
The postData param is already implemented inside the layout:

    mtype : 'POST',
    postData: {
        <?php echo $parameterNames['columnsHidden']?>: function(){
            return $('#<?php echo $this->gridId.'_'.$parameterNames['columnsHidden']; ?>').val();
        },
        <?php echo $parameterNames['columnsGroupByLocal']?>: function(){
            return $('#<?php echo $this->gridId.'_'.$parameterNames['columnsGroupByLocal']; ?>').val();
        }
        <?php
        if(count($parametersHtml) > 0){
            echo ',';
        }
        echo implode(',', $parametersHtml);
        ?>,
    },

The imploded $parametersHtml can be found at the top:

$parametersHtml = array();
foreach($this->parameters as $name => $value){
    $parametersHtml []= $name.': \''.$value.'\'';
}

And then set the value on the grid:

        $grid->setParameters(array(
            'week' => (string) $weekParam,
                'week2' => '2014-W01',
            'foo' => 'bar',
            'foo2' => 'bar2'
        ));

Unfortunately the week param was not added to the POST request while the other params would. The problem seems to be that I already have a column named week too that is also used with groupingView.

I then tried to change the URL via:

        $url = $this->url()->fromRoute('timekeeping', array(
            'action' => 'overview',
            'week'   => $weekParam
        ));

$grid->setUrl($url);

But the grid seems to overwrite the URL at least inside the layout:

$url = $this->url(null, array(), array(), true);
if($this->overwriteUrl != ''){
    $url = $this->overwriteUrl;
}

In the end I came up with an individual layout template simply commenting out the mentioned section:

// $url = $this->url(null, array(), array(), true);
// if($this->overwriteUrl != ''){
//     $url = $this->overwriteUrl;
// }
$url = $this->url;

Though it did not end with the expected result because the URL now is completey empty:

var grid_defaultGrid = $('#defaultGrid').jqGrid({

    url: '',

Any ideas?

Copied from original issue: ThaDafinser/ZfcDatagrid#117

Should formatter keep a reference to the raw column data?

From @rumeau on August 25, 2014 17:53

Hello, I've been using the datagrid for a couple of months and i have deal with custom formatters and conditional actions.

Currently if i need to format a status column (integer), i use a custom formatter called LabelFormatter which displays the status column to a human readable status ie:

1 => '<label class="open">OPEN</label>'
2 => '<label class="closed">CLOSED</label>'

I order to add conditional values to my actions i add the status column twice, i hide the original and add a second one and add the formatter to it, then i add my showOnValue to the hidden original.

Here is my question, giving that the Formatter has a purely presentation purpose (it might not in some cases), shouldn't the showOnValue value be compared with the raw value and not with the formatted one?

This is because i shouldn't need to add the status column twice, but just once, so if i am comparing with '1', then:

1 === '<label class="open">OPEN</label>' // works only if compare is '==' as a boolean
// having 1 =  the state i want to compare with
// '<label class="open">OPEN</label>' = the formatted value of column 'status'

should be:

1 === 1
// 1 = the state i want to compare with
// 1 = the raw value of column 'status'

Is this the expected behaviour or did i missed something?

Thanks.

Copied from original issue: ThaDafinser/ZfcDatagrid#136

bootstrap daterangepicker locale usage

From @webdevilopers on May 27, 2014 14:24

Currentely you can configure the locale parameter for the Bootstrap DaterangePicker this way:

'locale' => \Locale::getDefault(),

See https://github.com/ThaDafinser/ZfcDatagrid/blob/master/docs/Configuration.md
locale: (object) Allows you to provide localized strings for buttons and labels, and the first day of week for the calendars

According to the DaterangePicker locale exprects an object:
https://github.com/dangrossman/bootstrap-daterangepicker#options

E.g.:

'locale' => [
    'customRangeLabel' => 'Eigener Zeitraum'
],

Anyway this looks like the wrong place to translations especially when you are trying to add multiple languages.

Does the DaterangePicker offer a different attempt maybe in combination with jQuery itself or its datepicker?

Copied from original issue: ThaDafinser/ZfcDatagrid#114

jqgrid paging breaks when using groupingView due to additional sortByColumns on POST request

From @webdevilopers on May 20, 2014 8:33

I added groupingView to my jqgrid layout in order to add summary on my footerrow:

var grid_<?php echo $this->gridId; ?> = $('#<?php echo $this->gridId; ?>').jqGrid({
    // ...
    grouping: true,
    groupingView : {
        groupField : ['contract_id'],
        groupSummary : [true],
        groupColumnShow : [false],
        groupText : [' '],
        groupCollapse : false,
        groupDataSorted : false,
        groupSorted: false,
        //groupOrder: ['asc']
        //groupOrder: [false]
    groupOrder: []
    },    
    // ...    

The pagination will fail with a 500 Internal Server Error and the following message from ZfcDatagrid on the POST request:
Count missmatch order columns/direction

The regular POST params without groupingView will result in:

columnsGroupBy    
columnsHidden    id,contract_id
currentPage    2
isSearch    false
itemsPerPage    5
nd    1400510371968
sortByColumns    
sortDirections   

Using groupView it will add the sortByColumns:

columnsGroupBy    
columnsHidden    id,contract_id
currentPage    2
isSearch    false
itemsPerPage    5
nd    1400510295168
sortByColumns    contract_id asc,
sortDirections 

I have tried several jqgrid groupingView setups but could not override the sortByColumns.

This issue may be related to other issues and improvements:

Copied from original issue: ThaDafinser/ZfcDatagrid#108

Filters - Extended

From @imonteiro on April 4, 2017 14:13

Hi @ThaDafinser

What do you think about these ideas, regarding the Filters:

  • Possibility to extend Filter and create custom render to column filters (the class will return the html code for the BootstrapTable)
  • Ability to add some callback in the Filter in order to apply custom filter

IM

Copied from original issue: ThaDafinser/ZfcDatagrid#276

Mass Actions

From @imonteiro on January 13, 2014 22:11

It's possible provide the possibility to perfom some action on multiple rows, by adding an extra column with a checkbox and passing the primary key throw POST.

Example:

$action1 = array('url' => '/action1', 'caption' => 'Some action');
$action2 = array('url' => '/action2', 'caption' => 'Another action');
$actions = array($action1, $action2);
$grid->setMassActions($actions )

//OR
$grid->addMassAction($action1);
$grid->addMassAction($action2);

Copied from original issue: ThaDafinser/ZfcDatagrid#56

Drop support for PHP 5.6 and 7.0

This might be an unpopular opinion, but hear me out. Both PHP 5.6 and 7.0 will be completely unsupported by PHP in three months from now. The next release of this project should no longer support these versions of PHP.

The current stable version works fine on both 5.6 and 7.0 so there wouldn't be any loss to current users. It is imperative to keep focus on the support of PHP 7.1 and 7.2, however. Dropping the support for PHP 5.6 and 7.0 in the next release will in no way harm the project.

export custom filtered data

From @umeshjoshi on July 31, 2015 10:38

Hi ,
I have an issue on export regarding filters. I have set some custom filters, and these are working fine.
But when I am exporting data its only filtering column filters and leaving custom filters.
Can you please help me to export custom filtered data.

Thanks,

Copied from original issue: ThaDafinser/ZfcDatagrid#193

Implement object dereferencing for setters

From @popovsergiy on January 10, 2016 19:26

Since PHP 5.4 appears awesomeness "class member access on instantiation"

(new CoolObject())->setSomething($option)->addOther($item)->etc()

It would be very useful add something like this to your library:

$actions = new Column\Action('edit');
$actions->setLabel(' ');
$actions->setTranslationEnabled();
$actions->setFormatters([
    (new \ZfcDatagrid\Column\Formatter\Link())
        ->setAttribute('class', 'pencil-edit')
        ->setLink('/spares-ras/products/' . $fmtr->getColumnValuePlaceholder($colId))
]);
$grid->addColumn($actions);

Copied from original issue: ThaDafinser/ZfcDatagrid#221

Problem with select column

From @emontes on July 13, 2014 6:16

I have the following
$categories = array();
foreach ($em->getRepository('Noticias\Entity\Category')->findBy(array(), array('title' => 'ASC')) as $item) {
$categories[strval($item->getCatid())] = $item->getTitle();
}
$col = new Column\Select('catid','s');
$col->setLabel('Categoría');
$col->setReplaceValues($categories,false);
$grid->addColumn($col);

But When I got the select I get:
-BacalarCancúnCaribe MexicanoChetumalCobáCozumelEl EstadoEventosMexican CaribbeanPlaya del CarmenPolíticaPuerto MorelosRiviera MayaTextosTulum

Where the values not correspond with the values in the array that I have sended, I have noticed that if I put some string in the array key then the Select goes right, but It don't correspond with the values for replace.

Copied from original issue: ThaDafinser/ZfcDatagrid#130

Bootstrap DateRange not filtering correctely in examples

From @webdevilopers on April 29, 2014 8:16

Example: /zfcDatagrid/person/bootstrap

When using the DateRange picker on the Birthday column no matter what value I choose I always get two rows returned with Birthday 31.01.1981.

When using the DateRange picker on the Last change" column with *Today or Yesterday I always get the same rows returned.

Is there a special intl setting I have to set on DateRange or the column to make it work?

Ps.: Will there be a DateRange version available for JqGrid?

Copied from original issue: ThaDafinser/ZfcDatagrid#96

String as number with PHPExcel

From @jonathangreco on July 8, 2015 13:7

Hi

I have a problem with the use ZfcDatagrid\Column\Type.

I have a function :

    /**
     * create a column type with number formatted depends on Locale
     * @param integer $locale
     * @return Type
     */
    public function getNumberFromLocale($locale)
    {
        $colType = new Type\Number(
            NumberFormatter::DECIMAL,
            NumberFormatter::TYPE_DEFAULT,
            $locale
        );

        return $colType;
    }

This method is called from my column maker

``` PHP`
// More declaration above
$col = new Column\Select('totalDutyFree');
$col->setLabel('Montant facturé HT');
$col->setType($this->getNumberFromLocale('fr_FR'));
$col->setWidth(5);
$grid->addColumn($col);
//more declaration below


What I want is :
On my XLS document, my totaDutyFree column has to be with numbers not string, but Excel says to me that all my numbers are in string. From here i tried a lot of things to make this work, no luck !
below I explain what I got, during my tests.

When my locale is En_us, it works for numbers like 15.56 but not for 15 or 5,000
When my locale is fr_FR it works only when the result is more than 1000. And never work for 15,15 or 15.

I also test with a code snippet that cast to double those numbers before setting again my dataSource, because mySQL returns all numbers as string and I thought my problems comes from here.

I'm stuck here, anyone as an idea ?


_Copied from original issue: ThaDafinser/ZfcDatagrid#185_

Add multiple cellattr on column when using jqGrid

From @webdevilopers on May 20, 2014 7:58

This issue is based on issue ThaDafinser/ZfcDatagrid#102.

A common jqGrid feature is using footerrow and setting footerData to add totals to the grid.

Unfortunately I could not append any javascript to the grid to add this after the grid was generated.

Same for using grouping for summary. The following demo requires setting attributes summaryType and summaryTpl on columns:

summaryType:'min', summaryTpl:'<b>Min: {0}</b>

http://trirand.com/blog/jqgrid/jqgrid.html

Of course creating your own template is a possible workaround. But mostly for only this one use case.

The jqGrid Columns view helper already has the possibility to set options:
https://github.com/ThaDafinser/ZfcDatagrid/blob/master/src/ZfcDatagrid/Renderer/JqGrid/View/Helper/Columns.php#L86-95

The getter methods get their values from \ZfcDatagrid\Column\AbstractColumn.
It would make no sense to add jqgrid typical options like summaryType there.
Extending the abstract class to define a jqgrid Column would be possible.
But using a global setOptions methods maybe is a smarter solution. And the use the view helper to set an array with "allowed" values.

Another workaround is adding options to the cellattr:
https://github.com/ThaDafinser/ZfcDatagrid/blob/master/src/ZfcDatagrid/Renderer/JqGrid/View/Helper/Columns.php#L109-115

            /**
             * Cellattr
             */
            $rendererParameters = $column->getRendererParameters('jqGrid');
            if (isset($rendererParameters['cellattr'])) {
                $options['cellattr'] = (string) $rendererParameters['cellattr'];
            }
            if (isset($rendererParameters['summaryType'])) {
                $options['summaryType'] = (string) $rendererParameters['summaryType'];
            }
            if (isset($rendererParameters['summaryTpl'])) {
                $options['summaryTpl'] = (string) $rendererParameters['summaryTpl'];
            }  

Should we add an array of possible options to set for the cellattr and add a method for setCellAttributes() and addCellAttributes instead of using the $rendererParameters?

Copied from original issue: ThaDafinser/ZfcDatagrid#107

The expediency of using the MvcEvent

I've wanted to adapt your module to ZF Expressive but see that code is using MvcEvent.
Expressive application doesn't have any registered "application" class and that to cause the problem.
I've gone through the code and see that there isn't real usage of MvcEvent. This only need to getting Request object.
Can we reduce using of MvcEvent and simply inject Request object?

Use route for links or action buttons

From @halfpastfouram on February 9, 2017 22:29

One thing I think the current version of the library is missing is the option to provide a route to the action buttons or link formatters.

Having to provide a string as a link or button target doesn't provide enough flexibility.

Advantages

  • No need to generate route in controller, service or model and pass it to the grid.
  • A great way to generate routes with the option to fill the routes' parameters with the grid's column values.

Requirements

  • Specify a link as a route.
  • Specify the column values required for building the route.
  • Routes will be generated when column action/select is rendered.

Example

Route:

'routes' => [
    'myRoute' => [
        'type'    => Segment::class,
        'options' => [
            'route'    => '/blog[/:month][/:id]',
            'defaults' => [
                'controller' => Controller\IndexController::class,
                'action'     => 'index',
                'month'      => 'september',
                'id'         => null,
            ],
        ],
    ],
];

Setting the link by route:

$column->setRoute( 'myRoute' );
$column->setRouteParams( [
    'month' => $column->getColumnValuePlaceholder( 'month' ),
    'id'    => $column->getColumnValuePlaceholder( 'id' ),
] );

Copied from original issue: ThaDafinser/ZfcDatagrid#268

Error rendering NULLs in DateTime columns with PHPExcel

From @jroedel on January 31, 2017 21:21

I'm using v1.3.2. I'm exporting a DataGrid as an excel with some null values in a DateTime column. I get the following Exception:
Fatal error: Uncaught Error: Call to a member function setTimezone() on boolean in /var/www/test/vendor/thadafinser/zfc-datagrid/src/ZfcDatagrid/Renderer/PHPExcel/Renderer.php:112

It seems that at some point the data source value of the datetime column NULL gets changed to a string(0) "". Then just before the Exception the Renderer tries to get cast the string(0)"" to a DateTime object.

I was able to reproduce the error in a ZF2 Controller (with the ?rendererType=PHPExcel query param):

    public function testAction()
    {
    	$sm = $this->getServiceLocator();
    	/** @var $grid \ZfcDatagrid\Datagrid */
    	$grid = $sm->get('ZfcDatagrid\Datagrid');
    	$grid->setTitle('Test excel');
    	$grid->setDataSource([['testDate' => null]]);
    	$col = new \ZfcDatagrid\Column\Select('testDate');
        $dateType = new \ZfcDatagrid\Column\Type\DateTime('Y-m-d', \IntlDateFormatter::SHORT, \IntlDateFormatter::NONE);
        $col->setType($dateType);
        $col->setLabel('Test date');
        $grid->addColumn($col);
        return $grid->getResponse();
    }

I've been trying to figure out this problem on and off for the past month so I really appreciate whoever takes a look at this!

Copied from original issue: ThaDafinser/ZfcDatagrid#267

Add datagrid filters instead of using the columns filters

One of the issues I have notice is that to do a filtration on the datagrid, you have to add column to the grid and use the toolbarfilter of that column to do the filtration...

Me and my friend thought about adding a new filters, those filters are added to the grid as columns did, and are rendered on the top of the grid... so, we can get rid of the columns and use those filters to get the required data...

In this case, we don't need to show the columns that we want to filter, but at the same time we can filter the grid based on them using the added filters

Can we make it use Ajax? Ajax Massactions and Ajax Filtering would be awsome!

From @isisis on January 15, 2015 23:8

First of all, thx for this nice Module. Some Ajax functionality would be really awesome.
Is it possible to send Ajax Massactions? If we send Ajax Massactions it's also a must-have to filter the grid and fill new data by Ajax without reloading the page. Otherwise the Ajax Massactions wouldn't make sense.

Why?
This could be used as an easy way to add X-to-Many relations on the edit page of an Entity. So the ajax grid could be rendered next to the form elements and would send the entities id with its massaction ajax request, without even beeing a form element.

Even better solution!
If it's not too hard to implement would be a ZfcDatagridFormElement, which can also filter data by ajax. The ZfcDatagridFormElement won't send the data, but write all selections to a hidden form element, so all selected IDs would be sent with the form. The selected IDs could be stored in a multiselect I guess.

Even more nice awesome stuff
A ZfcDatagridDoctrineFormElement would be mega aswome. Just working as the other one I described, but can populate data to doctrine entities.

Copied from original issue: ThaDafinser/ZfcDatagrid#154

Creating Mass Action with Button on Toolbar

From @ellipee on July 3, 2015 1:43

Hello, Please i need help creating checkbox column with an action button on the toolbar that when clicked will send the ids of the checked checkbox to my controller.

i read issues #56 where a discussion on the implementation of mass action was brought forth. but i have no idea how i can get it to work.

Copied from original issue: ThaDafinser/ZfcDatagrid#182

Get value from another column

Hello,
I add a hidden column and I want to use the value of it in another column.
I tried using $ grid-> getColumnByUniqueId ('other_column_id') but it does not work

Specific renderer (currently only supported for jqGrid) not being rendered

From @webdevilopers on April 28, 2014 13:32

In my controller I set this rendererParameter:

        $col = new Column\Select('number', 'c');
        $col->setLabel('Number');
        //only jqGrid currently (custom display)
        $col->setRendererParameter('formatter', '
            function (value, options, rowObject) {
                // do something custom
                return "<b><u>" + value + "</u></b>";
            }
        ', 'jqgrid');        
        $grid->addColumn($col);

But it seems like the code is not generated inside the view as long as I don't remove the third parameter 'jqgrid'.

BTW: Is there a recommended way to escape the javascript?
I would recommend to put the javascript functions into the view and simply parse a string as second parameter so that jqgrid can use it to callback my view function.

Unfortunately parsing a string to the second parameter will cause the code to generate a string in double quotes:

{name: "c_number",index: "c_number",label: "Number",width: "5",hidden: false,sortable: true,search: true,formatter: "formatNumber"}],

But to make jqgrid use it as a callback the quotes need to be removed:

{name: "c_number",index: "c_number",label: "Number",width: "5",hidden: false,sortable: true,search: true,formatter: formatNumber}],

Copied from original issue: ThaDafinser/ZfcDatagrid#95

Custom form for filtering

From @ghost on September 22, 2014 18:32

Hey,

is there a way to implement a form(zend-form) which offers the filter fields?

The way i got in my mind is:
-create a own renderer + layout/toolbar(or extend the bootstrap one)
-create the form and pass it from the renderer to the view
-implement the getFilter-Function in the renderer which handles the post-data and creates the Zfcdatagrid-Filter elements(?)

I dont want to handle the post-data in my controller and create a custom query for the grid...

Im using doctrine.
Great work by the way and greetings from Hamburg ;)

Copied from original issue: ThaDafinser/ZfcDatagrid#142

JqGrid Rendrer overwrite default Action column value

From @popovsergiy on January 10, 2016 20:0

I try add formatter to custom column Action

$fmtr = new Column\Formatter\Link();
$fmtr->setAttribute('class', 'pencil-edit');
$fmtr->setLink('/spares-ras/products/' . $fmtr->getColumnValuePlaceholder($colId));

$action = new Column\Action('edit');
$action->setLabel(' ');
$action->setTranslationEnabled();
$action->setFormatters([$fmtr]);
$grid->addColumn($action);

but on #L211-L220 my value overwrite with empty value because I don't add any action through $action->addAction();.
This can be fixed if add if statement something like this

...
} elseif ($column instanceof Column\Action) {
    /* @var $column \ZfcDatagrid\Column\Action */

    if ($columnActions = $column->getActions()) {
        $actions = [];
        foreach ($columnActions as $action) {
            /* @var $action \ZfcDatagrid\Column\Action\AbstractAction */
            if ($action->isDisplayed($row) === true) {
                $action->setTitle($this->getTranslator()->translate($action->getTitle()));
                $actions[] = $action->toHtml($row);
            }
        }
        $row[$column->getUniqueId()] = implode(' ', $actions);
    }
}
...

Copied from original issue: ThaDafinser/ZfcDatagrid#222

Add jqGrid specific colModel parameters

From @popovsergiy on January 3, 2016 20:21

I need several params edittype, editoptions and searchoptions

colModel: [
    //...
    {name: 'ship_via', width: 100, align: 'center', formatter: 'select',
        edittype: 'select',
        editoptions: {
            value: 'FE:FedEx;TN:TNT;IN:Intim',
            defaultValue: 'Intime',
            multiple: true
        },
        stype: 'select',
        searchoptions: {
            sopt: ['eq', 'ne'],
            value: 'FE:FedEx;TN:TNT;IN:Intim',
            attr: {multiple: 'multiple', size: 4},
            dataInit: dataInitMultiselect
        }},
    //...
],

but through ZfcDatagrid API I can only add value for searchoptions something like this
$col->setFilterSelectOptions([/*values here*/]).
In code on #L103 available only clearSearch, defaultValue, stype and value.
Is it possible add specific parameters for colModel?

Copied from original issue: ThaDafinser/ZfcDatagrid#218

TypeError when applying toobar filter on grid with PhpArray datasource and null value in data

Error:

TypeError: ZfcDatagrid\Column\Type\AbstractType::getFilterValue(): Argument #1 ($val) must be of type string, null given, called in C:\work\php\laminas\vendor\zfc-datagrid\zfc-datagrid\src\ZfcDatagrid\DataSource\PhpArray\Filter.php on line 48 and defined in C:\work\php\laminas\vendor\zfc-datagrid\zfc-datagrid\src\ZfcDatagrid\Column\Type\AbstractType.php:50
Stack trace:
#0 C:\work\php\laminas\vendor\zfc-datagrid\zfc-datagrid\src\ZfcDatagrid\DataSource\PhpArray\Filter.php(48): ZfcDatagrid\Column\Type\AbstractType->getFilterValue(NULL)
#1 [internal function]: ZfcDatagrid\DataSource\PhpArray\Filter->applyFilter(Array)
#2 C:\work\php\laminas\vendor\zfc-datagrid\zfc-datagrid\src\ZfcDatagrid\DataSource\PhpArray.php(62): array_filter(Array, Array)
#3 C:\work\php\laminas\vendor\zfc-datagrid\zfc-datagrid\src\ZfcDatagrid\Datagrid.php(1018): ZfcDatagrid\DataSource\PhpArray->execute()
#4 C:\work\php\laminas\vendor\zfc-datagrid\zfc-datagrid\src\ZfcDatagrid\Datagrid.php(1100): ZfcDatagrid\Datagrid->loadData()
#5 C:\work\php\laminas\vendor\zfc-datagrid\zfc-datagrid\src\ZfcDatagrid\Datagrid.php(1240): ZfcDatagrid\Datagrid->render()

Also, this method works correctly now for non-string types like int it will stop working when strict types declaration will be added to the class file.
Possible solution could be to cast value to string before calling method in ZfcDatagrid\DataSource\PhpArray::applyFilter()

            $value = (string) $row[$col->getUniqueId()];
            $value = $col->getType()->getFilterValue($value);

PHP: 8.0.3
zfc-datagrid/zfc-datagrid: 2.0.0

To reproduce:

        $grid = $this->serviceLocator->get('ZfcDatagrid\Datagrid');
        $grid->addColumn(new Column\Select('name'));
        $grid->addColumn(new Column\Select('value'));
        $grid->setDataSource([
            ['name' => 'name', 'value' => null],
        ]);
        $grid->getResponse();

and apply toolbar filter in 'value' column in browser.

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.