Carregar dados de Composição na Datagrid Possuo uma classe Prova e uma outra chamada Alternativa. Elas estão relacionadas por Composição. Gostaria que uma célula da datagrid que mostra as provas cadastradas trouxesse TODAS as alternativas cadastradas para a respectiva prova. Não entendi como fazer a array de dados aparecer numa única célula da datagrid. O que estou fazendo errado? ...
CS
Carregar dados de Composição na Datagrid  
Possuo uma classe Prova e uma outra chamada Alternativa. Elas estão relacionadas por Composição. Gostaria que uma célula da datagrid que mostra as provas cadastradas trouxesse TODAS as alternativas cadastradas para a respectiva prova. Não entendi como fazer a array de dados aparecer numa única célula da datagrid. O que estou fazendo errado?

 
  1. <?php
 
  1. <?php
  2. class Prova extends TRecord
  3. {
  4. const TABLENAME = 'prova';
  5. const PRIMARYKEY= 'id';
  6. const IDPOLICY = 'serial'; // {max, serial}
  7. private $alternativas;
  8. private $curso;
  9. /**
  10. * Constructor method
  11. */
  12. public function __construct($id = NULL, $callObjectLoad = TRUE)
  13. {
  14. parent::__construct($id, $callObjectLoad);
  15. parent::addAttribute('texto_questao');
  16. parent::addAttribute('caminho_imagem');
  17. parent::addAttribute('curso_id');
  18. }
  19. /**
  20. * Method addAlternativa
  21. * Add a Alternativa to the Prova
  22. * @param $object Instance of Alternativa
  23. */
  24. public function addAlternativa(Alternativa $object)
  25. {
  26. $this->alternativas[] = $object;
  27. }
  28. /**
  29. * Method getAlternativas
  30. * Return the Prova' Alternativa's
  31. * @return Collection of Alternativa
  32. */
  33. public function getAlternativas()
  34. {
  35. // loads the associated object
  36. if (empty($this->alternativa))
  37. // $this->alternativa = Alternativa::where('prova_id', '=', $id)->load();
  38. // foreach ($this->alternativa as $alt)
  39. // {
  40. // $return $alt;
  41. // }
  42. // returns the associated object
  43. return $this->alternativa;
  44. }
  45. /**
  46. * Method getCurso
  47. * Return the Prova' Curso's
  48. * @return Collection of Curso
  49. */
  50. public function get_curso()
  51. {
  52. // loads the associated object
  53. if (empty($this->curso))
  54. $this->curso = new Curso($this->curso_id);
  55. // returns the associated object
  56. return $this->curso;
  57. }
  58. /**
  59. * Reset aggregates
  60. */
  61. public function clearParts()
  62. {
  63. $this->alternativas = array();
  64. }
  65. /**
  66. * Load the object and its aggregates
  67. * @param $id object ID
  68. */
  69. public function load($id)
  70. {
  71. // load the related Alternativa objects
  72. $repository = new TRepository('Alternativa');
  73. $criteria = new TCriteria;
  74. $criteria->add(new TFilter('prova_id', '=', $id));
  75. $this->alternativas = $repository->load($criteria);
  76. // load the object itself
  77. return parent::load($id);
  78. }
  79. /**
  80. * Store the object and its aggregates
  81. */
  82. public function store()
  83. {
  84. // store the object itself
  85. parent::store();
  86. // delete the related Alternativa objects
  87. $criteria = new TCriteria;
  88. $criteria->add(new TFilter('prova_id', '=', $this->id));
  89. $repository = new TRepository('Alternativa');
  90. $repository->delete($criteria);
  91. // store the related Alternativa objects
  92. if ($this->alternativas)
  93. {
  94. foreach ($this->alternativas as $alternativa)
  95. {
  96. unset($alternativa->id);
  97. $alternativa->prova_id = $this->id;
  98. $alternativa->store();
  99. }
  100. }
  101. }
  102. /**
  103. * Delete the object and its aggregates
  104. * @param $id object ID
  105. */
  106. public function delete($id = NULL)
  107. {
  108. $id = isset($id) ? $id : $this->id;
  109. // delete the related Alternativa objects
  110. $repository = new TRepository('Alternativa');
  111. $criteria = new TCriteria;
  112. $criteria->add(new TFilter('prova_id', '=', $id));
  113. $repository->delete($criteria);
  114. // delete the object itself
  115. parent::delete($id);
  116. }
  117. }
  118. ?>

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 (3)


