Lançado Adianti Framework 7.6!
Clique aqui para saber mais
Chamar um formulário através da condicional IF dentro da Função Estou iniciando no Framework e estou me deparando com um problema que creio ser simples, mais não consegui resolver. Tenho uma classe ClienteList nesta classe tenho toda a listagem de clientes. Estou querendo implementar o Botão de Editar com condicional IF Ex. Se o cliente for PF Pessoa Física Abre o ClienteFormPF e se for Pessoa Juridica abre o ClienteFormPJ. Consegui chegar até ...
DJ
Chamar um formulário através da condicional IF dentro da Função  
Estou iniciando no Framework e estou me deparando com um problema que creio ser simples, mais não consegui resolver.

Tenho uma classe ClienteList nesta classe tenho toda a listagem de clientes.

Estou querendo implementar o Botão de Editar com condicional IF

Ex. Se o cliente for PF Pessoa Física Abre o ClienteFormPF e se for Pessoa Juridica abre o ClienteFormPJ.

Consegui chegar até a estrutura do IF....

Estou usando o TAction.. mais não estou conseguindo o resultado esperado.

Qual o comando utilizado para chamar o FORM desejado?

Segue o função:
/**
* Ação antes da Edição
*/
public function editarCliente($param)
{
try
{
TTransaction::open('permission');

if (isset($param['key']))
{
$key = $param['key'];
$cliente = new Clientes($key);

if ($cliente->tipocliente_id == '2')
{
$action_edit = new TAction(array('ClientesFormPF', 'onEdit'));
}
else
{
$action_edit = new TAction(array('ClientesFormPJ', 'onEdit'));
}
}
}
catch (exception $e)
{
new TMessage('error', $e->getMessage());
}
}

Se alguem puder me dar uma ajuda.

Agradeço Muito..

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


NR

Use a função loadPage:
  1. <?php
  2. TApplication::loadPage($classe,$metodo,$parametros);
  3. ?>
DJ

Funcionou.. obrigado
PS

Dovanir Junior, por gentileza posta o código que você usou pra ficar tudo ok.
PS

Nataniel Rabaioli, na função acima onde coloco esse código?

<? php
TApplication :: loadPage ( $ classe , $ metodo , $ parametros );
?>
NR

Pode ser dentro do if e do else
PS

