Skip to content

Instantly share code, notes, and snippets.

@coma
Created May 31, 2012 15:47
Show Gist options
  • Save coma/2844304 to your computer and use it in GitHub Desktop.
Save coma/2844304 to your computer and use it in GitHub Desktop.
Datagrid
<?php
namespace Comakai\AdminBundle\Component;
use Comakai\AdminBundle\Comun\CRUDController,
Pagerfanta\Pagerfanta,
Pagerfanta\Adapter\DoctrineORMAdapter,
Comakai\AdminBundle\Form\SearchType,
Symfony\Component\HttpFoundation\Cookie,
Doctrine\ORM\QueryBuilder;
class Datagrid {
protected $controller;
protected $sorting;
protected $searchFields;
protected $batch;
protected $defaultParams;
protected $defaultRouteName;
protected $batchRouteName;
protected $defaultEntityName;
protected $customQueryBuilder;
protected $customSort;
protected $porPagina;
function __construct(CRUDController $controller, $sorting = array(), $searchFields = array('a.id:number' => 'ID'), $batch = true, $defaultParams = null, $defaultRouteName = null, $batchRouteName = null, $defaultEntityName = null, $customQueryBuilder = null, $customSort = null, $porPagina = 20) {
$this->controller = $controller;
$this->sorting = $sorting;
$this->searchFields = $searchFields;
$this->batch = $batch;
$this->defaultParams = $defaultParams;
$this->defaultRouteName = $defaultRouteName;
$this->batchRouteName = $batchRouteName;
$this->defaultEntityName = $defaultEntityName;
$this->customQueryBuilder = $customQueryBuilder;
$this->customSort = $customSort;
$this->porPagina = $porPagina;
}
public function execute() {
if ($this->controller->hasParameter('sort')) {
$this->setSort($this->controller->getParameter('sort'));
}
$search = $this->controller->createForm(new SearchType($this->searchFields));
$search->bindRequest($this->controller->getRequest());
return array(
'batch' => $this->batch,
'form' => $this->controller->createOneForm($this->controller->getKey())->createView(),
'defaultParams' => $this->defaultParams,
'defaultRouteName' => $this->defaultRouteName,
'batchRouteName' => $this->batchRouteName,
'sorting' => $this->getSorting(),
'pager' => $this->getPager(),
'search' => $search->createView()
);
}
protected function getSorting() {
$options = array();
foreach($this->sorting as $n => $sort) {
if(!isset($sort['label'])) {
$sort['label'] = (is_array($sort['sort'])) ? $sort['sort']['by'] : $sort['sort'];
}
if(!isset($sort['asc'])) {
$sort['asc'] = 'ascendente';
}
if(!isset($sort['desc'])) {
$sort['desc'] = 'descendente';
}
$q = $this->controller->getRequest()->query->all();
$q['page'] = 1;
$sort['asc'] = array(
'label' => $sort['asc'],
'params' => array_merge($this->defaultParams, $q, array('sort' => array('n' => $n, 'o' => 'ASC')))
);
$sort['desc'] = array(
'label' => $sort['desc'],
'params' => array_merge($this->defaultParams, $q, array('sort' => array('n' => $n, 'o' => 'DESC')))
);
$options[] = $sort;
}
$sort = $this->getSort();
$label = 'ordenar por...';
if(!is_null($sort) && isset($sort['n'])) {
$order = (isset($sort['o'])) ? strtolower($sort['o']) : 'asc';
$sort = $options[$sort['n']];
$label = $sort['label'].': '.$sort[$order]['label'];
}
return array('label' => $label, 'options' => $options);
}
protected function getSort() {
return $this->controller->getAttribute('sort');
}
protected function setSort($sort) {
$this->controller->setAttribute('sort', $sort);
}
protected function sort(QueryBuilder $qb, $sort, $order = 'ASC') {
$cqb = null;
if(isset($this->customSort)) {
/*
* @todo: cambiar a PHP 5.4 (http://php.net/manual/es/functions.anonymous.php)
*/
$customSort = $this->customSort;
$cqb = $customSort($qb, $sort, $order, $this->controller);
}
if(is_null($cqb)) {
$table = 'a';
$by = 'id';
if(is_array($sort)) {
extract($sort);
} else {
$by = $sort;
}
$qb->orderBy($table.'.'.$by, $order);
return $qb;
}
return $cqb;
}
protected function getQueryBuilder() {
$qb = $this->controller
->getDoctrine()
->getEntityManager()
->createQueryBuilder()
->select('a')
->from('ComakaiModelBundle:' . $this->defaultEntityName, 'a');
$search = $this->controller->getRequest()->get('search');
if (!is_null($search)) {
if (key_exists('ids', $search)) {
$ids = $this->getIds();
$qb->where(($ids != '') ? "a.id IN ($ids)" : "a.id IN (0)");
} else {
$q = trim($search['q']);
$by = explode(':', trim($search['by']));
$field = $by[0];
$type = (count($by) > 1) ? $by[1] : '';
switch ($type) {
case 'gt':
$qb->where("$field > $q");
break;
case 'lt':
$qb->where("$field < $q");
break;
case 'gte':
$qb->where("$field >= $q");
break;
case 'lte':
$qb->where("$field <= $q");
break;
case 'number':
$qb->where("$field = $q");
break;
case 'exact':
case 'date':
$qb->where("$field = '$q'");
break;
case 'like':
default:
$qb->where("$field LIKE '%$q%'");
}
}
}
$sort = $this->getSort();
if(!is_null($sort) && isset($sort['n']) && isset($this->sorting[$sort['n']])) {
$order = (isset($sort['o'])) ? $sort['o'] : 'ASC';
$sort = $this->sorting[$sort['n']]['sort'];
$qb = $this->sort($qb, $sort, $order);
}
if(isset($this->customQueryBuilder)) {
/*
* @todo: cambiar a PHP 5.4 (http://php.net/manual/es/functions.anonymous.php)
*/
$customQueryBuilder = $this->customQueryBuilder;
return $customQueryBuilder($qb, $this->controller);
}
return $qb;
}
protected function getPager() {
$pager = new Pagerfanta(new DoctrineORMAdapter($this->getQueryBuilder()->getQuery()));
$pager->setMaxPerPage($this->porPagina);
$pager->setCurrentPage(min(max($this->controller->get('request')->query->get('page', 1), 1), max($pager->getNbPages(), 1)));
return $pager;
}
public function getIds($string = true) {
$ids = trim($this->controller->getRequest()->cookies->get($this->controller->getKey('index') . '_datagrid_ids'));
if ($string) {
return $ids;
}
if ($ids != '') {
return explode(',', $ids);
}
return array();
}
public function cleanIdsAndRedirect() {
$cookie = new Cookie($this->controller->getKey('index') . '.datagrid.ids');
$response = $this->controller->redirect($this->controller->getPrevURL());
$response->headers->setCookie($cookie);
//$response->headers->removeCookie($this->controller->getKey('index') . '.datagrid.ids');
return $response;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment