Paginação Mongodb com adianti Estou desenvolvendo um código com o mongodb. E eu não estou conseguindo fazer a paginação. Já tentei algumas pesquisas, mas não deu muito certo. Segue abaixo meu código: Mongodb versão 5 ...
LS
Paginação Mongodb com adianti  

Estou desenvolvendo um código com o mongodb. E eu não estou conseguindo fazer a paginação. Já tentei algumas pesquisas, mas não deu muito certo.

Segue abaixo meu código:

Mongodb versão 5

 
  1. <?php
  2. /**
  3. * TelaCPFNomeList Listing
  4. * @author <your name here>
  5. */
  6. class TelaCPFNomeList extends TPage
  7. {
  8. protected $form; // registration form
  9. protected $datagrid; // listing
  10. protected $pageNavigation;
  11. protected $formgrid;
  12. protected $deleteButton;
  13. protected $transformCallback;
  14. private $properties;
  15. /**
  16. * Class constructor
  17. * Creates the page, the form and the listing
  18. */
  19. public function __construct()
  20. {
  21. parent::__construct();
  22. try
  23. {
  24. // creates the form
  25. $this->form = new BootstrapFormBuilder('form_search_TelaCPFNome');
  26. $this->form->setFormTitle('Lista CPF E Nome MongoDB');
  27. // create the form fields
  28. $nome = new TEntry('nome');
  29. $nome->forceUpperCase();
  30. $nome->setMaxLength(100);
  31. $cpf = new TEntry('cpf');
  32. $cpf->setMask('999.999.999-99');
  33. $cpf->addValidation(('Regex Format'), new TRequiredValidator);
  34. $inativa = new TCombo('inativa');
  35. $inativa->addItems(array( 'f' => ('Ativo'), 't' => ('Inativo')));
  36. $nome->setSize('100%');
  37. $cpf->setSize('100%');
  38. $inativa->setSize('100%');
  39. // add the fields
  40. $row = $this->form->addFields( [new TLabel('CPF', '', '14px', 'b', '100%'), $cpf] );
  41. $row->layout = ['col-sm-4','col-sm-4','col-sm-4'];
  42. $row = $this->form->addFields( [new TLabel('Nome', '', '14px', 'b', '100%'),$nome] );
  43. $row->layout = ['col-sm-8', 'col-sm-4'];
  44. $row = $this->form->addFields( [new TLabel('Situação', '', '14px', 'b', '100%'),$inativa] );
  45. $row->layout = ['col-sm-4', 'col-sm-4', 'col-sm-4'];
  46. // keep the form filled during navigation with session data
  47. $this->form->setData( TSession::getValue(__CLASS__.'_filter_data') );
  48. // add the search form actions
  49. $this->form->addAction(_t('New'), new TAction(array('TelaCPFNomeForm', 'onEdit')), 'fa:plus')->class = 'btn btn-sm btn-success';
  50. $this->form->addAction(_t('Find'), new TAction(array($this, 'onSearch')), 'fa:search')->class = 'btn btn-sm btn-primary';
  51. $this->form->addAction(_t('Clear'), new TAction(array($this, 'onClear')), 'fa:eraser')->class = 'btn btn-sm btn-warning';
  52. // creates a Datagrid
  53. $this->datagrid = new BootstrapDatagridWrapper(new TDataGrid);
  54. $this->datagrid->datatable = 'true';
  55. $this->datagrid->style = 'width: 100%';
  56. $this->datagrid->setHeight(320);
  57. // creates the datagrid columns
  58. //$column_id = new TDataGridColumn('id', 'ID', 'center');
  59. $column_cpf = new TDataGridColumn('cpf', 'CPF', 'center');
  60. $column_nome = new TDataGridColumn('nome', 'Nome', 'center');
  61. $column_inativa = new TDataGridColumn('inativa', _t('Status'), 'center');
  62. $column_inativa->setTransformer(function($value, $object, $row) {
  63. $class = ($value==false) ? 'success' : 'danger';
  64. $label = ($value==false) ? 'Ativo' : 'Inativo';
  65. $div = new TElement('span');
  66. $div->class="label label-{$class}";
  67. $div->style="text-shadow:none; font-size:12px; font-weight:lighter";
  68. $div->add($label);
  69. return $div;
  70. });
  71. // add the columns to the DataGrid
  72. //$this->datagrid->addColumn($column_id);
  73. $this->datagrid->addColumn($column_cpf);
  74. $this->datagrid->addColumn($column_nome);
  75. $this->datagrid->addColumn($column_inativa);
  76. $this->datagrid->disableDefaultClick();
  77. // create EDIT action
  78. $action_edit = new TDataGridAction(array('TelaCPFNomeForm', 'onEdit'));
  79. $action_edit->setButtonClass('btn btn-default');
  80. $action_edit->setLabel(_t('Edit'));
  81. $action_edit->setImage('far:edit blue fa-lg');
  82. $action_edit->setField('id');
  83. $this->datagrid->addAction($action_edit);
  84. // create DELETE action
  85. $action_del = new TDataGridAction(array($this, 'onDelete'));
  86. $action_del->setButtonClass('btn btn-default');
  87. $action_del->setLabel(_t('Delete'));
  88. $action_del->setImage('fa:trash red fa-lg');
  89. $action_del->setField('id');
  90. $this->datagrid->addAction($action_del);
  91. // create the datagrid model
  92. $this->datagrid->createModel();
  93. // create the page navigation
  94. $this->pageNavigation = new TPageNavigation;
  95. $this->pageNavigation->enableCounters();
  96. $this->pageNavigation->setAction(new TAction(array($this, 'onReload')));
  97. $this->pageNavigation->setWidth($this->datagrid->getWidth());
  98. $panel = new TPanelGroup;
  99. $panel->add($this->datagrid);
  100. $panel->addFooter($this->pageNavigation);
  101. // vertical box container
  102. $container = new TVBox;
  103. $container->style = 'width: 100%';
  104. $container->add(new TXMLBreadCrumb('menu.xml', 'TelaCPFNomeList'));
  105. $container->add($this->form);
  106. $container->add($panel);
  107. parent::add($container);
  108. }
  109. catch (Exception $e)
  110. {
  111. new TMessage('error', $e->getMessage());
  112. }
  113. }
  114. function onClear()
  115. {
  116. // get the search form data
  117. $data = $this->form->getData();
  118. TSession::setValue(__CLASS__.'_filter_data', NULL);
  119. TSession::setValue(__CLASS__.'_filters', NULL);
  120. $data->cpf = '';
  121. $data->nome = '';
  122. $data->inativa = '';
  123. // fill the form with data again
  124. $this->form->setData($data);
  125. $param = array();
  126. $param['offset'] = 0;
  127. $param['first_page'] = 1;
  128. $this->onReload($param);
  129. }
  130. /**
  131. * Register the filter in the session
  132. */
  133. public function onSearch($param = NULL)
  134. {
  135. // get the search form data
  136. $data = $this->form->getData();
  137. // clear session filters
  138. TSession::setValue(__CLASS__.'_filter_data', NULL);
  139. TSession::setValue(__CLASS__.'_filters', NULL);
  140. $filters = array();
  141. if ((isset($data->cpf) AND ($data->cpf != NULL)) ||
  142. (isset($data->nome) AND ($data->nome != NULL)) ||
  143. (isset($data->inativa) AND ($data->inativa != NULL)))
  144. {
  145. $data->nome = mb_strtoupper($data->nome, 'UTF-8');
  146. $cpf = json_decode(json_encode($data->cpf, true), true);
  147. $nome = json_decode(json_encode($data->nome, true), true);
  148. $inativa = json_decode(json_encode($data->inativa, true), true);
  149. $cpf = new MongoDB\BSON\Regex("^$cpf.*$", 'i');
  150. $nome = new MongoDB\BSON\Regex("^$nome.*$", 'i');
  151. $filters = array("cpf" => $cpf, "nome" => $nome, "inativa" => boolval($inativa));
  152. }
  153. // fill the form with data again
  154. $this->form->setData($data);
  155. TSession::setValue(__CLASS__.'_filter_data', $data);
  156. TSession::setValue(__CLASS__.'_filters', $filters);
  157. // keep the search data in the session
  158. TSession::setValue('TelaCPFNome_filter_data', $data);
  159. $param=array();
  160. $param['offset'] =0;
  161. $param['first_page']=1;
  162. $this->onReload($param);
  163. }
  164. /**
  165. * Load the datagrid with data
  166. */
  167. public function onReload($param = NULL)
  168. {
  169. try
  170. {
  171. // This path should point to Composer's autoloader
  172. require '../../../../vendor/autoload.php';
  173. // default order
  174. $limit = 10;
  175. $offset = 0;
  176. // default order
  177. if (empty($param['order']))
  178. {
  179. $param['order'] = '_id';
  180. $param['direction'] = 'desc';
  181. }
  182. $param['limit'] = isset($limit) ? $limit : NULL;
  183. $limit = $param['limit'];
  184. if (isset($param['offset']) AND $param['offset'])
  185. {
  186. $offset = (int) $param['offset'];
  187. }
  188. /*
  189. if ($param['page']=="" || $param['page']=="1")
  190. {
  191. $param['first_page']=1;
  192. }
  193. else
  194. {
  195. $param['first_page']=($param['page']*10)-10;
  196. }
  197. $options=[
  198. 'limit' => $limit,
  199. 'skip' => $param['first_page'],
  200. 'sort' => ["_id" => -1],
  201. ];
  202. */
  203. $options = [
  204. 'skip'=> $offset,
  205. 'limit'=> $limit,
  206. 'sort' => ["_id" => -1],
  207. ];
  208. $filters = [];
  209. if(TSession::getValue(__CLASS__.'_filters'))
  210. {
  211. $filters = json_decode(json_encode(TSession::getValue(__CLASS__.'_filters'), true), true);
  212. }
  213. echo "<pre>";
  214. print_r($param);
  215. echo "</pre>";
  216. $this->datagrid->clear();
  217. $manager = new MongoDB\Driver\Manager('mongodb://localhost:27017');
  218. $readPreference = new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::RP_PRIMARY);
  219. $query = new MongoDB\Driver\Query($filters, $options);
  220. $cursor = $manager->executeQuery('bancoTeste.cadastro_cpf_nome', $query, $readPreference);
  221. $objects = json_decode(json_encode($cursor->toArray(),true), true);
  222. if ($objects)
  223. {
  224. foreach ($objects as $key => $object)
  225. {
  226. $newObject = new stdClass;
  227. $newObject->id = $object['_id']['$oid'];
  228. $newObject->cpf = $object['cpf'];
  229. $newObject->nome = $object['nome'];
  230. $newObject->inativa = $object['inativa'];
  231. // add the object inside the datagrid
  232. $this->datagrid->addItem($newObject);
  233. }
  234. }
  235. if (is_callable($this->transformCallback))
  236. {
  237. call_user_func($this->transformCallback, $objects, $param);
  238. }
  239. $param['limit'] = NULL;
  240. $param['order'] = NULL;
  241. $param['offset'] = NULL;
  242. $param['group'] = NULL;
  243. $count = count($objects);
  244. $this->pageNavigation->setCount($count); // count of records
  245. $this->pageNavigation->setProperties($param); // order, page
  246. $this->pageNavigation->setLimit($limit); // limit
  247. $this->loaded = true;
  248. }
  249. catch (Exception $e) // in case of exception
  250. {
  251. // shows the exception error message
  252. new TMessage('error', $e->getMessage());
  253. // undo all pending operations
  254. TTransaction::rollback();
  255. }
  256. }
  257. /**
  258. * Ask before deletion
  259. */
  260. public function onDelete($param)
  261. {
  262. // define the delete action
  263. $action = new TAction(array($this, 'Delete'));
  264. $action->setParameters($param); // pass the key parameter ahead
  265. // shows a dialog to the user
  266. new TQuestion(AdiantiCoreTranslator::translate('Do you really want to delete ?'), $action);
  267. }
  268. /**
  269. * Delete a record
  270. */
  271. public function Delete($param)
  272. {
  273. try
  274. {
  275. $id = $param['id']; // get the parameter $key
  276. // This path should point to Composer's autoloader
  277. require '../../../../vendor/autoload.php';
  278. //connect to mongodb
  279. $conexaoMongo = new MongoDB\Client('mongodb://localhost:27017');
  280. $banco = $conexaoMongo->bancoTeste;
  281. $cadastro = $banco->cadastro_cpf_nome;
  282. $cadastro->deleteOne( array( '_id' => new MongoDB\BSON\ObjectId ($id)) );
  283. $this->onReload( $param ); // reload the listing
  284. new TMessage('info', AdiantiCoreTranslator::translate('Record deleted')); // success message
  285. TApplication::loadPage('TelaCPFNomeList', '');
  286. }
  287. catch (Exception $e) // in case of exception
  288. {
  289. new TMessage('error', $e->getMessage()); // shows the exception error message
  290. TTransaction::rollback(); // undo all pending operations
  291. }
  292. }
  293. public function show()
  294. {
  295. // check if the datagrid is already loaded
  296. if (!$this->loaded AND (!isset($_GET['method']) OR !(in_array($_GET['method'], array('onReload', 'onSearch', 'onClear')))) )
  297. {
  298. if (func_num_args() > 0)
  299. {
  300. $this->onReload( func_get_arg(0) );
  301. }
  302. else
  303. {
  304. $this->onReload();
  305. }
  306. }
  307. parent::show();
  308. }
  309. function showMessage()
  310. {
  311. new TMessage('info', AdiantiCoreTranslator::translate('Record saved'));
  312. $this->onReload();
  313. }
  314. }
  315. ?>


 
  1. <?php
  2. /**
  3. * TelaCPFNomeForm Form
  4. * @author <your name here>
  5. */
  6. class TelaCPFNomeForm extends TPage
  7. {
  8. protected $form; // form
  9. /**
  10. * Form constructor
  11. * @param $param Request
  12. */
  13. public function __construct()
  14. {
  15. parent::__construct();
  16. try
  17. {
  18. // creates the form
  19. $this->form = new BootstrapFormBuilder('form_TelaCPFNome');
  20. // define the form title
  21. $this->form->setFormTitle('Cadastro CPF E Nome MongoDB');
  22. // create the form fields
  23. $id = new THidden('id');
  24. $id->setEditable(false);
  25. $this->form->addFields( [$id]);
  26. $nome = new TEntry('nome');
  27. $nome->forceUpperCase();
  28. $nome->setMaxLength(100);
  29. $nome->addValidation(('Name'), new TRequiredValidator);
  30. $cpf = new TEntry('cpf');
  31. $cpf->setMask('999.999.999-99');
  32. $cpf->addValidation(('Regex Format'), new TRequiredValidator);
  33. //descrever o local físico do arquivo
  34. $inativa = new TRadioGroup('inativa');
  35. $inativa->setLayout('horizontal');
  36. $inativa->setUseButton();
  37. $inativa->addItems(['f' => 'Ativo', 't' => 'Inativo']);
  38. $nome->setSize('100%');
  39. $cpf->setSize('100%');
  40. $inativa->setSize('100%');
  41. // add the fields
  42. $row = $this->form->addFields( [new TLabel('CPF', '', '14px', 'b', '100%'), $cpf] );
  43. $row->layout = ['col-sm-4','col-sm-4','col-sm-4'];
  44. $row = $this->form->addFields( [new TLabel('Nome', '', '14px', 'b', '100%'), $nome] );
  45. $row->layout = ['col-sm-9','col-sm-3'];
  46. $row = $this->form->addFields( [new TLabel('Situação', '', '14px', 'b', '100%'), $inativa] );
  47. $row->layout = ['col-sm-4','col-sm-4','col-sm-4'];
  48. // create the form actions
  49. $this->form->addAction(_t('Save'), new TAction(array($this, 'onSave')), 'fa:save')->class = 'btn btn-sm btn-success';
  50. $this->form->addAction(_t('Back'),new TAction(array('TelaCPFNomeList', 'onReload')),'fa:arrow-circle-left')->class = 'btn btn-sm btn-info';
  51. // vertical box container
  52. $container = new TVBox;
  53. $container->style = 'width: 100%';
  54. $container->add(new TXMLBreadCrumb('menu.xml', 'TelaCPFNomeList'));
  55. $container->add($this->form);
  56. parent::add($container);
  57. }
  58. catch (Exception $e)
  59. {
  60. new TMessage('error', $e->getMessage());
  61. }
  62. }
  63. /**
  64. * Save form data
  65. * @param $param Request
  66. */
  67. public function onSave()
  68. {
  69. require '../../../../vendor/autoload.php';
  70. try
  71. {
  72. //connect to mongodb
  73. $conexaoMongo = new MongoDB\Client('mongodb://localhost:27017');
  74. $data = $this->form->getData(); // get form data as array
  75. $this->form->validate(); // validate form data
  76. $banco = $conexaoMongo->bancoTeste;
  77. $cadastro = $banco->cadastro_cpf_nome;
  78. if ($cadastro instanceof \MongoDB\Collection)
  79. {
  80. $valorInativa = $data->inativa == 'f' ? FALSE : TRUE;
  81. $nome = mb_strtoupper($data->nome, 'UTF-8');
  82. $documento = ['_id' => new MongoDB\BSON\ObjectId(), "cpf" => $data->cpf, "nome" => $nome, "inativa" => $valorInativa, "data_cadastro" => new MongoDB\BSON\UTCDateTime()];
  83. if (strlen(trim(TSession::getValue('mongoID')))>0)
  84. {
  85. //require('mongodb://localhost:27017').MongoDB\BSON\ObjectId;
  86. $id = new MongoDB\BSON\ObjectId(TSession::getValue('mongoID'));
  87. $cadastro->replaceOne(['_id' => $id], ['_id' => $id, "cpf" => $data->cpf, "nome" => $nome, "inativa" => $valorInativa, "data_cadastro" => new MongoDB\BSON\UTCDateTime()], ['upsert' => true]);
  88. }
  89. else
  90. {
  91. $cadastro->insertOne($documento);
  92. }
  93. TApplication::loadPage('TelaCPFNomeList', 'showMessage');
  94. }
  95. }
  96. catch (Exception $e)
  97. {
  98. new TMessage('error', $e->getMessage()); // shows the exception error message
  99. TTransaction::rollback(); // undo all pending operations
  100. }
  101. }
  102. /**
  103. * Load object to form data
  104. * @param $param Request
  105. */
  106. public function onEdit( $param )
  107. {
  108. TSession::setValue('mongoID', NULL);
  109. try
  110. {
  111. if (isset($param['id']))
  112. {
  113. // This path should point to Composer's autoloader
  114. require '../../../../vendor/autoload.php';
  115. //connect to mongodb
  116. $conexaoMongo = new MongoDB\Client('mongodb://localhost:27017');
  117. $id = $param['id'];
  118. TSession::setValue('mongoID', $id);
  119. $banco = $conexaoMongo->bancoTeste;
  120. $cadastro = $banco->cadastro_cpf_nome;
  121. $data = $cadastro->findOne(array('_id' => new MongoDB\BSON\ObjectID($id)));
  122. $data->inativa = !$data->inativa ? 'f' : 't';
  123. $this->form->setData($data); // fill the form
  124. }
  125. }
  126. catch (Exception $e) // in case of exception
  127. {
  128. new TMessage('error', $e->getMessage()); // shows the exception error message
  129. TTransaction::rollback(); // undo all pending operations
  130. }
  131. }
  132. }
  133. ?>

