public function listAction()
 {
     $pagerAction = $this->handlePager();
     $limit = $this->getLimit($this->defaultPageSize);
     $limit = 100;
     $page = $this->getRequest()->getQuery('page', 0);
     $sort = $this->getRequest()->getQuery('sort', $this->defaultSort);
     $order = $this->getRequest()->getQuery('order', $this->defaultOrder);
     if (empty($sort)) {
         $sort = $this->defaultSort;
     }
     $offset = $limit * $page - $limit;
     if ($offset < 0) {
         $offset = 0;
     }
     /* @var $qb \Doctrine\ORM\QueryBuilder */
     $qb = $this->getEntityManager()->createQueryBuilder();
     $qb->select(['e.referrer', 'COUNT(e.id) AS refcount'])->from($this->getEntityClass(), 'e')->setFirstResult($offset)->setMaxResults($limit)->groupBy('e.referrer')->orderBy('e.' . $sort, $order);
     $qb = $this->handleSearch($qb);
     $pager = $this->getPagerForm($limit);
     $q = $qb->getQuery();
     $q->setMaxResults($limit);
     $q->setFirstResult($offset);
     $results = $this->getSources($q->getArrayResult());
     $paginator = new Paginator(new ArrayAdapter($results));
     $paginator->setCacheEnabled(true);
     $paginator->setDefaultItemCountPerPage($limit);
     $paginator->setCurrentPageNumber($page);
     $paginator->setPageRange($this->paginatorRange);
     $ui = ['table' => ["source" => ["col" => 3, "label" => "Source", "sort" => false], "referrers" => ["col" => 6, "label" => "Referrers", "sort" => false], "count" => ["col" => 1, "label" => "# Leads", "sort" => false]]];
     return ['paginator' => $paginator, 'sort' => $sort, 'order' => $order, 'page' => $page, 'pager' => $pager, 'query' => $this->params()->fromQuery(), 'ui' => $ui, 'isAdmin' => $this->isAdmin(), 'history' => $this->setHistory()];
 }
