PHP code example of avpretty / grid-bundle

1. Go to this page and download the library: Download avpretty/grid-bundle library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

avpretty / grid-bundle example snippets


$bundles = [
    new AV\GridBundle\AVGridBundle(),
];

{% block stylesheets %}
    {% stylesheets '@AVGridBundle/Resources/public/css/grid-view.css' %}
        <link rel="stylesheet" href="{{ asset_url }}" />
    {% endstylesheets %}
{% endblock %}

...

{% block javascripts %}
    {% javascripts '@AVGridBundle/Resources/public/js/grid-view.js' %}
        <script src="{{ asset_url }}"></script>
    {% endjavascripts %}
{% endblock %}

// IN YOUR CONTROLLER
$em = $this->getDoctrine()->getManager();

$dataSource = $this->get('av_grid.query_data_source')
    ->setEntityName(User::class)->setRootAlias('u')
    ->setDataSource($em->getRepository('User')->createQueryBuilder('u'));

$gridData = [
    'dataSource' => $dataSource,
];

return $this->render('index.html.twig', [
    'paginationInstance' => $dataSource->getPagination(),
    'gridView' => $this->get('av_grid.grid_view_factory')
        ->prepareGridView($gridData),
]);

{{ gridView(gridView) }}
{{ gridPagination(paginationInstance) }}

$gridData = [
    'dataSource' => $dataSource,
    'filterEntity' => new User,
    'tableCaption' => 'Users',
    'emptyCell' => 'no data',
    'columns' => [
        [
            'label' => 'User ID',
            'attributeName' => 'id'
        ],
        [
            'label' => 'User Full Name',
            'content' => function($userEntity, $rowIndex) {
                return $userEntity->getFirstName().' '.$userEntity->getLastName(); 
            }
        ],
        [
            'attributeName' => 'created',
            'filterType' => DateType::class,
            'filterFieldOptions' => [
                'widget' => 'single_text'
            ]
        ]
    ]
];

return $this->render('index.html.twig', [
    'paginationInstance' => $dataSource->getPagination(),
    'gridView' => $this->get('av_grid.grid_view_factory')
        ->prepareGridView($gridData),
]);

// IN CONTROLLER
$ext = $this->get('twig')->getExtension(GridExtension::class);

$nestedGridData = [
    'dataSource' => $nestedGridDataSource,
]; 

$renderedNestedGrid = $ext->prepareGridView(
    $gridFactory->prepareGridView($nestedGridData)
);

$gridData = [
    'dataSource' => $dataSource,
    'filterEntity' => new User,
    'tableCaption' => 'Users',
    'emptyCell' => 'no data',
    'columns' => [
        ...
        [
            'content' => function($entity, $rowIndex) use ($renderedNestedGrid) {
                return $renderedNestedGrid;
            }
            'format' => ColumnFormat::RAW_FORMAT
        ]
    ]
];

return $this->render('index.html.twig', [
    'paginationInstance' => $dataSource->getPagination(),
    'gridView' => $this->get('av_grid.grid_view_factory')
        ->prepareGridView($gridData),
]);

$userEntity = new User;

$gridData = [
    'filterEntity' => $userEntity,
    ...
];

$gridData = [
    'filterEntity' => $userEntity,
    'dataSource' => $dataSource,
    'columns' => [
        [
            'label' => 'User Name',
            'attributeName' => 'name',
            'filterType' => TextType::class,
        ]
    ],
];

...
public function search(array $searchParams)
{
    $queryBuilder = $this->createQueryBuilder('u');

    if (!$searchParams) {
        return $queryBuilder;
    }
    
    $firstName = $searchParams['firstName'];
    
    $lastName = $searchParams['lastName'];
    
    $created = $searchParams['created']; // Date foramt - Y-m-d (in our case)
    
    if ($firstName) {
        $queryBuilder->andWhere('u.firstName LIKE :firstName')
            ->setParameter(':firstName', '%'.$firstName.'%');
    }
    
    if ($lastName) {
        $queryBuilder->andWhere('u.lastName LIKE :lastName')
            ->setParameter(':lastName', '%'.$lastName.'%');
    }

    // I'm sure you'll have time to write code better than this
    if ($created) {
        $queryBuilder->andWhere('u.created BETWEEN :start AND :end')
        ->setParameter(':start', $created)
        ->setParameter(
            ':end',
            (new \DateTime($created))->modify('+1 day')->format('Y-m-d')
        );
    }

    return $queryBuilder;
}
...

$gridFactory = $this->get('av_grid.grid_view_factory');

/** @var EntityManager $em */
$em = $this->getDoctrine()->getManager();

$dataSource = $this->get('av_grid.query_data_source')
    ->setEntityName(User::class)
    ->setRootAlias('u');

$dataSource->setDataSource(
    $em->getRepository('User')->search($request->get('User'))
);

$gridData = [
    'filterEntity' => new User,
    'dataSource' => $dataSource,
];
...
// render template

[
    'attributeName' => 'country',
    'content' => function($userEntity, $rowIndex) {
        return $entity->getCountry()->getTitle();
    },
    'filterType' => EntityType::class,
    'filterFieldOptions' => [
        'class' => Country::class,
        'choice_label' => 'title'
    ]
],

// To just display all fields of entity you can omit column configuration
'columns' => [
    ['attributeName' => 'firstName'],
    ['attributeName' => 'lastName'],
    ['attributeName' => 'age'],
    ['attributeName' => 'email'],
    ['attributeName' => 'created'],
]

'columns' => [
    [
        'label' => 'User Country'
        'content' => function($userEntity, $rowIndex) {
            return $userEntity->getCountry()->getTitle();
        }
    ]
]

OR YOU CAN USE SHORT SYNTAX

'columns' => [
    [
        'attributeName' => 'country.title'
    ]
]

'columns' => [
    [
        'label' => 'User Name'
        'sortable' => false
        'attributeName' => 'firstName',
        'filterType' => EntityType::class,
        'filterFieldOptions' => [
            'class' => User::class,
            'choice_label' => 'firstName',
            'placeholder' => 'Select name',
        ]
    ],
    [
        'label' => 'User Last Name'
        'attributeName' => 'lastName'
    ],
    [
        'attributeName' => 'fullName'
        'content' => function($userEntity, $rowIndex) {
            return $userEntity->getFirstName() . ' ' . $userEntity->getLastName(); 
        },
        'filterType' => TextType::class,
        'filterFieldOptions' => [
            'mapped' => false
        ]
    ],
    [
        'attributeName' => 'created',
        'format' => [ColumnFormat::DATE_FORMAT => 'Y-m-d']
    ],
    [
        'attributeName' => 'email',
        'visible' => function() use ($someExternalObject) {
            return // some permission check logic
        }
    ],
    [
        'label' => 'Custom column',
        'content' => function($userEntity) use ($someEntity) {
            return $someEntity->getDataByUserId($userEntity->getId());
        },
        'contentOptions' => ['width' => '100px']
    ]
]

'columns' => [
    [
        'service' => 'av_grid.counter_column',
        'label' => 'My Custom Label' // # by default
    ]
]

'columns' => [
    [
        // Custom configuration
        'service' => 'av_grid.action_column',
        'buttons' => [
            ActionColumn::SHOW => 'http://custom-url.com'
            ActionColumn::EDIT => function ($entity, $url) use ($router) {
                return $router->generate('compaign_show', ['id' => 4]);
            },
        ],
        'hiddenButtons' => [
            ActionColumn::EDIT => function ($entity, $url) {
                return $entity->getId() == 5; // If true then won't be shown
            }
        ]
    ]
]

'columns' => [
    [
        'label' => 'Plain text'
        'content' => function ($entity) {
            return '<script>alert("hello");</script>'; // will be displayed as plain text
        },
    ],
    [
        'label' => 'Execute JS'
        'content' => function ($entity) {
            return '<script>alert("hello");</script>'; // alert message will be shown
        },
        'format' => ColumnFormat::RAW_FORMAT,
    ],
    [
        'label' => 'Format timestamp'
        'content' => function($entity) {
            // return $entity->getCreated(); // returns \DateTime 

            // return '1484204985'; // simple timestamp
        },
        'format' => [ColumnFormat::DATE_FORMAT => 'Y-m-d']
    ]
    [
        'label' => 'Twig construction'
        'content' => function($entity) {
            return "{{ 'CUSTOM TEXT'|lower }}";
        },
        'format' => ColumnFormat::FORMAT
    ]
]

// Get user entity query builder
$queryBuilder = $entityManager->getRepository('User')->createQueryBuilder('u');