Curso Dominando o Adianti Framework

O material mais completo de treinamento do Framework.
Curso em vídeo aulas + Livro completo + Códigos fontes do projeto ERPHouse.
Conteúdo Atualizado!


Dominando o Adianti Framework Quero me inscrever agora!

Comentários (7)


RJ

Eu ainda não juntei o Adianti com MongoDB, porém já fiz alguns trabalhos com FormDin (um framework primo do Adianti) com MongoDB. O que vou te falar é apenas da paginação do MongoBD, depois vc terá juntar com o grid do Adianti para pegar o numero da pagina

Vc vai usar o parâmetros skip e limit

https://www.mongodb.com/docs/php-library/v1.12/reference/method/MongoDBCollectio

Editado 04/07/2022 (há 3 anos) - Ver alterações
LS

Eu já estou usando o limit e o skip meu caro. Vou olhar o seu link
LS

Você viu meu código? pode postar algum seu com esse outro framework?
PD

Lucas,

Dê um var_dump no $options, pra ver se ele está montando do jeito certo antes de ser passado para a API.

Outra dica, não deixe os dados de conexão direto no código ('mongodb://localhost:27017')
Prefira manter em arquivo de configuração em app/config, seja em .INI ou .PHP (melhor)

Ex...:

app/config/mongo.php
 
  1. <?php
  2. return [
  3. 'host' => '127.0.0.1'
  4. ]
  5. ?>