Example #2
0
 public function testWithCacheDisabled()
 {
     $this->paginator->setCacheEnabled(false);
     $this->paginator->setCurrentPageNumber(1)->getCurrentItems();
     $cachedPageItems = $this->paginator->getPageItemCache();
     $expected = new \ArrayIterator(range(1, 10));
     $this->assertEquals(array(), $cachedPageItems);
     $pageItems = $this->paginator->getCurrentItems();
     $this->assertEquals($expected, $pageItems);
 }
 public function searchAction()
 {
     $id = $this->getEvent()->getRouteMatch()->getParam('id', 0);
     $pagerAction = $this->handlePager();
     $limit = $this->getLimit($this->defaultPageSize);
     $page = $this->getRequest()->getQuery('page', 0);
     $sort = $this->getRequest()->getQuery('sort', $this->defaultSort);
     $order = $this->getRequest()->getQuery('order', $this->defaultOrder);
     if (empty($sort)) {
         $sort = $this->defaultSort;
     }
     $offset = $limit * $page - $limit;
     if ($offset < 0) {
         $offset = 0;
     }
     if (method_exists($this, 'getSearchForm')) {
         $form = $this->getSearchForm();
     } else {
         $form = $this->getForm();
     }
     if ($id) {
         $form->get('id')->setValue($id);
     }
     $request = $this->getRequest();
     $classe = $this->getEntityClass();
     /* @var $report \Report\Entity\Report */
     $report = new $classe();
     $report->setServiceLocator($this->getServiceLocator());
     $account = $this->params()->fromQuery('account');
     if ($account) {
         $objRepository = $this->getEntityManager()->getRepository('Account\\Entity\\Account');
         $aEntity = $objRepository->findOneBy(['id' => $account]);
         if ($aEntity) {
             $report->setAccount($aEntity);
             $report->setName($aEntity->getName() . ' Report');
         }
     }
     $this->getEventManager()->trigger('getForm', $this, ['form' => $form, 'entityClass' => $this->getEntityClass(), 'id' => 0, 'entity' => $report]);
     $form->bind($report);
     $pager = $this->getPagerForm($limit);
     $ui = ['table' => ["_score" => ["col" => 1, "label" => "Score", "sort" => true], "name" => ["col" => 3, "label" => "Name", "sort" => false], "account" => ["col" => 2, "label" => "Account", "sort" => false], "lastsubmitted" => ["col" => 2, "label" => "Submitted", "sort" => true], "timecreated" => ["col" => 2, "label" => "Date", "sort" => true]]];
     $redirectUrl = $this->url()->fromRoute($this->getActionRoute(), [], ['query' => $this->params()->fromQuery()], true);
     if (!$pagerAction) {
         $prg = $this->fileprg($form, $redirectUrl, true);
     } else {
         $prg = false;
     }
     if ($prg instanceof Response) {
         return $prg;
     } elseif ($prg === false || !$form->isValid()) {
         if ($prg && !$form->isValid()) {
             $message = "You have invalid Form Entries.";
             $this->flashMessenger()->addErrorMessage($message);
             $messages = $form->getMessages();
             if ($messages) {
                 $this->flashMessenger()->addErrorMessage($this->formatFormMessages($form, ". <br>\n", true));
             }
         } elseif ($id) {
             // Retrieve Session-Cached data
             $cachedData = $this->getCachedParams($id);
             if ($cachedData) {
                 $form->setData($cachedData);
                 if ($form->isValid()) {
                     $form->get('id')->setValue($id);
                     $prg = $cachedData;
                 }
             }
         }
     }
     $this->setHistory();
     // Set Session-Cached data
     if ($prg) {
         $_id = md5(serialize($prg));
         $report->setId($_id);
         $form->get('id')->setValue($_id);
         $this->setCachedParams($_id, $prg);
         if ($_id != $id) {
             $this->redirect()->toRoute($this->getActionRoute(), ['id' => $_id], ['query' => $this->params()->fromQuery()], true);
         }
     }
     if ($report) {
         $report = $this->setRelationships($report, $prg);
         $results = $report->getResults(false, null, $sort, $order);
     } else {
         $results = [];
     }
     $paginator = new Paginator(new ArrayAdapter($results));
     $paginator->setCacheEnabled(true);
     $paginator->setDefaultItemCountPerPage($limit);
     $paginator->setCurrentPageNumber($page);
     $paginator->setPageRange($this->paginatorRange);
     return ['entity' => $report, 'paginator' => $paginator, 'sort' => $sort, 'order' => $order, 'page' => $page, 'pager' => $pager, 'query' => $this->params()->fromQuery(), 'form' => $form, 'ui' => $ui, 'history' => $this->getHistory()];
 }
 /**
  * (non-PHPdoc)
  *
  * @see \LosBase\Controller\ORM\AbstractCrudController::listAction()
  */
 public function listAction()
 {
     $pagerAction = $this->handlePager();
     $limit = $this->getLimit($this->defaultPageSize);
     $page = $this->getRequest()->getQuery('page', 0);
     $sort = $this->getRequest()->getQuery('sort', $this->defaultSort);
     $order = $this->getRequest()->getQuery('order', $this->defaultOrder);
     $id = $this->getEvent()->getRouteMatch()->getParam('id', 0);
     if (empty($sort)) {
         $sort = $this->defaultSort;
     }
     $offset = $limit * $page - $limit;
     if ($offset < 0) {
         $offset = 0;
     }
     $objRepository = $this->getEntityManager()->getRepository("Report\\Entity\\Report");
     /* @var $report \Report\Entity\Report */
     $report = $objRepository->findOneBy(['id' => $id]);
     if (!$report) {
         return $this->redirect()->toRoute('report/list', ['action' => 'list'], true);
     }
     $pager = $this->getPagerForm($limit);
     $results = $report ? $report->getResults(false, null, $sort, $order) : [];
     $paginator = new Paginator(new ArrayAdapter($results));
     $paginator->setCacheEnabled(true);
     $paginator->setDefaultItemCountPerPage($limit);
     $paginator->setCurrentPageNumber($page);
     $paginator->setPageRange($this->paginatorRange);
     $ui = ['table' => ["_score" => ["col" => 1, "label" => "Score", "sort" => true], "name" => ["col" => 3, "label" => "Name", "sort" => false], "account" => ["col" => 2, "label" => "Account", "sort" => false], "lastsubmitted" => ["col" => 2, "label" => "Submitted", "sort" => true], "timecreated" => ["col" => 2, "label" => "Date", "sort" => true]]];
     $post = $this->params()->fromPost();
     $redirectUrl = $this->url()->fromRoute($this->getActionRoute(), [], true);
     if (!$pagerAction) {
         $prg = $this->prg($redirectUrl, true);
     } else {
         $prg = false;
     }
     if ($pagerAction) {
         $prg = false;
     }
     if ($prg instanceof Response) {
         return $prg;
     } elseif ($prg === false) {
         $form = $this->getListForm($paginator);
         return ['entity' => $report, 'paginator' => $paginator, 'sort' => $sort, 'order' => $order, 'page' => $page, 'pager' => $pager, 'query' => $this->params()->fromQuery(), 'form' => $form, 'ui' => $ui, 'history' => $this->setHistory()];
     }
     $form = $this->getListForm($paginator, $prg);
     $action = isset($prg['bulk_action']) ? $prg['bulk_action'] : false;
     $sel = isset($prg['sel']) ? array_filter($prg['sel']) : false;
     $account_id = isset($prg['account']) ? $prg['account'] : false;
     if ($action && $prg && $sel && ($account_id || in_array($action, ['submit', 'unassign', 'delete']))) {
         $res = true;
         $count = 0;
         $total = 0;
         $em = $this->getEntityManager();
         $i = 1;
         try {
             foreach (array_filter($prg['sel']) as $lead_id => $one) {
                 if ($one) {
                     $res = $this->editLead($lead_id, $account_id, $action) ? $res : false;
                     $count = $res ? $count + 1 : $count;
                     $total++;
                     if ($i % $this->batchSize == 0) {
                         $em->flush();
                         $em->clear();
                     }
                     $i++;
                 }
             }
             $em->flush();
             $em->clear();
         } catch (\Exception $e) {
             $res = false;
         }
         $message = $this->successEditMessage;
         if ($res) {
             switch ($action) {
                 case 'delete':
                     $message = str_replace("The", "{$count} out of {$total}", $this->successDeleteMessage);
                     break;
                 case 'unassign':
                 case 'assign':
                     $message = str_replace("The", "{$count} out of {$total}", $this->successAssignMessage);
                     break;
                 case 'submit':
                     $message = str_replace("The", "{$count} out of {$total}", $this->successSubmitMessage);
                     break;
                 case 'assignSubmit':
                     $message = str_replace("The", "{$count} out of {$total}", $this->successSubmitMessage);
                     break;
             }
             $this->flashMessenger()->addSuccessMessage($this->getServiceLocator()->get('translator')->translate($message));
         } else {
             $message = $this->errorSubmitMessage;
             $message_part = " " . ($total - $count) . " of {$total} Lead(s) were not successfully ";
             switch ($action) {
                 case 'delete':
                     $message = $this->errorDeleteMessage . $message_part . "{$action}ed.";
                     break;
                 case 'unassign':
                 case 'assign':
                     $message = $this->errorAssignMessage . $message_part . "{$action}ed.";
                     break;
                 case 'submit':
                     $message = $this->errorSubmitMessage . $message_part . "{$action}ted.";
                     break;
                 case 'assignSubmit':
                     $message = $this->errorSubmitMessage . $message_part . "submitted.";
                     break;
             }
             $this->flashMessenger()->addErrorMessage($this->getServiceLocator()->get('translator')->translate($message));
         }
     } else {
         $message = "One or more required fields are missing.";
         $this->flashMessenger()->addErrorMessage($this->getServiceLocator()->get('translator')->translate($message));
     }
     return $this->redirect()->toRoute($this->getActionRoute(), ['id' => $id], true);
 }
 public function listAction()
 {
     $pagerAction = $this->handlePager();
     $limit = $this->getLimit($this->defaultPageSize);
     $page = $this->getRequest()->getQuery('page', 0);
     $sort = $this->getRequest()->getQuery('sort', $this->defaultSort);
     $order = $this->getRequest()->getQuery('order', $this->defaultOrder);
     if (empty($sort)) {
         $sort = $this->defaultSort;
     }
     $query = $this->params()->fromQuery();
     $offset = $limit * $page - $limit;
     if ($offset < 0) {
         $offset = 0;
     }
     /* @var $qb \Doctrine\ORM\QueryBuilder */
     $qb = $this->getEntityManager()->createQueryBuilder();
     $qb->add('select', 'e')->add('from', $this->getEntityClass() . ' e')->setFirstResult($offset)->setMaxResults($limit);
     // Hack to bypass Doctrine's busted Paginator
     if (!empty($query['description'])) {
         $sort = 'id';
         $order = 'desc';
     } else {
         $qb->orderBy('e.' . $sort, $order);
     }
     $qb = $this->handleSearch($qb);
     $pager = $this->getPagerForm($limit);
     $paginator = new Paginator(new DoctrinePaginator(new FastPaginator($qb, true)));
     $paginator->setCacheEnabled(true);
     $paginator->setDefaultItemCountPerPage($limit);
     $paginator->setCurrentPageNumber($page);
     $paginator->setPageRange($this->paginatorRange);
     $ui = ['table' => ["description" => ["col" => 2, "label" => "Name", "sort" => false], "account" => ["col" => 2, "label" => "Account", "sort" => false], "referrer" => ["col" => 2, "label" => "Source", "sort" => true], "lastsubmitted" => ["col" => 2, "label" => "Submitted", "sort" => true], "timecreated" => ["col" => 2, "label" => "Created", "sort" => true]]];
     $filters = $this->getFilterForm($this->params()->fromQuery());
     $hiddenFilters = $this->getHiddenFilterForm($this->params()->fromQuery());
     $post = $this->params()->fromPost();
     $redirectUrl = $this->url()->fromRoute($this->getActionRoute(), [], true);
     if (!$pagerAction) {
         $prg = $this->prg($redirectUrl, true);
     } else {
         $prg = false;
     }
     if ($pagerAction) {
         $prg = false;
     }
     if ($prg instanceof Response) {
         return $prg;
     } elseif ($prg === false) {
         $form = $this->getListForm($paginator);
         $form->setData(['filters' => $this->params()->fromQuery()]);
         return ['paginator' => $paginator, 'sort' => $sort, 'order' => $order, 'page' => $page, 'pager' => $pager, 'query' => $this->params()->fromQuery(), 'form' => $form, 'filters' => $filters, 'hiddenFilters' => $hiddenFilters, 'ui' => $ui, 'history' => $this->setHistory()];
     }
     $form = $this->getListForm($paginator, $prg);
     $action = $prg['bulk_action'] ?: false;
     $sel = isset($prg['sel']) ? array_filter($prg['sel']) : false;
     $account_id = isset($prg['account']) ? $prg['account'] : false;
     if ($action && $prg && $sel && ($account_id || in_array($action, ['unassign', 'delete', 'submit']))) {
         $res = true;
         $count = 0;
         $total = 0;
         $em = $this->getEntityManager();
         $i = 1;
         try {
             foreach (array_filter($prg['sel']) as $lead_id => $one) {
                 if ($one) {
                     $res = $this->editLead($lead_id, $account_id, $action) ? $res : false;
                     $count = $res ? $count + 1 : $count;
                     $total++;
                     if ($i % $this->batchSize == 0) {
                         $em->flush();
                         $em->clear();
                     }
                     $i++;
                 }
             }
             $em->flush();
             $em->clear();
         } catch (\Exception $e) {
             $res = false;
         }
         $message = $this->successEditMessage;
         if ($res) {
             switch ($action) {
                 case 'delete':
                     $message = str_replace("The", "{$count} out of {$total}", $this->successDeleteMessage);
                     break;
                 case 'unassign':
                 case 'assign':
                     $message = str_replace("The", "{$count} out of {$total}", $this->successAssignMessage);
                     break;
                 case 'submit':
                     $message = str_replace("The", "{$count} out of {$total}", $this->successSubmitMessage);
                     break;
                 case 'assignSubmit':
                     $message = str_replace("The", "{$count} out of {$total}", $this->successSubmitMessage);
                     break;
             }
             $this->flashMessenger()->addSuccessMessage($this->getServiceLocator()->get('translator')->translate($message));
         } else {
             $message = $this->errorSubmitMessage;
             $message_part = " " . ($total - $count) . " of {$total} Lead(s) were not successfully ";
             switch ($action) {
                 case 'delete':
                     $message = $this->errorDeleteMessage . $message_part . "{$action}ed.";
                     break;
                 case 'unassign':
                 case 'assign':
                     $message = $this->errorAssignMessage . $message_part . "{$action}ed.";
                     break;
                 case 'submit':
                     $message = $this->errorSubmitMessage . $message_part . "{$action}ted.";
                     break;
                 case 'assignSubmit':
                     $message = $this->errorSubmitMessage . $message_part . "submitted.";
                     break;
             }
             $this->flashMessenger()->addErrorMessage($this->getServiceLocator()->get('translator')->translate($message));
         }
     } else {
         $message = "One or more required fields are missing.";
         $this->flashMessenger()->addErrorMessage($this->getServiceLocator()->get('translator')->translate($message));
     }
     return $this->getHistoricalRedirect('list', true);
 }
