Lançado Adianti Framework 7.6!
Clique aqui para saber mais
Carregar dados de um Datagrid Boa tarde a todos, Preciso carregar os dados de um datagrid de uma tela mestre detalhe. O que acontece é que se eu fizer: ...
WS
Carregar dados de um Datagrid  
Boa tarde a todos,

Preciso carregar os dados de um datagrid de uma tela mestre detalhe. O que acontece é que se eu fizer:

  1. <?php
  2.         $data $this->datagrid->getItems();
  3.        // var_dump($data);
  4.         if($data)
  5.         {
  6.             foreach ($data as $registro)
  7.             {
  8.                 $teste 'teste: ' $registro->id;
  9.                 echo $teste;
  10.                 
  11.             }
  12.         
  13.     }
  14. ?>


não consigo pegar dados. Lei as postagens antigas mas nenhuma resolveu.

Não vou colocar meu codigo aqui porque vai ocupar muito espaço. Vou colar um codigo do tutor com o método save alterado para entendimento apenas. Se conseguir fazer o getItems funcionar eu sigo tranquilo. Segue o código:

  1. <?php
  2. /**
  3. class SaleForm extends TWindow
  4. {
  5.     protected $form; // form
  6.     
  7.     /**
  8.      * Class constructor
  9.      * Creates the page and the registration form
  10.      */
  11.     function __construct()
  12.     {
  13.         parent::__construct();
  14.         parent::setSize(0.8null);
  15.         parent::removePadding();
  16.         parent::removeTitleBar();
  17.         parent::disableEscape();
  18.         
  19.         // creates the form
  20.         $this->form = new BootstrapFormBuilder('form_Sale');
  21.         $this->form->setFormTitle('Sale');
  22.         $this->form->setProperty('style''margin:0;border:0');
  23.         $this->form->setClientValidation(true);
  24.         
  25.         // master fields
  26.         $id          = new TEntry('id');
  27.         $date        = new TDate('date');
  28.         $customer_id = new TDBUniqueSearch('customer_id''samples''Customer''id''name');
  29.         $obs         = new TText('obs');
  30.         
  31.         $button = new TActionLink('', new TAction(['CustomerFormWindow''onEdit']), 'green'nullnull'fa:plus-circle');
  32.         $button->class 'btn btn-default inline-button';
  33.         $button->title _t('New');
  34.         $customer_id->after($button);
  35.         
  36.         // detail fields
  37.         $product_detail_unqid      = new THidden('product_detail_uniqid');
  38.         $product_detail_id         = new THidden('product_detail_id');
  39.         $product_detail_product_id = new TDBUniqueSearch('product_detail_product_id''samples''Product''id''description');
  40.         $product_detail_price      = new TEntry('product_detail_price');
  41.         $product_detail_amount     = new TEntry('product_detail_amount');
  42.         $product_detail_discount   = new TEntry('product_detail_discount');
  43.         $product_detail_total      = new TEntry('product_detail_total');
  44.         
  45.         // adjust field properties
  46.         $id->setEditable(false);
  47.         //$customer_id->setSize('100%');
  48.         $customer_id->setSize('calc(100% - 30px)');
  49.         $customer_id->setMinLength(1);
  50.         $date->setSize('100%');
  51.         $obs->setSize('100%'80);
  52.         $product_detail_product_id->setSize('100%');
  53.         $product_detail_product_id->setMinLength(1);
  54.         $product_detail_price->setSize('100%');
  55.         $product_detail_amount->setSize('100%');
  56.         $product_detail_discount->setSize('100%');
  57.         
  58.         // add validations
  59.         $date->addValidation('Date', new TRequiredValidator);
  60.         $customer_id->addValidation('Customer', new TRequiredValidator);
  61.         
  62.         // change action
  63.         $product_detail_product_id->setChangeAction(new TAction([$this,'onProductChange']));
  64.         
  65.         // add master form fields
  66.         $this->form->addFields( [new TLabel('ID')], [$id], 
  67.                                 [new TLabel('Date (*)''#FF0000')], [$date] );
  68.         $this->form->addFields( [new TLabel('Customer (*)''#FF0000')], [$customer_id ] );
  69.         $this->form->addFields( [new TLabel('Obs')], [$obs] );
  70.         
  71.         $this->form->addContent( ['<h4>Details</h4><hr>'] );
  72.         $this->form->addFields( [ $product_detail_unqid], [$product_detail_id] );
  73.         $this->form->addFields( [ new TLabel('Product (*)''#FF0000') ], [$product_detail_product_id],
  74.                                 [ new TLabel('Amount(*)''#FF0000') ],   [$product_detail_amount] );
  75.         $this->form->addFields( [ new TLabel('Price (*)''#FF0000') ],   [$product_detail_price],
  76.                                 [ new TLabel('Discount')],                [$product_detail_discount] );
  77.         
  78.         $add_product TButton::create('add_product', [$this'onProductAdd'], 'Register''fa:plus-circle green');
  79.         $add_product->getAction()->setParameter('static','1');
  80.         $this->form->addFields( [], [$add_product] );
  81.         
  82.         $this->product_list = new BootstrapDatagridWrapper(new TDataGrid);
  83.         $this->product_list->setHeight(150);
  84.         $this->product_list->makeScrollable();
  85.         $this->product_list->setId('products_list');
  86.         $this->product_list->generateHiddenFields();
  87.         $this->product_list->style "min-width: 700px; width:100%;margin-bottom: 10px";
  88.         
  89.         $col_uniq   = new TDataGridColumn'uniqid''Uniqid''center''10%');
  90.         $col_id     = new TDataGridColumn'id''ID''center''10%');
  91.         $col_pid    = new TDataGridColumn'product_id''ProdID''center''10%');
  92.         $col_descr  = new TDataGridColumn'product_id''Product''left''30%');
  93.         $col_amount = new TDataGridColumn'amount''Amount''left''10%');
  94.         $col_price  = new TDataGridColumn'sale_price''Price''right''15%');
  95.         $col_disc   = new TDataGridColumn'discount''Discount''right''15%');
  96.         $col_subt   = new TDataGridColumn'={amount} * ( {sale_price} - {discount} )''Subtotal''right''20%');
  97.         
  98.         $this->product_list->addColumn$col_uniq );
  99.         $this->product_list->addColumn$col_id );
  100.         $this->product_list->addColumn$col_pid );
  101.         $this->product_list->addColumn$col_descr );
  102.         $this->product_list->addColumn$col_amount );
  103.         $this->product_list->addColumn$col_price );
  104.         $this->product_list->addColumn$col_disc );
  105.         $this->product_list->addColumn$col_subt );
  106.         
  107.         $col_descr->setTransformer(function($value) {
  108.             return Product::findInTransaction('samples'$value)->description;
  109.         });
  110.         
  111.         $col_subt->enableTotal('sum''R$'2',''.');
  112.         
  113.         $col_id->setVisibility(false);
  114.         $col_uniq->setVisibility(false);
  115.         
  116.         // creates two datagrid actions
  117.         $action1 = new TDataGridAction([$this'onEditItemProduto'] );
  118.         $action1->setFields( ['uniqid''*'] );
  119.         
  120.         $action2 = new TDataGridAction([$this'onDeleteItem']);
  121.         $action2->setField('uniqid');
  122.         
  123.         // add the actions to the datagrid
  124.         $this->product_list->addAction($action1_t('Edit'), 'far:edit blue');
  125.         $this->product_list->addAction($action2_t('Delete'), 'far:trash-alt red');
  126.         
  127.         $this->product_list->createModel();
  128.         
  129.         $panel = new TPanelGroup;
  130.         $panel->add($this->product_list);
  131.         $panel->getBody()->style 'overflow-x:auto';
  132.         $this->form->addContent( [$panel] );
  133.         
  134.         $format_value = function($value) {
  135.             if (is_numeric($value)) {
  136.                 return 'R$ '.number_format($value2',''.');
  137.             }
  138.             return $value;
  139.         };
  140.         
  141.         $col_price->setTransformer$format_value );
  142.         $col_disc->setTransformer$format_value );
  143.         $col_subt->setTransformer$format_value );
  144.         
  145.         $this->form->addHeaderActionLink_t('Close'),  new TAction([__CLASS__'onClose'], ['static'=>'1']), 'fa:times red');
  146.         $this->form->addAction'Save',  new TAction([$this'onSave'], ['static'=>'1']), 'fa:save green');
  147.         $this->form->addAction'Clear', new TAction([$this'onClear']), 'fa:eraser red');
  148.         
  149.         // create the page container
  150.         $container = new TVBox;
  151.         $container->style 'width: 100%';
  152.         //$container->add(new TXMLBreadCrumb('menu.xml', __CLASS__));
  153.         $container->add($this->form);
  154.         parent::add($container);
  155.     }
  156.     
  157.     /**
  158.      * Pre load some data
  159.      */
  160.     public function onLoad($param)
  161.     {
  162.         $data = new stdClass;
  163.         $data->customer_id   $param['customer_id'];
  164.         $this->form->setData($data);
  165.     }
  166.     
  167.     
  168.     /**
  169.      * On product change
  170.      */
  171.     public static function onProductChange$params )
  172.     {
  173.         if( !empty($params['product_detail_product_id']) )
  174.         {
  175.             try
  176.             {
  177.                 TTransaction::open('samples');
  178.                 $product   = new Product($params['product_detail_product_id']);
  179.                 TForm::sendData('form_Sale', (object) ['product_detail_price' => $product->sale_price ]);
  180.                 TTransaction::close();
  181.             }
  182.             catch (Exception $e)
  183.             {
  184.                 new TMessage('error'$e->getMessage());
  185.                 TTransaction::rollback();
  186.             }
  187.         }
  188.     }
  189.     
  190.     
  191.     /**
  192.      * Clear form
  193.      * @param $param URL parameters
  194.      */
  195.     function onClear($param)
  196.     {
  197.         $this->form->clear();
  198.     }
  199.     
  200.     /**
  201.      * Add a product into item list
  202.      * @param $param URL parameters
  203.      */
  204.     public function onProductAdd$param )
  205.     {
  206.         try
  207.         {
  208.             $this->form->validate();
  209.             $data $this->form->getData();
  210.             
  211.             if( (! $data->product_detail_product_id) || (! $data->product_detail_amount) || (! $data->product_detail_price) )
  212.             {
  213.                 throw new Exception('The fields Product, Amount and Price are required');
  214.             }
  215.             
  216.             $uniqid = !empty($data->product_detail_uniqid) ? $data->product_detail_uniqid uniqid();
  217.             
  218.             $grid_data = ['uniqid'      => $uniqid,
  219.                           'id'          => $data->product_detail_id,
  220.                           'product_id'  => $data->product_detail_product_id,
  221.                           'amount'      => $data->product_detail_amount,
  222.                           'sale_price'  => $data->product_detail_price,
  223.                           'discount'    => $data->product_detail_discount];
  224.             
  225.             // insert row dynamically
  226.             $row $this->product_list->addItem( (object) $grid_data );
  227.             $row->id $uniqid;
  228.             
  229.             TDataGrid::replaceRowById('products_list'$uniqid$row);
  230.             
  231.             // clear product form fields after add
  232.             $data->product_detail_uniqid     '';
  233.             $data->product_detail_id         '';
  234.             $data->product_detail_product_id '';
  235.             $data->product_detail_name       '';
  236.             $data->product_detail_amount     '';
  237.             $data->product_detail_price      '';
  238.             $data->product_detail_discount   '';
  239.             
  240.             // send data, do not fire change/exit events
  241.             TForm::sendData'form_Sale'$datafalsefalse );
  242.         }
  243.         catch (Exception $e)
  244.         {
  245.             $this->form->setData$this->form->getData());
  246.             new TMessage('error'$e->getMessage());
  247.         }
  248.     }
  249.     
  250.     /**
  251.      * Edit a product from item list
  252.      * @param $param URL parameters
  253.      */
  254.     public static function onEditItemProduto$param )
  255.     {
  256.         $data = new stdClass;
  257.         $data->product_detail_uniqid     $param['uniqid'];
  258.         $data->product_detail_id         $param['id'];
  259.         $data->product_detail_product_id $param['product_id'];
  260.         $data->product_detail_amount     $param['amount'];
  261.         $data->product_detail_price      $param['sale_price'];
  262.         $data->product_detail_discount   $param['discount'];
  263.         
  264.         // send data, do not fire change/exit events
  265.         TForm::sendData'form_Sale'$datafalsefalse );
  266.     }
  267.     
  268.     /**
  269.      * Delete a product from item list
  270.      * @param $param URL parameters
  271.      */
  272.     public static function onDeleteItem$param )
  273.     {
  274.         $data = new stdClass;
  275.         $data->product_detail_uniqid     '';
  276.         $data->product_detail_id         '';
  277.         $data->product_detail_product_id '';
  278.         $data->product_detail_amount     '';
  279.         $data->product_detail_price      '';
  280.         $data->product_detail_discount   '';
  281.         
  282.         // send data, do not fire change/exit events
  283.         TForm::sendData'form_Sale'$datafalsefalse );
  284.         
  285.         // remove row
  286.         TDataGrid::removeRowById('products_list'$param['uniqid']);
  287.     }
  288.     
  289.     /**
  290.      * Edit Sale
  291.      */
  292.     public function onEdit($param)
  293.     {
  294.         try
  295.         {
  296.             TTransaction::open('samples');
  297.             
  298.             if (isset($param['key']))
  299.             {
  300.                 $key $param['key'];
  301.                 
  302.                 $object = new Sale($key);
  303.                 $sale_items SaleItem::where('sale_id''='$object->id)->load();
  304.                 
  305.                 foreach( $sale_items as $item )
  306.                 {
  307.                     $item->uniqid uniqid();
  308.                     $row $this->product_list->addItem$item );
  309.                     $row->id $item->uniqid;
  310.                 }
  311.                 $this->form->setData($object);
  312.                 TTransaction::close();
  313.             }
  314.             else
  315.             {
  316.                 $this->form->clear();
  317.             }
  318.         }
  319.         catch (Exception $e)
  320.         {
  321.             new TMessage('error'$e->getMessage());
  322.             TTransaction::rollback();
  323.         }
  324.     }
  325.     
  326.     /**
  327.      * Save the sale and the sale items
  328.      */
  329.     public function onSave($param)
  330.     {
  331.         $data $this->datagrid->getItems();
  332.         var_dump($data);
  333.         if($data)
  334.         {
  335.             foreach ($data as $registro)
  336.             {
  337.                 $teste 'teste: ' $registro->id;
  338.                 echo $teste;
  339.                 
  340.             }
  341.         }
  342.     }
  343.     
  344.     /**
  345.      * Closes window
  346.      */
  347.     public static function onClose()
  348.     {
  349.         parent::closeWindow();
  350.     }
  351. }
  352. ?>


