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

Pacotão Dominando o Adianti Framework 7
O material mais completo de treinamento do Framework.
Curso em vídeo aulas + Livro completo + Códigos fontes do projeto ERPHouse.
Conteúdo Atualizado! Versão 7.4


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