Example #6
0
 /**
  * Retorna vários registros da tabela
  *
  * @param mixed $where
  *            OPTIONAL Condições SQL
  * @param array|int $order
  *            OPTIONAL Ordem dos registros
  * @param int $count
  *            OPTIONAL Limite de registros
  * @param int $offset
  *            OPTIONAL Offset
  *
  * @return array
  */
 public function fetchAll($where = null, $order = null, $count = null, $offset = null)
 {
     // Cria a assinatura da consulta
     if ($where instanceof \Zend\Db\Sql\Select) {
         $md5 = md5($where->getSqlString());
     } else {
         $md5 = md5(var_export($where, true) . var_export($order, true) . var_export($count, true) . var_export($offset, true) . var_export($this->getShowDeleted(), true) . var_export($this->getUseDeleted(), true));
     }
     // Verifica se tem no cache
     // Se estiver usando o paginador, o cache é controlado pelo Zend\Paginator
     if ($this->getUseCache() && !$this->getUsePaginator() && $this->getCache()->hasItem($md5)) {
         return $this->getCache()->getItem($md5);
     }
     $select = $this->getSelect($where, $order, $count, $offset);
     // Verifica se deve usar o Paginator
     if ($this->getUsePaginator()) {
         // Configura o fetchAll com o paginator
         $fetchAll = new Paginator(new PaginatorDbAdapter($select, $this->getTableGateway()->getAdapter()));
         // Verifica se deve usar o cache
         if ($this->getUseCache()) {
             $fetchAll->setCacheEnabled(true)->setCache($this->getCache());
         }
         // Configura o paginator
         $fetchAll->setPageRange($this->getPaginatorConfig()->getPageRange());
         $fetchAll->setCurrentPageNumber($this->getPaginatorConfig()->getCurrentPageNumber());
         $fetchAll->setItemCountPerPage($this->getPaginatorConfig()->getItemCountPerPage());
         // retorna o resultado da consulta
         return $fetchAll;
     }
     // Recupera os registros do banco de dados
     $fetchAll = $this->getTableGateway()->selectWith($select);
     // Verifica se foi localizado algum registro
     if (!is_null($fetchAll) && count($fetchAll) > 0) {
         // Passa o $fetch para array para poder incluir campos extras
         $fetchAll = $fetchAll->toArray();
         // Verifica se deve adicionar campos extras
         $fetchAll = $this->getFetchAllExtraFields($fetchAll);
     } else {
         $fetchAll = null;
     }
     // Grava a consulta no cache
     if ($this->getUseCache()) {
         $this->getCache()->setItem($md5, $fetchAll);
     }
     // retorna o resultado da consulta
     return $fetchAll;
 }
