Lançado Adianti Framework 7.6!
Clique aqui para saber mais
key da TDataGrid Olá! Estou desenvolvendo uma aplicação onde uma listagem de dados (contas) leva a outra listagem de dados (movimentos da conta de uma conta especifica). Logo, na primeira listagem tenho na URL &key=id_do_objeto_conta; Na segunda listagem, leio o ID para carregar somente os movimentos da conta selecionada; Mas, na segunda listagem, cada linha tem o parâmetro &key=id_do_objeto_movime...
MD
key da TDataGrid  
Fechado
Olá!

Estou desenvolvendo uma aplicação onde uma listagem de dados (contas) leva a outra listagem de dados (movimentos da conta de uma conta especifica).

Logo, na primeira listagem tenho na URL &key=id_do_objeto_conta;

Na segunda listagem, leio o ID para carregar somente os movimentos da conta selecionada;

Mas, na segunda listagem, cada linha tem o parâmetro &key=id_do_objeto_movimento, logo, quando peço para remover um item, ele chama a listagem novamente, mas, sem o ID da conta, e sim com o ID do movimento.

Para resolver esse detalhe, copiei a classe TDataGrid para a área que tenho em minha aplicação onde eventualmente alguma classe do framework é "sobrescrita" (para tal modifiquei a classe TAdiantiLoader para buscar primeiro as classes em app/lib/adianti_mod dessa forma não modifico nenhum arquivo do framework e sei quais classes devem ser verificadas em um update do framework) e então criei um metodo chamado setKey onde posso setar um novo key para a TDataGrid.

