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

</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. ?>