Example #7
0
 /**
  * Retorna vários registros da tabela
  *
  * @param mixed     $where  OPTIONAL Condições SQL
  * @param array|int $order  OPTIONAL Ordem dos registros
  * @param int       $count  OPTIONAL Limite de registros
  * @param int       $offset OPTIONAL Offset
  *
  * @return array
  */
 public function fetchAll($where = null, $order = null, $count = null, $offset = null)
 {
     // Cria a assinatura da consulta
     if ($where instanceof \Zend\Db\Sql\Select) {
         $md5 = md5($where->getSqlString());
     } else {
         $md5 = md5(var_export($where, true) . var_export($order, true) . var_export($count, true) . var_export($offset, true) . var_export($this->getShowDeleted(), true) . var_export($this->getUseDeleted(), true));
     }
     // Verifica se tem no cache
     // o Zend_Paginator precisa do Zend_Paginator_Adapter_DbSelect para acessar o cache
     if ($this->getUseCache() && !$this->getUsePaginator() && $this->getCache()->hasItem($md5)) {
         return $this->getCache()->getItem($md5);
     } else {
         // Recupera a clausula where dos ExtraFields
         $extraFields = null;
         if ($where instanceof \Zend\Db\Sql\Select) {
             $select = $where;
         } else {
             if (isset($where['extra-fields'])) {
                 $extraFields = $where['extra-fields'];
                 unset($where['extra-fields']);
             }
             /**
              *
              * @var \Zend\Db\Sql\Select
              */
             $select = $this->getSelect($where, $order, $count, $offset);
         }
         // Verifica se deve usar o Paginator
         if ($this->getUsePaginator()) {
             $paginatorAdapter = new DbSelect($select, $this->getTableGateway()->getAdapter());
             $fetchAll = new Paginator($paginatorAdapter);
             // Verifica se deve usar o cache
             if ($this->getUseCache()) {
                 $fetchAll->setCacheEnabled(true)->setCache($this->getCache());
             }
             // Configura o paginator
             $fetchAll->setPageRange($this->getPaginator()->getPageRange());
             $fetchAll->setCurrentPageNumber($this->getPaginator()->getCurrentPageNumber());
             $fetchAll->setItemCountPerPage($this->getPaginator()->getItemCountPerPage());
         } else {
             // Recupera os registros do banco de dados
             $fetchAll = $this->getTableGateway()->selectWith($select);
             // Verifica se foi localizado algum registro
             if (!is_null($fetchAll) && count($fetchAll) > 0) {
                 // Passa o $fetch para array para poder incluir campos extras
                 $fetchAll = $fetchAll->toArray();
                 // Verifica se deve adicionar campos extras
                 $fetchAll = $this->getFetchAllExtraFields($fetchAll, $extraFields);
             } else {
                 $fetchAll = null;
             }
             // Grava a consulta no cache
             if ($this->getUseCache()) {
                 $this->getCache()->setItem($md5, $fetchAll);
             }
         }
         // Some garbage collection
         unset($select);
         // retorna o resultado da consulta
         return $fetchAll;
     }
 }