obrigado

Curso completo Meu Negócio Pronto
Use para si, ou transforme em um negócio: Inclui aulas e códigos-fontes
Gestor de conteúdo (SITE) + Loja Virtual (E-Commerce) + Emissor de Notas para infoprodutos


Meu negócio pronto Quero me inscrever agora!

Comentários (3)


NR

A solução está nesse mesmo exemplo que você passou. Veja a função onSave original do tutor:
  1. <?php
  2. if( !empty($param['products_list_product_id'] ))
  3. {
  4.      foreach( $param['products_list_product_id'] as $key => $item_id )
  5.      {
  6.            $item = new SaleItem;
  7.            $item->product_id  $item_id;
  8.            $item->sale_price  = (float) $param['products_list_sale_price'][$key];
  9.            $item->amount      = (float) $param['products_list_amount'][$key];
  10.            $item->discount    = (float) $param['products_list_discount'][$key];
  11.            ....
  12. ?>

Ou seja, você vai pegar os dados da grid via $param(post), pois a grid está sendo alimentada estaticamente e assim na onSave ela vai estar vazia.
NR

Não recebi o email de confirmação anterior...
WS

Oi Nataniel Rabaioli,

só agora vou conseguir dar andamento no código.
Vou testar e posto oresultado.

muito obrigado pela ajuda!