E no código (controller):
 
  1. <?php
  2. $ini = require 'app/config/mongo.php';
  3. ?>


Att,
LS

certo Pablo.

aqui o print da variável $param

Array
(
[class] => TelaCPFNomeList
[method] => onReload
[offset] => 0
[limit] => 10
[direction] => desc
[page] => 1
[first_page] => 1
[order] => _id
)

eu comparei com outros exemplos com o banco sendo relacional e retornam a mesma coisa.
LS

Bom dia alguém encontrou uma solução para o problema? Ainda não consegui resolver.
LS

Bom dia pessoal.

Estava sem tempo para postar. Mas já consegui resolver o problema.

No onReload eu chamei eu rodo uma segunda query para contar os registros. Fiz algumas poucas alterações também.

 
  1. <?php
  2. /**
  3. * TelaCPFNomeForm Form
  4. * @author <your name here>
  5. */
  6. class TelaCPFNomeForm extends TPage
  7. {
  8. protected $form; // form
  9. private $ini;
  10. /**
  11. * Form constructor
  12. * @param $param Request
  13. */
  14. public function __construct()
  15. {
  16. $this->ini = require 'app/config/mongo.php';
  17. parent::__construct();
  18. try
  19. {
  20. // creates the form
  21. $this->form = new BootstrapFormBuilder('form_TelaCPFNome');
  22. // define the form title
  23. $this->form->setFormTitle('Cadastro CPF E Nome MongoDB');
  24. // create the form fields
  25. $id = new THidden('id');
  26. $id->setEditable(false);
  27. $this->form->addFields( [$id]);
  28. $nome = new TEntry('nome');
  29. $nome->forceUpperCase();
  30. $nome->setMaxLength(100);
  31. $nome->addValidation(('Name'), new TRequiredValidator);
  32. $cpf = new TEntry('cpf');
  33. $cpf->setMask('999.999.999-99');
  34. $cpf->addValidation(('Regex Format'), new TRequiredValidator);
  35. //descrever o local físico do arquivo
  36. $inativa = new TRadioGroup('inativa');
  37. $inativa->setLayout('horizontal');
  38. $inativa->setUseButton();
  39. $inativa->addItems(['f' => 'Ativo', 't' => 'Inativo']);
  40. $nome->setSize('100%');
  41. $cpf->setSize('100%');
  42. $inativa->setSize('100%');
  43. // add the fields
  44. $row = $this->form->addFields( [new TLabel('CPF', '', '14px', 'b', '100%'), $cpf] );
  45. $row->layout = ['col-sm-4','col-sm-4','col-sm-4'];
  46. $row = $this->form->addFields( [new TLabel('Nome', '', '14px', 'b', '100%'), $nome] );
  47. $row->layout = ['col-sm-9','col-sm-3'];
  48. $row = $this->form->addFields( [new TLabel('Situação', '', '14px', 'b', '100%'), $inativa] );
  49. $row->layout = ['col-sm-4','col-sm-4','col-sm-4'];
  50. // create the form actions
  51. $this->form->addAction(_t('Save'), new TAction(array($this, 'onSave')), 'fa:save')->class = 'btn btn-sm btn-success';
  52. $this->form->addAction(_t('Back'),new TAction(array('TelaCPFNomeList', 'onReload')),'fa:arrow-circle-left')->class = 'btn btn-sm btn-info';
  53. // vertical box container
  54. $container = new TVBox;
  55. $container->style = 'width: 100%';
  56. $container->add(new TXMLBreadCrumb('menu.xml', 'TelaCPFNomeList'));
  57. $container->add($this->form);
  58. parent::add($container);
  59. }
  60. catch (Exception $e)
  61. {
  62. new TMessage('error', $e->getMessage());
  63. }
  64. }
  65. /**
  66. * Save form data
  67. * @param $param Request
  68. */
  69. public function onSave()
  70. {
  71. // This path should point to Composer's autoloader
  72. //require_once __DIR__ . '/vendor/autoload.php';
  73. //require '../../../../vendor/autoload.php';
  74. try
  75. {
  76. //connect to mongodb
  77. $conexaoMongo = new MongoDB\Client($this->ini['host']);
  78. $data = $this->form->getData(); // get form data as array
  79. $this->form->validate(); // validate form data
  80. $banco = $conexaoMongo->bancoTeste;
  81. $cadastro = $banco->cadastro_cpf_nome;
  82. if ($cadastro instanceof \MongoDB\Collection)
  83. {
  84. $valorInativa = $data->inativa == 'f' ? FALSE : TRUE;
  85. $nome = mb_strtoupper($data->nome, 'UTF-8');
  86. /*
  87. https://imasters.com.br/back-end/mecanismos-de-busca-de-php-com-mongodb
  88. inclui tags para tornar a pesquisa mais rápida
  89. The simplest way is, by using explode:
  90. $parts = explode(" ", $name);
  91. After you have the parts, pop the last one as $lastname:
  92. $lastname = array_pop($parts);
  93. Finally, implode back the rest of the array as your $firstname:
  94. $firstname = implode(" ", $parts);
  95. https://www.luiztools.com.br/post/como-criar-um-mecanismo-de-busca/
  96. https://stackoverflow.com/questions/13637145/split-text-string-into-first-and-last-name-in-php
  97. $parts = explode(" ", $nome);
  98. $firstname = implode(" ", $parts);
  99. $lastname = array_pop($parts);
  100. $documento = ['_id' => new MongoDB\BSON\ObjectId(), "cpf" => $data->cpf, "nome" => $nome, "inativa" => $valorInativa, "tags":[$data->cpf, $firstname, $lastname]];
  101. */
  102. $documento = ['_id' => new MongoDB\BSON\ObjectId(), "cpf" => $data->cpf, "nome" => $nome, "inativa" => $valorInativa, "data_cadastro" => new MongoDB\BSON\UTCDateTime()];
  103. if (strlen(trim($data->id))>0)
  104. {
  105. //require($this->ini['host']).MongoDB\BSON\ObjectId;
  106. $id = new MongoDB\BSON\ObjectId($data->id);
  107. /*
  108. replaceOne replace the entire document, while updateOne allows for update an specific field of the document
  109. replaceOne() replaces the first matching document in the collection that matches the filter, using the replacement document.
  110. upsert
  111. If upsert: true and no documents match the filter, db.collection.replaceOne() creates a new document based on the replacement document.
  112. db.collection.replaceOne(
  113. <filter>,
  114. <replacement>,
  115. {
  116. upsert: <boolean>,
  117. writeConcern: <document>,
  118. collation: <document>,
  119. hint: <document|string>
  120. }
  121. db.collection.replaceOne() with upsert: true can be run on an existing collection or a non-existing collection. If run on a non-existing collection, the operation creates the collection.
  122. */
  123. $cadastro->replaceOne(['_id' => $id], ['_id' => $id, "cpf" => $data->cpf, "nome" => $nome, "inativa" => $valorInativa, "data_cadastro" => new MongoDB\BSON\UTCDateTime()], ['upsert' => true]);
  124. }
  125. else
  126. {
  127. $cadastro->insertOne($documento);
  128. }
  129. TApplication::loadPage('TelaCPFNomeList', 'showMessage');
  130. }
  131. }
  132. catch (Exception $e)
  133. {
  134. new TMessage('error', $e->getMessage()); // shows the exception error message
  135. TTransaction::rollback(); // undo all pending operations
  136. }
  137. }
  138. /**
  139. * Load object to form data
  140. * @param $param Request
  141. */
  142. public function onEdit( $param )
  143. {
  144. //TSession::setValue('mongoID', NULL);
  145. try
  146. {
  147. if (isset($param['id']))
  148. {
  149. // This path should point to Composer's autoloader
  150. //require '../../../../vendor/autoload.php';
  151. //connect to mongodb
  152. $conexaoMongo = new MongoDB\Client($this->ini['host']);
  153. $id = $param['id'];
  154. //TSession::setValue('mongoID', $id);
  155. $banco = $conexaoMongo->bancoTeste;
  156. $cadastro = $banco->cadastro_cpf_nome;
  157. $data = $cadastro->findOne(array('_id' => new MongoDB\BSON\ObjectID($id)));
  158. $data->id = $id;
  159. $data->inativa = !$data->inativa ? 'f' : 't';
  160. $this->form->setData($data); // fill the form
  161. }
  162. }
  163. catch (Exception $e) // in case of exception
  164. {
  165. new TMessage('error', $e->getMessage()); // shows the exception error message
  166. TTransaction::rollback(); // undo all pending operations
  167. }
  168. }
  169. }
  170. ?>


 
  1. <?php
  2. /**
  3. * TelaCPFNomeList Listing
  4. * @author <your name here>
  5. */
  6. class TelaCPFNomeList extends TPage
  7. {
  8. protected $form; // registration form
  9. protected $datagrid; // listing
  10. protected $pageNavigation;
  11. protected $formgrid;
  12. protected $deleteButton;
  13. protected $transformCallback;
  14. private $ini;
  15. private $properties;
  16. /**
  17. * Class constructor
  18. * Creates the page, the form and the listing
  19. */
  20. public function __construct()
  21. {
  22. $this->ini = require 'app/config/mongo.php';
  23. parent::__construct();
  24. try
  25. {
  26. // creates the form
  27. $this->form = new BootstrapFormBuilder('form_search_TelaCPFNome');
  28. $this->form->setFormTitle('Lista CPF E Nome MongoDB');
  29. $id = new TEntry('id');
  30. // create the form fields
  31. $nome = new TEntry('nome');
  32. $nome->forceUpperCase();
  33. $nome->setMaxLength(100);
  34. $cpf = new TEntry('cpf');
  35. $cpf->setMask('999.999.999-99');
  36. $cpf->addValidation(('Regex Format'), new TRequiredValidator);
  37. $inativa = new TCombo('inativa');
  38. $inativa->addItems(array( 0 => ('Ativo'), 1 => ('Inativo')));
  39. $id->setSize('100%');
  40. $nome->setSize('100%');
  41. $cpf->setSize('100%');
  42. $inativa->setSize('100%');
  43. // add the fields
  44. $row = $this->form->addFields( [new TLabel('ID', '', '14px', 'b', '100%'), $id] );
  45. $row->layout = ['col-sm-4','col-sm-4','col-sm-4'];
  46. $row = $this->form->addFields( [new TLabel('CPF', '', '14px', 'b', '100%'), $cpf] );
  47. $row->layout = ['col-sm-4','col-sm-4','col-sm-4'];
  48. $row = $this->form->addFields( [new TLabel('Nome', '', '14px', 'b', '100%'),$nome] );
  49. $row->layout = ['col-sm-8', 'col-sm-4'];
  50. $row = $this->form->addFields( [new TLabel('Situação', '', '14px', 'b', '100%'),$inativa] );
  51. $row->layout = ['col-sm-4', 'col-sm-4', 'col-sm-4'];
  52. // keep the form filled during navigation with session data
  53. $this->form->setData( TSession::getValue(__CLASS__.'_filter_data') );
  54. // add the search form actions
  55. $this->form->addAction(_t('New'), new TAction(array('TelaCPFNomeForm', 'onEdit')), 'fa:plus')->class = 'btn btn-sm btn-success';
  56. $this->form->addAction(_t('Find'), new TAction(array($this, 'onSearch')), 'fa:search')->class = 'btn btn-sm btn-primary';
  57. $this->form->addAction(_t('Clear'), new TAction(array($this, 'onClear')), 'fa:eraser')->class = 'btn btn-sm btn-warning';
  58. // creates a Datagrid
  59. $this->datagrid = new BootstrapDatagridWrapper(new TDataGrid);
  60. $this->datagrid->datatable = 'true';
  61. $this->datagrid->style = 'width: 100%';
  62. $this->datagrid->setHeight(320);
  63. // creates the datagrid columns
  64. $column_id = new TDataGridColumn('id', 'ID', 'center');
  65. $column_cpf = new TDataGridColumn('cpf', 'CPF', 'center');
  66. $column_nome = new TDataGridColumn('nome', 'Nome', 'center');
  67. $column_inativa = new TDataGridColumn('inativa', _t('Status'), 'center');
  68. $column_inativa->setTransformer(function($value, $object, $row) {
  69. $class = ($value==false) ? 'success' : 'danger';
  70. $label = ($value==false) ? 'Ativo' : 'Inativo';
  71. $div = new TElement('span');
  72. $div->class="label label-{$class}";
  73. $div->style="text-shadow:none; font-size:12px; font-weight:lighter";
  74. $div->add($label);
  75. return $div;
  76. });
  77. // add the columns to the DataGrid
  78. $this->datagrid->addColumn($column_id);
  79. $this->datagrid->addColumn($column_cpf);
  80. $this->datagrid->addColumn($column_nome);
  81. $this->datagrid->addColumn($column_inativa);
  82. $this->datagrid->disableDefaultClick();
  83. // create EDIT action
  84. $action_edit = new TDataGridAction(array('TelaCPFNomeForm', 'onEdit'));
  85. $action_edit->setButtonClass('btn btn-default');
  86. $action_edit->setLabel(_t('Edit'));
  87. $action_edit->setImage('far:edit blue fa-lg');
  88. $action_edit->setField('id');
  89. $this->datagrid->addAction($action_edit);
  90. // create DELETE action
  91. $action_del = new TDataGridAction(array($this, 'onDelete'));
  92. $action_del->setButtonClass('btn btn-default');
  93. $action_del->setLabel(_t('Delete'));
  94. $action_del->setImage('fa:trash red fa-lg');
  95. $action_del->setField('id');
  96. $this->datagrid->addAction($action_del);
  97. // create the datagrid model
  98. $this->datagrid->createModel();
  99. // create the page navigation
  100. $this->pageNavigation = new TPageNavigation;
  101. $this->pageNavigation->enableCounters();
  102. $this->pageNavigation->setAction(new TAction(array($this, 'onReload')));
  103. $this->pageNavigation->setWidth($this->datagrid->getWidth());
  104. $panel = new TPanelGroup;
  105. $panel->add($this->datagrid);
  106. $panel->addFooter($this->pageNavigation);
  107. // vertical box container
  108. $container = new TVBox;
  109. $container->style = 'width: 100%';
  110. $container->add(new TXMLBreadCrumb('menu.xml', 'TelaCPFNomeList'));
  111. $container->add($this->form);
  112. $container->add($panel);
  113. parent::add($container);
  114. }
  115. catch (Exception $e)
  116. {
  117. new TMessage('error', $e->getMessage());
  118. }
  119. }
  120. function onClear()
  121. {
  122. // get the search form data
  123. $data = $this->form->getData();
  124. TSession::setValue(__CLASS__.'_filter_data', NULL);
  125. TSession::setValue(__CLASS__.'_filters', NULL);
  126. $data->id = '';
  127. $data->cpf = '';
  128. $data->nome = '';
  129. $data->inativa = '';
  130. // fill the form with data again
  131. $this->form->setData($data);
  132. $param = array();
  133. $param['offset'] = 0;
  134. $param['first_page'] = 1;
  135. $this->onReload($param);
  136. }
  137. /**
  138. * Register the filter in the session
  139. */
  140. public function onSearch($param = NULL)
  141. {
  142. // get the search form data
  143. $data = $this->form->getData();
  144. // clear session filters
  145. TSession::setValue(__CLASS__.'_filter_data', NULL);
  146. TSession::setValue(__CLASS__.'_filters', NULL);
  147. $filters = array();
  148. if (isset($data->id) AND ($data->id != NULL))
  149. {
  150. $id = new \MongoDB\BSON\ObjectId($data->id);
  151. $filters['_id'] = $id;
  152. /*
  153. Find By _id
  154. $mongo = new \MongoDB\Driver\Manager('mongodb://root:root@192.168.0.127/db');
  155. $id = new \MongoDB\BSON\ObjectId("588c78ce02ac660426003d87");
  156. $filter = ['_id' => $id];
  157. $options = [];
  158. $query = new \MongoDB\Driver\Query($filter, $options);
  159. $rows = $mongo->executeQuery('db.collectionName', $query);
  160. foreach ($rows as $document) {
  161. pr($document);
  162. }
  163. https://www.php.net/manual/en/class.mongodb-driver-query.php
  164. */
  165. }
  166. if (isset($data->cpf) AND ($data->cpf != NULL))
  167. {
  168. $cpf = new MongoDB\BSON\Regex("^$data->cpf.*$", 'i');
  169. $filters['cpf'] = $cpf;
  170. }
  171. if (isset($data->nome) AND ($data->nome != NULL))
  172. {
  173. $data->nome = mb_strtoupper($data->nome, 'UTF-8');
  174. $nome = new MongoDB\BSON\Regex("^$data->nome.*$", 'i');
  175. $filters['nome'] = $nome;
  176. }
  177. if (isset($data->inativa) AND ($data->inativa != NULL))
  178. {
  179. $filters['inativa'] = boolval($data->inativa);
  180. }
  181. /*
  182. Mongo DB 5.0
  183. There is no like in mongo,You can use regex Here in this case you dont require regex,you can get your result using simple find query,Date stored in mongodb is in ISO formate,So first convert your date to ISO date and then find for eg
  184. var convertDate = "11/11/2016";
  185. convertDate = new Date(11/11/2016);
  186. db.getCollection('TableName').find({date : convertDate})
  187. Or if you want like in mongo use this
  188. 1)Search directly
  189. db.getCollection('TableName').find({date : {$regex : "11/11/2016"}})
  190. 2) Create a text index on date and then search
  191. db.getCollection('TableName').find({$text:{$search:"11/11/2016"}})
  192. https://stackoverflow.com/questions/40541617/how-do-i-query-in-mongo-db-using-like-operator
  193. transform stdclass to array
  194. json_decode(json_encode($value), true)
  195. https://stackoverflow.com/questions/18576762/php-stdclass-to-array
  196. array("inativa" => json_decode(json_encode($data->inativa), true)boolval($data->inativa))
  197. https://www.php.net/manual/en/mongodb-bson-regex.construct.php
  198. $nome = new MongoDB\BSON\Regex("^$nome", 'i');
  199. https://arctype.com/blog/sql-phone-number/
  200. https://stackoverflow.com/questions/28712248/difference-between-mongodb-and-mongoose
  201. https://studio3t.com/knowledge-base/articles/mongodb-find-method/
  202. https://stackoverflow.com/questions/45705786/mongoclient-class-vs-mongodb-driver-manager-class
  203. $filters = array('$or' => array(array("cpf" => $cpf), array("nome" => $nome), array("inativa" => boolval($inativa))));
  204. */
  205. // fill the form with data again
  206. $this->form->setData($data);
  207. TSession::setValue(__CLASS__.'_filter_data', $data);
  208. TSession::setValue(__CLASS__.'_filters', $filters);
  209. // keep the search data in the session
  210. $param=array();
  211. $param['offset'] =0;
  212. $param['first_page']=1;
  213. $this->onReload($param);
  214. }
  215. /**
  216. * Load the datagrid with data
  217. */
  218. public function onReload($param = NULL)
  219. {
  220. try
  221. {
  222. // This path should point to Composer's autoloader
  223. //require '../../../../vendor/autoload.php';
  224. /*https://www.php.net/manual/en/mongodb-driver-manager.executequery.php
  225. https://www.mongodb.com/docs/manual/reference/method/Session.startTransaction/
  226. https://www.php.net/manual/en/class.mongodb-driver-manager.php
  227. */
  228. // default order
  229. $limit = 10;
  230. //https://stackoverflow.com/questions/35147845/how-does-sorting-work-in-the-new-mongodb-pecl-extension
  231. // default order
  232. /*if (empty($param['order']))
  233. {
  234. $param['order'] = '_id';
  235. $param['direction'] = 'desc';
  236. }*/
  237. $param['limit'] = isset($limit) ? $limit : NULL;
  238. $param['page'] = isset($param['page']) ? $param['page'] : 1;
  239. $param['offset'] = isset($param['offset']) ? $param['offset'] : 0;
  240. //$param['offset'] = ($param['page']=="" || $param['page']=="1") ? 0 : ($param['page']*10)-10;
  241. /*
  242. $options = [
  243. 'skip'=> $offset,
  244. 'limit'=> $limit,
  245. 'sort' => ["_id" => -1],
  246. ];
  247. */
  248. /* Return the documents in descending order of _id by the timestamp
  249. This will sort your collection in descending order based on the date of insertion
  250. https://stackoverflow.com/questions/13847766/how-to-sort-a-collection-by-date-in-mongodb
  251. */
  252. /* Only return the following fields in the matching documents */
  253. $options = [
  254. 'skip' => $param['offset'],
  255. 'limit' => $param['limit'],
  256. 'sort' => ["_id" => -1]
  257. ];
  258. $filters = [];
  259. if(TSession::getValue(__CLASS__.'_filters'))
  260. {
  261. $filters = TSession::getValue(__CLASS__.'_filters');
  262. /*foreach ($filters as $key => $filter)
  263. {
  264. $filter = json_decode(json_encode($filter), true);
  265. if ($key == 'nome')
  266. {
  267. $filter = ['$regex' => $filter];
  268. }
  269. if ($key == 'inativa')
  270. {
  271. $filter = boolval($filter);
  272. }
  273. $newArray[] = array($key => $filter);
  274. $filters = array('$or' => $newArray);
  275. }
  276. $filtros = array();
  277. foreach ($filters as $key => $filter)
  278. {
  279. $filtros = array('$and' => array(array("{$key}" => $filter)));
  280. $filtros = array('$or' => array(array("{$key}" => $filter)));
  281. $filtros = array("{$key}" => array('$in' => array($filter)));
  282. $filtros[$key] = $filter;
  283. $filtros = array();
  284. $filters = array_merge($filtros, $filters);
  285. }*/
  286. $filters = array('$and' => array(array($filters)));
  287. }
  288. $this->datagrid->clear();
  289. $manager = new MongoDB\Driver\Manager($this->ini['host']);
  290. $readPreference = new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::RP_PRIMARY);
  291. $query = new MongoDB\Driver\Query($filters, $options);
  292. $cursor = $manager->executeQuery('bancoTeste.cadastro_cpf_nome', $query, $readPreference);
  293. //carrega todos os objetos para contagem
  294. $queryCount = new MongoDB\Driver\Query($filters);
  295. $cursorCount = $manager->executeQuery('bancoTeste.cadastro_cpf_nome', $queryCount, $readPreference);
  296. $objectsCount = json_decode(json_encode($cursorCount->toArray(),true), true);
  297. //https://stackoverflow.com/questions/36726069/how-to-get-cursor-result-count-using-the-mongodb-php-extension
  298. /*
  299. https://www.mongodb.com/community/forums/t/proper-way-to-get-a-php-array-from-aggregate-or-convert-a-mongodb-driver-cursor-to-array/8192
  300. This converts the BSON documents to an array instead of an std object in a single line.
  301. I tryed to convert to stdclass but it returned an empty array
  302. */
  303. $objects = json_decode(json_encode($cursor->toArray(),true), true);
  304. if ($objects)
  305. {
  306. foreach ($objects as $key => $object)
  307. {
  308. $newObject = new stdClass;
  309. $newObject->id = $object['_id']['$oid'];
  310. $newObject->cpf = $object['cpf'];
  311. $newObject->nome = $object['nome'];
  312. $newObject->inativa = $object['inativa'];
  313. // add the object inside the datagrid
  314. $this->datagrid->addItem($newObject);
  315. }
  316. }
  317. if (is_callable($this->transformCallback))
  318. {
  319. call_user_func($this->transformCallback, $objects, $param);
  320. }
  321. $param['limit'] = NULL;
  322. $param['order'] = NULL;
  323. $param['offset'] = NULL;
  324. $param['group'] = NULL;
  325. $count = count($objectsCount);
  326. //$count = $cursor->count($filters, $options);
  327. $this->pageNavigation->setCount($count); // count of records
  328. $this->pageNavigation->setProperties($param); // order, page
  329. $this->pageNavigation->setLimit($limit); // limit
  330. $this->loaded = true;
  331. }
  332. catch (Exception $e) // in case of exception
  333. {
  334. // shows the exception error message
  335. new TMessage('error', $e->getMessage());
  336. // undo all pending operations
  337. TTransaction::rollback();
  338. }
  339. }
  340. /**
  341. * Ask before deletion
  342. */
  343. public function onDelete($param)
  344. {
  345. // define the delete action
  346. $action = new TAction(array($this, 'Delete'));
  347. $action->setParameters($param); // pass the key parameter ahead
  348. // shows a dialog to the user
  349. new TQuestion(AdiantiCoreTranslator::translate('Do you really want to delete ?'), $action);
  350. }
  351. /**
  352. * Delete a record
  353. */
  354. public function Delete($param)
  355. {
  356. try
  357. {
  358. $id = $param['id']; // get the parameter $key
  359. // This path should point to Composer's autoloader
  360. //require '../../../../vendor/autoload.php';
  361. //connect to mongodb
  362. $conexaoMongo = new MongoDB\Client($this->ini['host']);
  363. $banco = $conexaoMongo->bancoTeste;
  364. $cadastro = $banco->cadastro_cpf_nome;
  365. $cadastro->deleteOne( array( '_id' => new MongoDB\BSON\ObjectId ($id)) );
  366. $this->onReload( $param ); // reload the listing
  367. new TMessage('info', AdiantiCoreTranslator::translate('Record deleted')); // success message
  368. TApplication::loadPage('TelaCPFNomeList', '');
  369. }
  370. catch (Exception $e) // in case of exception
  371. {
  372. new TMessage('error', $e->getMessage()); // shows the exception error message
  373. TTransaction::rollback(); // undo all pending operations
  374. }
  375. }
  376. public function show()
  377. {
  378. // check if the datagrid is already loaded
  379. if (!$this->loaded AND (!isset($_GET['method']) OR !(in_array($_GET['method'], array('onReload', 'onSearch', 'onClear')))) )
  380. {
  381. if (func_num_args() > 0)
  382. {
  383. $this->onReload( func_get_arg(0) );
  384. }
  385. else
  386. {
  387. $this->onReload();
  388. }
  389. }
  390. parent::show();
  391. }
  392. function showMessage()
  393. {
  394. new TMessage('info', AdiantiCoreTranslator::translate('Record saved'));
  395. $this->onReload();
  396. }
  397. }
  398. ?>


</your></document></document></boolean></replacement></filter></your>