// Initialize data source
$dataSource = $this->get('av_grid.query_data_source')
    ->setDataSource($queryBuilder)
    ->setRootAlias('u'); // Read below about root alias

// Create custom pagination. OPTIONAL
$pagination = $this->get('av_grid.pagination')
    ->setPageSize(5)
    ->setTotalCount(50);

// Create custom sort. OPTIONAL
$sortAttributes = [
    'u.email',
    // Custom configuration
    'name' => [
        Sort::ASC  => [
            'u.first_name' => Sort::ASC, 'u.last_name' => Sort::ASC
        ],
        Sort::DESC => [
            'u.first_name' => Sort::DESC, 'u.last_name' => Sort::DESC
        ],
    ],
]

$sort = $this->get('av_grid.sort')->setAttributes($sortAttributes);

$dataSource->setPagination($pagination)->setSort($sort);

// Get all user entities
$dataSource->fetchEntities();

// Get entities total count even if we did not call `setTotalCount` of pagiantion component
$dataSource->getTotalCount();

// Get user entity query builder
$userData = [
    ['first_name' => 'John', last_name => 'Doe', 'email' => '[email protected]'],
    ['first_name' => 'Jane', last_name => 'Doe', 'email' => '[email protected]'],
    ['first_name' => 'Mike', last_name => 'Doe', 'email' => '[email protected]'],
];

// Initialize data source
$dataSource = $this->get('av_grid.array_data_source')
    ->setDataSource($userData);

// Create custom pagination. OPTIONAL
...

// Create custom sort. OPTIONAL
...

$sort = $this->get('av_grid.sort')->setAttributes($sortAttributes);

$dataSource->setPagination($pagination)->setSort($sort);

$dataSource = $this->get('av_grid.data_source');
$dataSource->setDataSource(
    $entityManager->getRepository('User')->createQueryBuilder('u')
);

// Simple example
$sortAttributes = [
    'u.email',
    'u.first_name'
    'u.last_name'
]

// Extended example: sorting by multiple fields
$sortAttributes = [
    // Default sort params will be used
    'u.email',

    // Custom configuration
    'name' => [
        Sort::ASC  => [
            'u.first_name' => Sort::ASC, 'u.last_name' => Sort::ASC
        ],
        Sort::DESC => [
            'u.first_name' => Sort::DESC, 'u.last_name' => Sort::DESC
        ],
        'default' => Sort::DESC,
        'label'   => 'Name',
    ],
]

$sort = $this->get('av_grid.sort')->setAttributes($sortAttributes);

$dataSource->setSort($sort);

[
    'u.email'  => [
        Sort::ASC  => ['u.email' => Sort::ASC],
        Sort::DESC => ['u.email' => Sort::DESC],
        
    ],
]

$sort = $this->get('av_grid.sort');

$sort->setAttributes([
    'countryTitle' => [
        Sort::ASC  => ['c.title' => Sort::ASC],
        Sort::DESC => ['c.title' => Sort::DESC],
    ]
]);

$dataSource->setSort($sort);

$pagination = $this->get('av_grid.pagination');

// Set amount of items per page
$pagination->setPageSize(3); // Or default value will be used
$pagination->setTotalCount(12); // 

// Let's assume that we have query string: .../admin/user/?per-page=3&page=3

echo $pagination->getLimit(); // 3
echo $pagination->getOffset(); // 6

$pagination->setPageParam('my-page-counter'); // .../admin/user/?per-page=3&my-page-counter=3

// paginationInstance should be passed to template from controller
{{ gridPagination(paginationInstance) }}

{{ gridPagination(
        paginationInstance,
        {
            'options'             : {'id': 'pagination-block-id', 'data-id': 'some-id'},
            'linkOptions'         : {'class': 'class-for-each-link'},
            'showFirstPageLink'   : true,
            'showLastPageLink'    : true,
            'showPrevPageLink'    : true,
            'showNextPageLink'    : true,
            'nextPageLabel'       : '&rsaquo;',
            'prevPageLabel'       : '&lsaquo;',
            'firstPageLabel'      : '&laquo;',
            'lastPageLabel'       : '&raquo;',
            'maxButtonCount'      : 13,
            'activePageCssClass'  : 'active',
            'disabledPageCssClass': 'disabled',
            'firstPageCssClass'   : 'first',
            'lastPageCssClass'    : 'last',
            'prevPageCssClass'    : 'prev',
            'nextPageCssClass'    : 'next',
        }
   )
}}