CS

 
  1. <?php
  2. class ProvaList extends TPage
  3. {
  4. private $form; // form
  5. private $datagrid; // listing
  6. private $pageNavigation;
  7. private $formgrid;
  8. private $loaded;
  9. private $deleteButton;
  10. /**
  11. * Class constructor
  12. * Creates the page, the form and the listing
  13. */
  14. public function __construct()
  15. {
  16. parent::__construct();
  17. // creates the form
  18. $this->form = new BootstrapFormBuilder('form_Prova');
  19. $this->form->setFormTitle('Prova');
  20. // create the form fields
  21. $id = new TEntry('id');
  22. $texto_questao = new TEntry('texto_questao');
  23. $caminho_imagem = new TEntry('caminho_imagem');
  24. $curso_id = new TDBUniqueSearch('curso_id', 'permission', 'Curso', 'id', 'nome');
  25. // add the fields
  26. $this->form->addFields( [ new TLabel('Id') ], [ $id ] );
  27. $this->form->addFields( [ new TLabel('Texto Questao') ], [ $texto_questao ] );
  28. $this->form->addFields( [ new TLabel('Caminho Imagem') ], [ $caminho_imagem ] );
  29. $this->form->addFields( [ new TLabel('Curso Id') ], [ $curso_id ] );
  30. // set sizes
  31. $id->setSize('100%');
  32. $texto_questao->setSize('100%');
  33. $caminho_imagem->setSize('100%');
  34. $curso_id->setSize('100%');
  35. // keep the form filled during navigation with session data
  36. $this->form->setData( TSession::getValue('Prova_filter_data') );
  37. // add the search form actions
  38. $btn = $this->form->addAction(_t('Find'), new TAction([$this, 'onSearch']), 'fa:search');
  39. $btn->class = 'btn btn-sm btn-primary';
  40. $this->form->addActionLink(_t('New'), new TAction(['ProvaForm', 'onEdit']), 'fa:plus green');
  41. // creates a Datagrid
  42. $this->datagrid = new BootstrapDatagridWrapper(new TDataGrid);
  43. $this->datagrid->style = 'width: 100%';
  44. $this->datagrid->datatable = 'true';
  45. // $this->datagrid->enablePopover('Popover', 'Hi <b> {Prova::getAlternativas(id)} </b>');
  46. // creates the datagrid columns
  47. $column_id = new TDataGridColumn('id', 'Id', 'right');
  48. $column_texto_questao = new TDataGridColumn('texto_questao', 'Texto Questao', 'left');
  49. $column_caminho_imagem = new TDataGridColumn('caminho_imagem', 'Caminho Imagem', 'left');
  50. $column_curso_id = new TDataGridColumn('curso->nome', 'Curso', 'right');
  51. // $column_id1 = new TDataGridColumn('alternativa', 'Alternativas', 'right');
  52. // add the columns to the DataGrid
  53. $this->datagrid->addColumn($column_id);
  54. $this->datagrid->addColumn($column_texto_questao);
  55. $this->datagrid->addColumn($column_caminho_imagem);
  56. $this->datagrid->addColumn($column_curso_id);
  57. // $this->datagrid->addColumn($column_id1);
  58. // create EDIT action
  59. $action_edit = new TDataGridAction(['ProvaForm', 'onEdit']);
  60. //$action_edit->setUseButton(TRUE);
  61. //$action_edit->setButtonClass('btn btn-default');
  62. $action_edit->setLabel(_t('Edit'));
  63. $action_edit->setImage('fa:pencil-square-o blue fa-lg');
  64. $action_edit->setField('id');
  65. $this->datagrid->addAction($action_edit);
  66. // create DELETE action
  67. $action_del = new TDataGridAction(array($this, 'onDelete'));
  68. //$action_del->setUseButton(TRUE);
  69. //$action_del->setButtonClass('btn btn-default');
  70. $action_del->setLabel(_t('Delete'));
  71. $action_del->setImage('fa:trash-o red fa-lg');
  72. $action_del->setField('id');
  73. $this->datagrid->addAction($action_del);
  74. // create DELETE action
  75. $action_view= new TDataGridAction(array($this, 'onView'));
  76. //$action_del->setUseButton(TRUE);
  77. //$action_del->setButtonClass('btn btn-default');
  78. $action_view->setLabel('Visualizar Alternativas');
  79. $action_view->setImage('fa:search-plus green fa-lg');
  80. $action_view->setField('id');
  81. $this->datagrid->addAction($action_view);
  82. // create the datagrid model
  83. $this->datagrid->createModel();
  84. // creates the page navigation
  85. $this->pageNavigation = new TPageNavigation;
  86. $this->pageNavigation->setAction(new TAction([$this, 'onReload']));
  87. $this->pageNavigation->setWidth($this->datagrid->getWidth());
  88. // vertical box container
  89. $container = new TVBox;
  90. $container->style = 'width: 90%';
  91. // $container->add(new TXMLBreadCrumb('menu.xml', __CLASS__));
  92. $container->add($this->form);
  93. $container->add(TPanelGroup::pack('', $this->datagrid, $this->pageNavigation));
  94. parent::add($container);
  95. }
  96. /**
  97. * Inline record editing
  98. * @param $param Array containing:
  99. * key: object ID value
  100. * field name: object attribute to be updated
  101. * value: new attribute content
  102. */
  103. public function onInlineEdit($param)
  104. {
  105. try
  106. {
  107. // get the parameter $key
  108. $field = $param['field'];
  109. $key = $param['key'];
  110. $value = $param['value'];
  111. TTransaction::open('permission'); // open a transaction with database
  112. $object = new Prova($key); // instantiates the Active Record
  113. $object->{$field} = $value;
  114. $object->store(); // update the object in the database
  115. TTransaction::close(); // close the transaction
  116. $this->onReload($param); // reload the listing
  117. new TMessage('info', "Record Updated");
  118. }
  119. catch (Exception $e) // in case of exception
  120. {
  121. new TMessage('error', $e->getMessage()); // shows the exception error message
  122. TTransaction::rollback(); // undo all pending operations
  123. }
  124. }
  125. /**
  126. * Register the filter in the session
  127. */
  128. public function onSearch()
  129. {
  130. // get the search form data
  131. $data = $this->form->getData();
  132. // clear session filters
  133. TSession::setValue('ProvaList_filter_id', NULL);
  134. TSession::setValue('ProvaList_filter_texto_questao', NULL);
  135. TSession::setValue('ProvaList_filter_caminho_imagem', NULL);
  136. TSession::setValue('ProvaList_filter_curso_id', NULL);
  137. if (isset($data->id) AND ($data->id)) {
  138. $filter = new TFilter('id', '=', "$data->id"); // create the filter
  139. TSession::setValue('ProvaList_filter_id', $filter); // stores the filter in the session
  140. }
  141. if (isset($data->texto_questao) AND ($data->texto_questao)) {
  142. $filter = new TFilter('texto_questao', 'like', "%{$data->texto_questao}%"); // create the filter
  143. TSession::setValue('ProvaList_filter_texto_questao', $filter); // stores the filter in the session
  144. }
  145. if (isset($data->caminho_imagem) AND ($data->caminho_imagem)) {
  146. $filter = new TFilter('caminho_imagem', 'like', "%{$data->caminho_imagem}%"); // create the filter
  147. TSession::setValue('ProvaList_filter_caminho_imagem', $filter); // stores the filter in the session
  148. }
  149. if (isset($data->curso_id) AND ($data->curso_id)) {
  150. $filter = new TFilter('curso_id', '=', "$data->curso_id"); // create the filter
  151. TSession::setValue('ProvaList_filter_curso_id', $filter); // stores the filter in the session
  152. }
  153. // fill the form with data again
  154. $this->form->setData($data);
  155. // keep the search data in the session
  156. TSession::setValue('Prova_filter_data', $data);
  157. $param = array();
  158. $param['offset'] =0;
  159. $param['first_page']=1;
  160. $this->onReload($param);
  161. }
  162. /**
  163. * Load the datagrid with data
  164. */
  165. public function onReload($param = NULL)
  166. {
  167. try
  168. {
  169. // open a transaction with database 'permission'
  170. TTransaction::open('permission');
  171. // creates a repository for Prova
  172. $repository = new TRepository('Prova');
  173. $limit = 10;
  174. // creates a criteria
  175. $criteria = new TCriteria;
  176. // default order
  177. if (empty($param['order']))
  178. {
  179. $param['order'] = 'id';
  180. $param['direction'] = 'asc';
  181. }
  182. $criteria->setProperties($param); // order, offset
  183. $criteria->setProperty('limit', $limit);
  184. if (TSession::getValue('ProvaList_filter_id')) {
  185. $criteria->add(TSession::getValue('ProvaList_filter_id')); // add the session filter
  186. }
  187. if (TSession::getValue('ProvaList_filter_texto_questao')) {
  188. $criteria->add(TSession::getValue('ProvaList_filter_texto_questao')); // add the session filter
  189. }
  190. if (TSession::getValue('ProvaList_filter_caminho_imagem')) {
  191. $criteria->add(TSession::getValue('ProvaList_filter_caminho_imagem')); // add the session filter
  192. }
  193. if (TSession::getValue('ProvaList_filter_curso_id')) {
  194. $criteria->add(TSession::getValue('ProvaList_filter_curso_id')); // add the session filter
  195. }
  196. // $alternativa = Alternativa::where('prova_id', '=', '1')->load();
  197. // $this->datagrid->addItems($alternativa);
  198. // load the objects according to criteria
  199. $objects = $repository->load($criteria, FALSE);
  200. if (is_callable($this->transformCallback))
  201. {
  202. call_user_func($this->transformCallback, $objects, $param);
  203. }
  204. $this->datagrid->clear();
  205. if ($objects)
  206. {
  207. // iterate the collection of active records
  208. foreach ($objects as $object)
  209. {
  210. // add the object inside the datagrid
  211. $this->datagrid->addItem($object);
  212. }
  213. }
  214. // reset the criteria for record count
  215. $criteria->resetProperties();
  216. $count= $repository->count($criteria);
  217. $this->pageNavigation->setCount($count); // count of records
  218. $this->pageNavigation->setProperties($param); // order, page
  219. $this->pageNavigation->setLimit($limit); // limit
  220. // close the transaction
  221. TTransaction::close();
  222. $this->loaded = true;
  223. }
  224. catch (Exception $e) // in case of exception
  225. {
  226. // shows the exception error message
  227. new TMessage('error', $e->getMessage());
  228. // undo all pending operations
  229. TTransaction::rollback();
  230. }
  231. }
  232. /**
  233. * Ask before deletion
  234. */
  235. public static function onDelete($param)
  236. {
  237. // define the delete action
  238. $action = new TAction([__CLASS__, 'Delete']);
  239. $action->setParameters($param); // pass the key parameter ahead
  240. // shows a dialog to the user
  241. new TQuestion(TAdiantiCoreTranslator::translate('Do you really want to delete ?'), $action);
  242. }
  243. /**
  244. * Delete a record
  245. */
  246. public static function Delete($param)
  247. {
  248. try
  249. {
  250. $key=$param['key']; // get the parameter $key
  251. TTransaction::open('permission'); // open a transaction with database
  252. $object = new Prova($key, FALSE); // instantiates the Active Record
  253. $object->delete(); // deletes the object from the database
  254. TTransaction::close(); // close the transaction
  255. $pos_action = new TAction([__CLASS__, 'onReload']);
  256. new TMessage('info', TAdiantiCoreTranslator::translate('Record deleted'), $pos_action); // success message
  257. }
  258. catch (Exception $e) // in case of exception
  259. {
  260. new TMessage('error', $e->getMessage()); // shows the exception error message
  261. TTransaction::rollback(); // undo all pending operations
  262. }
  263. }
  264. /**
  265. * Delete a record
  266. */
  267. public static function onView($param)
  268. {
  269. try
  270. {
  271. $key = $param['key'];
  272. $win = TWindow::create('Alternativas', 0.6, 0.4);
  273. TTransaction::open('permission');
  274. $pergunta = new Prova($key);
  275. $alternativas = Alternativa::where('prova_id', '=', $key)->load();
  276. $win->add("$pergunta->texto_questao<br><br>");
  277. if ($alternativas)
  278. {
  279. $win->add("<ol type='A'>");
  280. foreach ($alternativas as $alt)
  281. {
  282. $win->add("<li>$alt->texto_alternativa</li>");
  283. }
  284. $win->add("</ol>");
  285. }
  286. $win->show();
  287. TTransaction::close();
  288. }
  289. catch (Exception $e) // in case of exception
  290. {
  291. new TMessage('error', $e->getMessage()); // shows the exception error message
  292. TTransaction::rollback(); // undo all pending operations
  293. }
  294. }
  295. /**
  296. * method show()
  297. * Shows the page
  298. */
  299. public function show()
  300. {
  301. // check if the datagrid is already loaded
  302. if (!$this->loaded AND (!isset($_GET['method']) OR !(in_array($_GET['method'], array('onReload', 'onSearch')))) )
  303. {
  304. if (func_num_args() > 0)
  305. {
  306. $this->onReload( func_get_arg(0) );
  307. }
  308. else
  309. {
  310. $this->onReload();
  311. }
  312. }
  313. parent::show();
  314. }
  315. }
  316. ?>
FC

Cleber

Se entendi, vc precisa de uma datagrid onde mostre "grupos" de "alternativas" por "prova" imagino que seja isso.

Tenta usar o setGroup
$this->datagrid->setGroupColumn(....

Exemplo
adianti.com.br/framework_files/tutor/index.php?class=DatagridColumnG
CS

Felipe,

muito obrigado. A sua dica resolveu o meu problema!