Abaixo segue a classe espero que possa ajudar:

  1. <?php
  2. /**
  3.  * DataGrid Widget: Allows to create datagrids with rows, columns and actions
  4.  *
  5.  * @version    1.0
  6.  * @package    widget_web
  7.  * @subpackage datagrid
  8.  * @author     Pablo Dall'Oglio
  9.  * @author     Marco A. Driemeyer <marco@plenatech.com.br>
  10.  * @copyright  Copyright (c) 2006-2013 Adianti Solutions Ltd. (http://www.adianti.com.br)
  11.  * @license    http://www.adianti.com.br/framework-license
  12.  */
  13. class TDataGrid extends TTable
  14. {
  15.     private $columns;
  16.     private $actions;
  17.     private $rowcount;
  18.     private $tbody;
  19.     private $height;
  20.     private $scrollable;
  21.     private $modelCreated;
  22.     private $pageNavigation;
  23.     private $defaultClick;
  24.     
  25.     /**
  26.      * Essa Classe foi modificada para que se possa setar o nome do field passado
  27.      * para a datagrid, por padrão seu nome é key, mas, eventualmente como na
  28.      * classe ContaControleMovimentoList é necessário mudar o nome da Key
  29.      */
  30.     private $key// variavel para receber o nome da key
  31.     // o mesmo bloco de comentario acima será repetido e cada mudança realizada na classe para poder melhor verificar as alterações
  32.     
  33.     /**
  34.      * Class Constructor
  35.      */
  36.     public function __construct()
  37.     {
  38.         parent::__construct();
  39.         $this->modelCreated FALSE;
  40.         $this->defaultClick TRUE;
  41.         
  42.         $this->{'class'} = 'tdatagrid_table';
  43.         $this-> id    'tdatagrid_table';
  44.         /**
  45.          * Essa Classe foi modificada para que se possa setar o nome do field passado
  46.          * para a datagrid, por padrão seu nome é key, mas, eventualmente como na
  47.          * classe ContaControleMovimentoList é necessário mudar o nome da Key
  48.          */
  49.         $this->key 'key'// no contruct seta o nome default de key
  50.     }
  51.     
  52.     
  53.     /**
  54.      * Essa Classe foi modificada para que se possa setar o nome do field passado
  55.      * para a datagrid, por padrão seu nome é key, mas, eventualmente como na
  56.      * classe ContaControleMovimentoList é necessário mudar o nome da Key
  57.      */
  58.      /**
  59.       * Metodo que seta o nome da Key da datagrid
  60.       */
  61.      public function setKey($key){
  62.          $this->key $key;
  63.      }
  64.     
  65.     
  66.     /**
  67.      * Make the datagrid scrollable
  68.      */
  69.     public function makeScrollable()
  70.     {
  71.         $this->scrollable TRUE;
  72.     }
  73.     
  74.     /**
  75.      * disable the default click action
  76.      */
  77.     public function disableDefaultClick()
  78.     {
  79.         $this->defaultClick FALSE;
  80.     }
  81.     
  82.     /**
  83.      * Define the Height
  84.      * @param $height An integer containing the height
  85.      */
  86.     function setHeight($height)
  87.     {
  88.         $this->height $height;
  89.     }
  90.     
  91.     /**
  92.      * Add a Column to the DataGrid
  93.      * @param $object A TDataGridColumn object
  94.      */
  95.     public function addColumn(TDataGridColumn $object)
  96.     {
  97.         if ($this->modelCreated)
  98.         {
  99.             throw new Exception(TAdiantiCoreTranslator::translate('You must call ^1 before ^2'__METHOD__ 'createModel') );
  100.         }
  101.         else
  102.         {
  103.             $this->columns[] = $object;
  104.         }
  105.     }
  106.     
  107.     /**
  108.      * Add an Action to the DataGrid
  109.      * @param $object A TDataGridAction object
  110.      */
  111.     public function addAction(TDataGridAction $object)
  112.     {
  113.         if ($this->modelCreated)
  114.         {
  115.             throw new Exception(TAdiantiCoreTranslator::translate('You must call ^1 before ^2'__METHOD__ 'createModel') );
  116.         }
  117.         else
  118.         {
  119.             $this->actions[] = $object;
  120.         }
  121.     }
  122.     
  123.     /**
  124.      * Clear the DataGrid contents
  125.      */
  126.     function clear()
  127.     {
  128.         if ($this->modelCreated)
  129.         {
  130.             // copy the headers
  131.             $copy $this->children[0];
  132.             // reset the row array
  133.             $this->children = array();
  134.             // add the header again
  135.             $this->children[] = $copy;
  136.             
  137.             // add an empty body
  138.             $this->tbody = new TElement('tbody');
  139.             $this->tbody->{'class'} = 'tdatagrid_body';
  140.             if ($this->scrollable)
  141.             {
  142.                 $this->tbody->{'style'} = "height: {$this->height}px; display: block; overflow-y:scroll; overflow-x:hidden;";
  143.             }
  144.             parent::add($this->tbody);
  145.             
  146.             // restart the row count
  147.             $this->rowcount 0;
  148.         }
  149.     }
  150.     
  151.     /**
  152.      * Creates the DataGrid Structure
  153.      */
  154.     public function createModel()
  155.     {
  156.         if (!$this->columns)
  157.         {
  158.             return;
  159.         }
  160.         
  161.         $thead = new TElement('thead');
  162.         $thead->{'class'} = 'tdatagrid_head';
  163.         parent::add($thead);
  164.         
  165.         $row = new TElement('tr');
  166.         if ($this->scrollable)
  167.         {
  168.             $row->{'style'} = 'display:block';
  169.         }
  170.         $thead->add($row);
  171.         
  172.         // add some cells for the actions
  173.         if ($this->actions)
  174.         {
  175.             foreach ($this->actions as $action)
  176.             {
  177.                 $cell = new TElement('td');
  178.                 $row->add($cell);
  179.                 $cell->add('&nbsp;');
  180.                 $cell->{'class'} = 'tdatagrid_col';
  181.                 $cell-> width '15px';
  182.             }
  183.         }
  184.         
  185.         // add some cells for the data
  186.         if ($this->columns)
  187.         {
  188.             // iterate the DataGrid columns
  189.             foreach ($this->columns as $column)
  190.             {
  191.                 // get the column properties
  192.                 $name  $column->getName();
  193.                 $label '&nbsp;'.$column->getLabel().'&nbsp;';
  194.                 $align $column->getAlign();
  195.                 $width $column->getWidth();
  196.                 if (isset($_GET['order']))
  197.                 {
  198.                     if ($_GET['order'] == $name)
  199.                     {
  200.                         $label .= '<img src="lib/adianti/images/ico_down.png">';
  201.                     }
  202.                 }
  203.                 // add a cell with the columns label
  204.                 $cell = new TElement('td');
  205.                 $row->add($cell);
  206.                 $cell->add($label);
  207.                 
  208.                 $cell->{'class'} = 'tdatagrid_col';
  209.                 $cell-> align $align;
  210.                 if ($width)
  211.                 {
  212.                     //$cell-> width = $width.'px';
  213.                     $cell-> width = ($width+7).'px';
  214.                 }
  215.                 
  216.                 // verify if the column has an attached action
  217.                 if ($column->getAction())
  218.                 {
  219.                     $url $column->getAction();
  220.                     $cell-> onmouseover "this.className='tdatagrid_col_over';";
  221.                     $cell-> onmouseout  "this.className='tdatagrid_col'";
  222.                     $cell-> href        $url;
  223.                     $cell-> generator   'adianti';
  224.                 }
  225.             }
  226.         }
  227.         
  228.         // add one row to the DataGrid
  229.         $this->tbody = new TElement('tbody');
  230.         $this->tbody->{'class'} = 'tdatagrid_body';
  231.         if ($this->scrollable)
  232.         {
  233.             $this->tbody->{'style'} = "height: {$this->height}px; display: block; overflow-y:scroll; overflow-x:hidden;";
  234.         }
  235.         parent::add($this->tbody);
  236.         
  237.         $this->modelCreated TRUE;
  238.     }
  239.     
  240.     /**
  241.      * Add an object to the DataGrid
  242.      * @param $object An Active Record Object
  243.      */
  244.     public function addItem($object)
  245.     {
  246.         if ($this->modelCreated)
  247.         {
  248.             // define the background color for that line
  249.             $classname = ($this->rowcount 2) == 'tdatagrid_row_even' 'tdatagrid_row_odd';
  250.             
  251.             $row = new TElement('tr');
  252.             $this->tbody->add($row);
  253.             $row->{'class'} = $classname;
  254.             
  255.             // verify if the DataGrid has ColumnActions
  256.             if ($this->actions)
  257.             {
  258.                 // iterate the actions
  259.                 foreach ($this->actions as $action)
  260.                 {
  261.                     // get the action properties
  262.                     $field  $action->getField();
  263.                     $label  $action->getLabel();
  264.                     $image  $action->getImage();
  265.                     
  266.                     if (is_null($field))
  267.                     {
  268.                         throw new Exception(TAdiantiCoreTranslator::translate('Field for action ^1 not defined'$label) . '.<br>' 
  269.                                             TAdiantiCoreTranslator::translate('Use the ^1 method''setField'.'()').'.');
  270.                     }
  271.                     
  272.                     // get the object property that will be passed ahead
  273.                     $key    $object->$field;
  274.                     
  275.                     /**
  276.                      * Essa Classe foi modificada para que se possa setar o nome do field passado
  277.                      * para a datagrid, por padrão seu nome é key, mas, eventualmente como na
  278.                      * classe ContaControleMovimentoList é necessário mudar o nome da Key
  279.                      */    
  280.                     //$action->setParameter('key', $key);
  281.                     $action->setParameter($this->key$key);
  282.                     $url    $action->serialize();
  283.                     
  284.                     // creates a link
  285.                     $link = new TElement('a');
  286.                     $link-> href      $url;
  287.                     $link-> generator 'adianti';
  288.                     
  289.                     $first_url = isset($first_url) ? $first_url $link-> href;
  290.                     
  291.                     // verify if the link will have an icon or a label
  292.                     if ($image)
  293.                     {
  294.                         // add the image to the link
  295.                         if (file_exists("lib/adianti/images/$image"))
  296.                         {
  297.                             $image=new TImage("lib/adianti/images/$image");
  298.                         }
  299.                         else
  300.                         {
  301.                             $image=new TImage("app/images/$image");
  302.                         }
  303.                         $image-> title $label;
  304.                         $link->add($image);
  305.                     }
  306.                     else
  307.                     {
  308.                         // add the label to the link
  309.                         $link->add($label);
  310.                     }
  311.                     // add the cell to the row
  312.                     $cell = new TElement('td');
  313.                     $row->add($cell);
  314.                     $cell->add($link);
  315.                     $cell-> width '16px';
  316.                     $cell->{'class'} = 'tdatagrid_cell';
  317.                 }
  318.             }
  319.             if ($this->columns)
  320.             {
  321.                 // iterate the DataGrid columns
  322.                 foreach ($this->columns as $column)
  323.                 {
  324.                     // get the column properties
  325.                     $name     $column->getName();
  326.                     $align    $column->getAlign();
  327.                     $width    $column->getWidth();
  328.                     $function $column->getTransformer();
  329.                     $data     is_null($object->$name) ? '' $object->$name;
  330.                     // verify if there's a transformer function
  331.                     if ($function)
  332.                     {
  333.                         // apply the transformer functions over the data
  334.                         $data call_user_func($function$data);
  335.                     }
  336.                     
  337.                     if ($editaction $column->getEditAction())
  338.                     {
  339.                         $editaction_field $editaction->getField();
  340.                         $div = new TElement('div');
  341.                         $div->{'class'}  = 'inlineediting';
  342.                         $div->{'style'}  = 'padding-left:5px;padding-right:5px';
  343.                         $div->{'action'} = $editaction->serialize();
  344.                         $div->{'field'}  = $name;
  345.                         $div->{'key'}    = $object->{$editaction_field};
  346.                         $div->add($data);
  347.                         $cell = new TElement('td');
  348.                         $row->add($cell);
  349.                         $cell->add($div);
  350.                         $cell->{'class'} = 'tdatagrid_cell';
  351.                     }
  352.                     else
  353.                     {
  354.                         // add the cell to the row
  355.                         $cell = new TElement('td');
  356.                         $row->add($cell);
  357.                         $cell->add($data);
  358.                         $cell->{'class'} = 'tdatagrid_cell';
  359.                         $cell-> align $align;
  360.                         $cell->{'style'} = 'padding-left:5px;padding-right:5px';
  361.                         if (isset($first_url) AND $this->defaultClick)
  362.                         {
  363.                             $cell-> href      $first_url;
  364.                             $cell-> generator 'adianti';
  365.                         }
  366.                     }
  367.                     if ($width)
  368.                     {
  369.                         $cell-> width $width.'px';
  370.                     }
  371.                 }
  372.             }
  373.             
  374.             // when the mouse is over the datagrid row
  375.              $row-> onmouseover "className='tdatagrid_row_sel'; style.cursor='pointer'";
  376.              $row-> onmouseout  "className='{$classname}';";
  377.             
  378.             // increments the row counter
  379.             $this->rowcount ++;
  380.         }
  381.         else
  382.         {
  383.             throw new Exception(TAdiantiCoreTranslator::translate('You must call ^1 before ^2''createModel'__METHOD__ ) );
  384.         }
  385.     }
  386.     
  387.     /**
  388.      * Returns the DataGrid's width
  389.      * @return An integer containing the DataGrid's width
  390.      */
  391.     public function getWidth()
  392.     {
  393.         $width=0;
  394.         if ($this->actions)
  395.         {
  396.             // iterate the DataGrid Actions
  397.             foreach ($this->actions as $action)
  398.             {
  399.                 $width += 22;
  400.             }
  401.         }
  402.         
  403.         if ($this->columns)
  404.         {
  405.             // iterate the DataGrid Columns
  406.             foreach ($this->columns as $column)
  407.             {
  408.                 $width += $column->getWidth();
  409.             }
  410.         }
  411.         return $width;
  412.     }
  413.     
  414.     /**
  415.      * Shows the DataGrid
  416.      */
  417.     function show()
  418.     {
  419.         TPage::include_css('lib/adianti/include/tdatagrid/tdatagrid.css');
  420.         // shows the datagrid
  421.         parent::show();
  422.         
  423.         $params $_REQUEST;
  424.         unset($params['class']);
  425.         unset($params['method']);
  426.         // to keep browsing parameters (order, page, first_page, ...)
  427.         $urlparams='&'.http_build_query($params);
  428.         
  429.         // inline editing treatment
  430.         $script = new TElement('script');
  431.         $script->add('$(function() {
  432.             $(".inlineediting").editInPlace({
  433.                 callback: function(unused, enteredText)
  434.                 {
  435.                     __adianti_load_page($(this).attr("action")+"'.$urlparams.'&key="+$(this).attr("key")+"&field="+$(this).attr("field")+"&value="+encodeURIComponent(enteredText));
  436.                     return enteredText;
  437.                 },
  438.                 show_buttons: false,
  439.                 text_size:20,
  440.                 params:column=name
  441.             });
  442.         });');
  443.         $script->show();
  444.     }
  445.     
  446.     /**
  447.      * Assign a PageNavigation object
  448.      * @param $pageNavigation object
  449.      */
  450.     function setPageNavigation($pageNavigation)
  451.     {
  452.         $this->pageNavigation $pageNavigation;
  453.     }
  454.     
  455.     /**
  456.      * Return the assigned PageNavigation object
  457.      * @return $pageNavigation object
  458.      */
  459.     function getPageNavigation()
  460.     {
  461.         return $this->pageNavigation;
  462.     }
  463. }
  464. ?>



