Prezent / prezent-grid-bundle

Integrate prezent-grid in Symfony
MIT License
6 stars 3 forks source link

Complete example #1

Closed Hanfrey closed 6 years ago

Hanfrey commented 9 years ago

Hello,

maybe you should add a complete example. I wanted to test this, but iam struggeling.

  1. Created class:
<?php

namespace AppBundle\Grids;

use Prezent\Grid\BaseGridType;
use Prezent\Grid\GridBuilder;

class SommerfestGrid extends BaseGridType
{
    public function buildGrid(GridBuilder $builder, array $options = [])
    {
        $builder
            ->addColumn('id', 'string')
            ->addColumn('name', 'string')     
        ;
    }
}
  1. created service
<service id="app.grid.sommerfest" class="AppBundle\Grids\SommerfestGrid">
    <tag name="prezent_grid.grid" alias="sommerfest" />
</service>
  1. added twig function

   {{ grid(grid,data) }}
  1. called everything in controller
     $query = $em->createQuery(
    'SELECT s.id,s.benutzername
    FROM AppBundle:Sommerfest s
    WHERE s.teilnahme=true
    ORDER BY s.benutzername ASC');

$products = $query->getResult();

        $grid = $this->get('grid_factory')->createGrid('sommerfest');

         return $this->render('bulk/grid.html.twig', array(

            'page_desc' => "Uebersicht",
            'page_header' => 'Alles',
            'data' => $products,
             'grid' => $grid->createView(),
        ));

Error: An exception has been thrown during the rendering of a template ("Cannot read property "id" from an array. Maybe you intended to write the property path as "[id]" instead.") in grid.html.twig at line 32.

sandermarechal commented 9 years ago

Yes, that is a good idea. As for your specific issue, add a property_path option, see https://github.com/Prezent/prezent-grid/blob/master/doc/define-grids.md#mapping-your-row-data

<?php

namespace AppBundle\Grids;

use Prezent\Grid\BaseGridType;
use Prezent\Grid\GridBuilder;

class SommerfestGrid extends BaseGridType
{
    public function buildGrid(GridBuilder $builder, array $options = [])
    {
        $builder
            ->addColumn('id', 'string', ['property_path' => '[id]')
            ->addColumn('name', 'string', ['property_path' => '[name]')     
        ;
    }
}

By default the property path is the same as the column name. But column names like 'id' and 'name' are used for object properies, not array indexes. You're passing an array to the grid so you need to use '[id]' etc.

Alternatively you could simply pass your entities to the grid:

$query = $em->createQuery(
    'SELECT s
    FROM AppBundle:Sommerfest s
    WHERE s.teilnahme=true
    ORDER BY s.benutzername ASC');