Nataniel Rabaioli veja se consegue me ajudar.
Tenho dois forms: ClientesFormPF e ClientesFormPJ
Gostaria de clicar no botão Editar dentro do Grid e conforme o tipo de pesso física ou jurídica chamar o form correspondente, segue meu código abaixo:

  1. <?php
  2. /**
  3.  * ClientesLista Listing
  4.  * @author  <your name here>
  5.  */
  6. class ClientesLista extends TPage
  7. {
  8.     private $form// form
  9.     private $datagrid// listing
  10.     private $pageNavigation;
  11.     private $formgrid;
  12.     private $loaded;
  13.     private $deleteButton;
  14.     
  15.     /**
  16.      * Class constructor
  17.      * Creates the page, the form and the listing
  18.      */
  19.     public function __construct()
  20.     {
  21.         parent::__construct();
  22.         
  23.         // creates the form
  24.         $this->form = new BootstrapFormBuilder('form_search_Clientes');
  25.         $this->form->setFormTitle('Clientes');        
  26.         // create the form fields
  27.         $id = new TEntry('id');
  28.         $nome = new TEntry('nome');
  29.         $pessoa_tp_id = new TDBCombo('pessoa_tp_id''gestoros''PessoaTp''id''nome');
  30.         $cpfcnpj = new TEntry('cpfcnpj');
  31.         $criteria = new TCriteria;
  32.         $criteria->add(new TFilter('ativo_id''=''1'));
  33.         $cidades_id = new TDBCombo('cidades_id''gestoros''Cidades''id''nome''nome'$criteria);                
  34.         $ativo_id = new TDBCombo('ativo_id''gestoros''Ativo''id''nome');
  35.         
  36.         $nome->style "text-transform: uppercase";
  37.         
  38.         // add the fields
  39.         $this->form->addFields( [ new TLabel('Id') ], [ $id ] );
  40.         $this->form->addFields( [ new TLabel('Nome') ], [ $nome ] );
  41.         $this->form->addFields( [ new TLabel('Pessoa') ], [ $pessoa_tp_id ] );
  42.         $this->form->addFields( [ new TLabel('CPF/CNPJ') ], [ $cpfcnpj ] );
  43.         $this->form->addFields( [ new TLabel('Cidade') ], [ $cidades_id ] );
  44.         $this->form->addFields( [ new TLabel('Ativo') ], [ $ativo_id ] );
  45.         // set sizes
  46.         $id->setSize('100%');
  47.         $nome->setSize('100%');
  48.         $pessoa_tp_id->setSize('100%');
  49.         $cpfcnpj->setSize('100%');
  50.         $cidades_id->setSize('100%');
  51.         $ativo_id->setSize('100%');
  52.         
  53.         // keep the form filled during navigation with session data
  54.         $this->form->setDataTSession::getValue(__CLASS__ '_filter_data') );
  55.         
  56.         // add the search form actions
  57.         $btn $this->form->addAction(_t('Find'), new TAction([$this'onSearch']), 'fa:search');
  58.         $btn->class 'btn btn-sm btn-primary';
  59.         $this->form->addActionLink(_t('New'), new TAction(['ClientesForm''onEdit']), 'fa:plus green');
  60.         
  61.         // creates a Datagrid
  62.         $this->datagrid = new BootstrapDatagridWrapper(new TDataGrid);
  63.         $this->datagrid->style 'width: 100%';
  64.         $this->datagrid->datatable 'true';
  65.         // $this->datagrid->enablePopover('Popover', 'Hi <b> {name} </b>');        
  66.         $this->datagrid->enablePopover('Clique para alterar''Cliente: <b> {id} </b>');
  67.         // creates the datagrid columns
  68.         $column_id = new TDataGridColumn('id''Id''right'30);
  69.         $column_nome = new TDataGridColumn('nome''Nome''left');
  70.         $column_pessoa_tp_id = new TDataGridColumn('pessoa_tp->nome''Pessoa''left');
  71.         $column_cpfcnpj = new TDataGridColumn('cpfcnpj''CPF/CNPJ''left');
  72.         $column_cidades_id = new TDataGridColumn('cidades->nome''Cidade''right');
  73.         $column_ativo_id = new TDataGridColumn('ativo_id''Ativo''right');
  74.         // add the columns to the DataGrid
  75.         $this->datagrid->addColumn($column_id);
  76.         $this->datagrid->addColumn($column_nome);
  77.         $this->datagrid->addColumn($column_pessoa_tp_id);
  78.         $this->datagrid->addColumn($column_cpfcnpj);
  79.         $this->datagrid->addColumn($column_cidades_id);
  80.         $this->datagrid->addColumn($column_ativo_id);
  81.         $column_ativo_id->setTransformer( function($value$object$row) {
  82.             $class = ($value=='2') ? 'danger' 'success';
  83.             $label = ($value=='2') ? _t('No') : _t('Yes');
  84.             $div = new TElement('span');
  85.             $div->class="label label-{$class}";
  86.             $div->style="text-shadow:none; font-size:12px; font-weight:lighter";
  87.             $div->add($label);
  88.             return $div;
  89.         });
  90.         // creates the datagrid column actions
  91.         $column_id->setAction(new TAction([$this'onReload']), ['order' => 'id']);
  92.         $column_nome->setAction(new TAction([$this'onReload']), ['order' => 'nome']);
  93.                 
  94.         $action1 = new TDataGridAction(['ClientesForm''onEdit'], ['id'=>'{id}']);
  95.         $action2 = new TDataGridAction([$this'onDelete'], ['id'=>'{id}']);
  96.         
  97.         $this->datagrid->addAction($action1_t('Edit'),   'far:edit blue');
  98.         $this->datagrid->addAction($action2 ,_t('Delete'), 'far:trash-alt red');
  99.         
  100.         // create the datagrid model
  101.         $this->datagrid->createModel();
  102.         
  103.         // creates the page navigation
  104.         $this->pageNavigation = new TPageNavigation;
  105.         $this->pageNavigation->setAction(new TAction([$this'onReload']));
  106.         $this->pageNavigation->setWidth($this->datagrid->getWidth());
  107.         
  108.         // vertical box container
  109.         $container = new TVBox;
  110.         $container->style 'width: 100%';
  111.         // $container->add(new TXMLBreadCrumb('menu.xml', __CLASS__));
  112.         $container->add($this->form);
  113.         $container->add(TPanelGroup::pack(''$this->datagrid$this->pageNavigation));
  114.         
  115.         parent::add($container);
  116.     }
  117.     
  118.     /**
  119.      * Inline record editing
  120.      * @param $param Array containing:
  121.      *              key: object ID value
  122.      *              field name: object attribute to be updated
  123.      *              value: new attribute content 
  124.      */
  125.     public function onInlineEdit($param)
  126.     {
  127.         try
  128.         {
  129.             // get the parameter $key
  130.             $field $param['field'];
  131.             $key   $param['key'];
  132.             $value $param['value'];
  133.             
  134.             TTransaction::open('gestoros'); // open a transaction with database
  135.             $object = new Clientes($key); // instantiates the Active Record
  136.             $object->{$field} = $value;
  137.             $object->store(); // update the object in the database
  138.             TTransaction::close(); // close the transaction
  139.             
  140.             $this->onReload($param); // reload the listing
  141.             new TMessage('info'"Record Updated");
  142.         }
  143.         catch (Exception $e// in case of exception
  144.         {
  145.             new TMessage('error'$e->getMessage()); // shows the exception error message
  146.             TTransaction::rollback(); // undo all pending operations
  147.         }
  148.     }
  149.     
  150.     /**
  151.      * Register the filter in the session
  152.      */
  153.     public function onSearch()
  154.     {
  155.         // get the search form data
  156.         $data $this->form->getData();
  157.         
  158.         // clear session filters
  159.         TSession::setValue(__CLASS__.'_filter_id',   NULL);
  160.         TSession::setValue(__CLASS__.'_filter_nome',   NULL);
  161.         TSession::setValue(__CLASS__.'_filter_pessoa_tp_id',   NULL);
  162.         TSession::setValue(__CLASS__.'_filter_cpfcnpj',   NULL);
  163.         TSession::setValue(__CLASS__.'_filter_cidades_id',   NULL);
  164.         TSession::setValue(__CLASS__.'_filter_ativo_id',   NULL);
  165.         if (isset($data->id) AND ($data->id)) {
  166.             $filter = new TFilter('id''='$data->id); // create the filter
  167.             TSession::setValue(__CLASS__.'_filter_id',   $filter); // stores the filter in the session
  168.         }
  169.         if (isset($data->nome) AND ($data->nome)) {
  170.             $filter = new TFilter('nome''like'"%{$data->nome}%"); // create the filter
  171.             TSession::setValue(__CLASS__.'_filter_nome',   $filter); // stores the filter in the session
  172.         }
  173.         if (isset($data->pessoa_tp_id) AND ($data->pessoa_tp_id)) {
  174.             $filter = new TFilter('pessoa_tp_id''='$data->pessoa_tp_id); // create the filter
  175.             TSession::setValue(__CLASS__.'_filter_pessoa_tp_id',   $filter); // stores the filter in the session
  176.         }
  177.         if (isset($data->cpfcnpj) AND ($data->cpfcnpj)) {
  178.             $filter = new TFilter('cpfcnpj''like'"%{$data->cpfcnpj}%"); // create the filter
  179.             TSession::setValue(__CLASS__.'_filter_cpfcnpj',   $filter); // stores the filter in the session
  180.         }
  181.         if (isset($data->cidades_id) AND ($data->cidades_id)) {
  182.             $filter = new TFilter('cidades_id''='$data->cidades_id); // create the filter
  183.             TSession::setValue(__CLASS__.'_filter_cidades_id',   $filter); // stores the filter in the session
  184.         }
  185.         if (isset($data->ativo_id) AND ($data->ativo_id)) {
  186.             $filter = new TFilter('ativo_id''='$data->ativo_id); // create the filter
  187.             TSession::setValue(__CLASS__.'_filter_ativo_id',   $filter); // stores the filter in the session
  188.         }
  189.         
  190.         // fill the form with data again
  191.         $this->form->setData($data);
  192.         
  193.         // keep the search data in the session
  194.         TSession::setValue(__CLASS__ '_filter_data'$data);
  195.         
  196.         $param = array();
  197.         $param['offset']    =0;
  198.         $param['first_page']=1;
  199.         $this->onReload($param);
  200.     }
  201.     
  202.     /**
  203.      * Load the datagrid with data
  204.      */
  205.     public function onReload($param NULL)
  206.     {
  207.         try
  208.         {
  209.             // open a transaction with database 'gestoros'
  210.             TTransaction::open('gestoros');
  211.             
  212.             // creates a repository for Clientes
  213.             $repository = new TRepository('Clientes');
  214.             $limit 10;
  215.             // creates a criteria
  216.             $criteria = new TCriteria;
  217.             
  218.             // default order
  219.             if (empty($param['order']))
  220.             {
  221.                 $param['order'] = 'id';
  222.                 $param['direction'] = 'asc';
  223.             }
  224.             $criteria->setProperties($param); // order, offset
  225.             $criteria->setProperty('limit'$limit);
  226.             //Desabilita o click do datagrid
  227.             $this->datagrid->disableDefaultClick();                        
  228.             if (TSession::getValue(__CLASS__.'_filter_id')) {
  229.                 $criteria->add(TSession::getValue(__CLASS__.'_filter_id')); // add the session filter
  230.             }
  231.             if (TSession::getValue(__CLASS__.'_filter_nome')) {
  232.                 $criteria->add(TSession::getValue(__CLASS__.'_filter_nome')); // add the session filter
  233.             }
  234.             if (TSession::getValue(__CLASS__.'_filter_pessoa_tp_id')) {
  235.                 $criteria->add(TSession::getValue(__CLASS__.'_filter_pessoa_tp_id')); // add the session filter
  236.             }
  237.             if (TSession::getValue(__CLASS__.'_filter_cpfcnpj')) {
  238.                 $criteria->add(TSession::getValue(__CLASS__.'_filter_cpfcnpj')); // add the session filter
  239.             }
  240.             if (TSession::getValue(__CLASS__.'_filter_cidades_id')) {
  241.                 $criteria->add(TSession::getValue(__CLASS__.'_filter_cidades_id')); // add the session filter
  242.             }
  243.             if (TSession::getValue(__CLASS__.'_filter_ativo_id')) {
  244.                 $criteria->add(TSession::getValue(__CLASS__.'_filter_ativo_id')); // add the session filter
  245.             }
  246.             
  247.             // load the objects according to criteria
  248.             $objects $repository->load($criteriaFALSE);
  249.             
  250.             if (is_callable($this->transformCallback))
  251.             {
  252.                 call_user_func($this->transformCallback$objects$param);
  253.             }
  254.             
  255.             $this->datagrid->clear();
  256.             if ($objects)
  257.             {
  258.                 // iterate the collection of active records
  259.                 foreach ($objects as $object)
  260.                 {
  261.                     // add the object inside the datagrid
  262.                     $this->datagrid->addItem($object);
  263.                 }
  264.             }
  265.             
  266.             // reset the criteria for record count
  267.             $criteria->resetProperties();
  268.             $count$repository->count($criteria);
  269.             
  270.             $this->pageNavigation->setCount($count); // count of records
  271.             $this->pageNavigation->setProperties($param); // order, page
  272.             $this->pageNavigation->setLimit($limit); // limit
  273.             
  274.             // close the transaction
  275.             TTransaction::close();
  276.             $this->loaded true;
  277.         }
  278.         catch (Exception $e)
  279.         {
  280.             new TMessage('error'$e->getMessage());
  281.             TTransaction::rollback();
  282.         }
  283.     }
  284.     
  285.     /**
  286.      * Ask before deletion
  287.      */
  288.     public static function onDelete($param)
  289.     {
  290.         // define the delete action
  291.         $action = new TAction([__CLASS__'Delete']);
  292.         $action->setParameters($param); // pass the key parameter ahead
  293.         
  294.         // shows a dialog to the user
  295.         new TQuestion(AdiantiCoreTranslator::translate('Do you really want to delete ?'), $action);
  296.     }
  297.     
  298.     /**
  299.      * Delete a record
  300.      */
  301.     public static function Delete($param)
  302.     {
  303.         try
  304.         {
  305.             $key=$param['key']; // get the parameter $key
  306.             TTransaction::open('gestoros'); // open a transaction with database
  307.             $object = new Clientes($keyFALSE); // instantiates the Active Record
  308.             $object->delete(); // deletes the object from the database
  309.             TTransaction::close(); // close the transaction
  310.             
  311.             $pos_action = new TAction([__CLASS__'onReload']);
  312.             new TMessage('info'AdiantiCoreTranslator::translate('Record deleted'), $pos_action); // success message
  313.         }
  314.         catch (Exception $e// in case of exception
  315.         {
  316.             new TMessage('error'$e->getMessage()); // shows the exception error message
  317.             TTransaction::rollback(); // undo all pending operations
  318.         }
  319.     }
  320.     
  321.     /**
  322.      * method show()
  323.      * Shows the page
  324.      */
  325.     public function show()
  326.     {
  327.         // check if the datagrid is already loaded
  328.         if (!$this->loaded AND (!isset($_GET['method']) OR !(in_array($_GET['method'],  array('onReload''onSearch')))) )
  329.         {
  330.             if (func_num_args() > 0)
  331.             {
  332.                 $this->onReloadfunc_get_arg(0) );
  333.             }
  334.             else
  335.             {
  336.                 $this->onReload();
  337.             }
  338.         }
  339.         parent::show();
  340.     }
  341. }
  342. ?>