No construct da classe de movimentos da conta sempre leio o ID da conta movimentada e então posso montar um link assim na listagem "...&method=onDelete&key=id_da_conta&id_movimento=id_do_movimento"

Abaixo exemplo de utilização:

  1. <?php
  2. public function __construct()
  3. {
  4.     ...
  5.     // creates a DataGrid
  6.     $this->datagrid = new TDataGrid;
  7.     $this->datagrid->setHeight(320);
  8.     $this->datagrid->setKey('id_movimento'); // seta uma nova key para a TDataGrid
  9.     ...
  10.     $action2 = new TDataGridAction(array($this'onDelete'));
  11.     $action2->setParameter('key'$this->id_conta); // aqui seto o real id da conta
  12.     $action2->setLabel('Delete');
  13.     $action2->setImage('ico_delete.png');
  14.     $action2->setField('id');
  15.         
  16.     // add the actions to the datagrid
  17.     $this->datagrid->addAction($action2);
  18. }
  19. ?>


Espero ter ajudado.

Um forte abraço!

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


AS

opa Marco Driemeyer, deixa eu ver se entendi vocẽ tem a conta, e quando clica na conta quer mostrar os movimentos referentes a quela conta.

se for isso é facil, fassa um listagem usando a TPage mesmo, lista os dados, depois envia a key para uma ContasMovimento que é uma StandartGrid, se seu banco tiver feito redondinho da certo, fiz isso com um modulo de vendas, para adicionar itens a venda, a ideia é a mesma, precisando tamo no skype

ale-php