</your>
PS

Como faço a chamada dessa função no clique da minha grid ?

  1. <?php
  2. /**
  3. * Ação antes da Edição
  4. */
  5. public function editarCliente($param)
  6. {
  7. try
  8. {
  9. TTransaction::open('permission');
  10. if (isset($param['key']))
  11. {
  12. $key $param['key'];
  13. $cliente = new Clientes($key);
  14. if ($cliente->tipocliente_id == '2')
  15. {
  16. $action_edit = new TAction(array('ClientesFormPF''onEdit'));
  17. }
  18. else
  19. {
  20. $action_edit = new TAction(array('ClientesFormPJ''onEdit'));
  21. }
  22. }
  23. }
  24. catch (exception $e)
  25. {
  26. new TMessage('error'$e->getMessage());
  27. }
  28. }
  29. ?>

PS

Vajam minha chamada do clique do botão no grid e minha função, o que estou fazendo de errado?

  1. <?php
  2.     $action_servico = new TDataGridAction(array($this'editarCliente'));
  3.         $action_servico->setLabel('Gerar contas');
  4.         $action_servico->setImage('fa:donate blue fa-lg');
  5.         $action_servico->setField('id');
  6.         $this->datagrid->addAction($action_servico);
  7. ?>


  1. <?php
  2.     public function editarCliente($param)
  3.     {
  4.         try
  5.         {
  6.             TTransaction::open('gestoros');
  7.             if (isset($param['key']))
  8.             {
  9.                 $key $param['key'];
  10.                 $cliente = new Clientes($key);
  11.                 if ($cliente->pessoa_tp_id == '2')
  12.                 {
  13.                     //$action_edit = new TAction(array('ClientesForm', 'onEdit'));
  14.                     $action_edit = new TDataGridAction(['ClientesFormPJ''onEdit'], ['id'=>'{id}']);
  15.                 }
  16.                 else
  17.                 {
  18.                     //$action_edit = new TAction(array('ClientesFormPJ', 'onEdit'));
  19.                     $action_edit = new TDataGridAction(['ClientesForm''onEdit'], ['id'=>'{id}']);
  20.                 }
  21.             }
  22.             TTransaction::close(); // close the transaction
  23.         }
  24.             catch (exception $e)
  25.             {
  26.             new TMessage('error'$e->getMessage());
  27.             }
  28.     }
  29. ?>