Como condicionar um botão à seleção de um combo box Boa tarde, estou precisando da seguinte ajuda: Preciso condicionar um botão à seleção do combo box, exemplo: ao selecionar uma das opções existentes no combo box o botão aparecerá, caso contrário ficará escondido. Preciso pegar o id da opção e criar uma estrutura de decisão para esconder o botão....
MS
Como condicionar um botão à seleção de um combo box  
Boa tarde, estou precisando da seguinte ajuda:

Preciso condicionar um botão à seleção do combo box, exemplo:
ao selecionar uma das opções existentes no combo box o botão aparecerá, caso contrário ficará escondido.
Preciso pegar o id da opção e criar uma estrutura de decisão para esconder o botão.

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


NR

Que classe de formulário você está utilizando?

Se deixar o botão desabilitado resolve, veja o exemplo abaixo:
adianti.com.br/framework_files/tutor/index.php?class=FormConditional
MS

Estou usando o TForm e dentro uma TTable, o combo ta como TDBCombo e o botão padrão com TButton
NR

A função TQuickForm::hideField($nome_form,$nome_widget) esconde o container pai que contenha a classe tformrow. Você pode fazer o seguinte:
 
  1. <?php
  2. $combo = new TCombo('combo');
  3. $combo->setChangeAction(new TAction(array($this,'changeCombo'))); // acao ao alterar valor da combo
  4. $button = TButton::create('save',[$this,'onSave'],'Salvar','fa:save');
  5. $row = $table->addRow();
  6. $row->class = 'tformrow'; // importante, pois a hideField vai procurar por essa classe para ocultar
  7. $row->addCell($button);
  8. // function changeCombo
  9. if (condicao)
  10. TQuickForm::hideField('nome_form','nome_botao');
  11. else
  12. TQuickForm::showField('nome_form','nome_botao');
  13. ?>
MS

Não está executando, da uma janela de erro no aplicação

 
  1. <?php
  2. $id_sala = new TDBCombo('id_sala', 'permission', 'Sala', 'id_sala', 'sg_sala');
  3. $id_sala->setChangeAction(new TAction(array($this,'changeCombo'))); // acao ao alterar valor da combo
  4. // create an print button (imprimir autorizacao de saida de automovel)
  5. $print_button=new TButton('print');
  6. $print_button->setAction(new TAction(array($this, 'onPrint')), 'Imprimir Autorização','fa:print');
  7. $row = $table->addRow();
  8. $row->class = 'print'; // importante, pois a hideField vai procurar por essa classe para ocultar
  9. $row->addCell($print_button);
  10. /*function changeCombo{
  11. if ($id_sala > 4){
  12. TQuickForm::hideField('$id_sala','$print_button');
  13. }
  14. else{
  15. TQuickForm::showField('$id_sala','$print_button');
  16. }
  17. }*/
  18. ?>
MS

A função não está marcada como acima, apenas mandei uma cópia errada

Segue código inteiro:
 
  1. <?php
  2. /**
  3. * CalendarEventForm
  4. */
  5. class CalendarEventForm extends TWindow
  6. {
  7. protected $form; // form
  8. /**
  9. * Class constructor
  10. * Creates the page and the registration form
  11. */
  12. public function __construct()
  13. {
  14. parent::__construct();
  15. parent::setSize(640, null);
  16. parent::setTitle('Calendário [Evento]');
  17. // creates the form
  18. $this->form = new TForm('form_event');
  19. $this->form->class = 'tform'; // CSS class
  20. $this->form->style = 'width: 600px';
  21. // add a table inside form
  22. $table = new TTable;
  23. $table-> width = '100%';
  24. $this->form->add($table);
  25. // add a row for the form title
  26. $row = $table->addRow();
  27. $row->class = 'tformtitle'; // CSS class
  28. $row->addCell( new TLabel('Evento') )->colspan = 2;
  29. $hours = array();
  30. $minutes = array();
  31. for ($n=0; $n<24; $n++)
  32. {
  33. $hours[$n] = str_pad($n, 2, '0', STR_PAD_LEFT);
  34. }
  35. for ($n=0; $n<=55; $n+=5)
  36. {
  37. $minutes[$n] = str_pad($n, 2, '0', STR_PAD_LEFT);
  38. }
  39. // create the form fields
  40. $view = new THidden('view');
  41. $id = new TEntry('id');
  42. $id_sala = new TDBCombo('id_sala', 'permission', 'Sala', 'id_sala', 'sg_sala');
  43. $id_sala->setChangeAction(new TAction(array($this,'changeCombo'))); // acao ao alterar valor da combo
  44. $color = new TColor('color');
  45. $start_date = new TDate('start_date');
  46. $start_hour = new TCombo('start_hour');
  47. $start_minute = new TCombo('start_minute');
  48. $end_date = new TDate('end_date');
  49. $end_hour = new TCombo('end_hour');
  50. $end_minute = new TCombo('end_minute');
  51. $title = new TEntry('title');
  52. $description = new TText('description');
  53. $participantes = new TDBMultiSearch('participantes', 'permission', 'SystemUser', 'id', 'name');
  54. $login = new TEntry('login');
  55. $color->setValue('#3a87ad');
  56. $start_hour->addItems($hours);
  57. $start_minute->addItems($minutes);
  58. $end_hour->addItems($hours);
  59. $end_minute->addItems($minutes);
  60. $id_sala->setDefaultOption(FALSE);
  61. $participantes->setMinLength(3);
  62. $login->setValue(TSession::getValue('login'));
  63. $login->setEditable(FALSE);
  64. $id->setEditable(FALSE);
  65. // define the sizes
  66. $id->setSize(60);
  67. $id_sala->setSize(100);
  68. $color->setSize(100);
  69. $start_date->setSize(100);
  70. $end_date->setSize(100);
  71. $start_hour->setSize(50);
  72. $end_hour->setSize(50);
  73. $start_minute->setSize(50);
  74. $end_minute->setSize(50);
  75. $title->setSize(400);
  76. $description->setSize(400, 50);
  77. $participantes->setSize(400, 50);
  78. $start_hour->setChangeAction(new TAction(array($this, 'onChangeStartHour')));
  79. $end_hour->setChangeAction(new TAction(array($this, 'onChangeEndHour')));
  80. $start_date->setExitAction(new TAction(array($this, 'onChangeStartDate')));
  81. $end_date->setExitAction(new TAction(array($this, 'onChangeEndDate')));
  82. // add one row for each form field
  83. $table->addRowSet( $view );
  84. $table->addRowSet( new TLabel('#:'), [$id , new TLabel('Proprietário:'), $login]);
  85. $table->addRowSet( new TLabel('Sala/Carro/Viagem:'), $id_sala );
  86. // $table->addRowSet( new TLabel('Color:'), $color );
  87. $table->addRowSet( new TLabel('Início:'), array($start_date, $start_hour, ':', $start_minute) );
  88. $table->addRowSet( new TLabel('Término:'), array($end_date, $end_hour, ':', $end_minute));
  89. $table->addRowSet( new TLabel('Título:'), $title );
  90. $table->addRowSet( new TLabel('Descrição:'), $description );
  91. $table->addRowSet( new TLabel('Participantes:'), $participantes );
  92. // create an action button (save)
  93. $save_button=new TButton('save');
  94. $save_button->setAction(new TAction(array($this, 'onSave')), _t('Save'));
  95. $save_button->setImage('fa:save green');
  96. // create an new button (edit with no parameters)
  97. $new_button=new TButton('new');
  98. $new_button->setAction(new TAction(array($this, 'onEdit')), 'Limpar');
  99. $new_button->setImage('fa:eraser blue');
  100. // create an del button (edit with no parameters)
  101. $del_button=new TButton('del');
  102. $del_button->setAction(new TAction(array($this, 'onDelete')), _t('Delete'));
  103. $del_button->setImage('fa:trash-o red');
  104. // create an print button (imprimir autorizacao de saida de automovel)
  105. $print_button=new TButton('print');
  106. $print_button->setAction(new TAction(array($this, 'onPrint')), 'Imprimir Autorização','fa:print');
  107. $row = $table->addRow();
  108. $row->class = 'print'; // importante, pois a hideField vai procurar por essa classe para ocultar
  109. $row->addCell($print_button);
  110. function changeCombo{
  111. if ($id_sala('id_sala') > 4){
  112. TQuickForm::hideField('$id_sala','$print_button');
  113. }
  114. else{
  115. TQuickForm::showField('$id_sala','$print_button');
  116. }
  117. }
  118. $this->form->setFields(array($id, $view, $login, $participantes, $color,$id_sala, $title, $description, $start_date, $start_hour, $start_minute, $end_date, $end_hour, $end_minute, $save_button,$new_button,$del_button, $print_button));
  119. $buttons_box = new THBox;
  120. $buttons_box->add($save_button);
  121. $buttons_box->add($new_button);
  122. $buttons_box->add($del_button);
  123. $buttons_box->add($print_button);
  124. // add a row for the form action
  125. $row = $table->addRow();
  126. $row->class = 'tformaction'; // CSS class
  127. $row->addCell($buttons_box)->colspan = 2;
  128. parent::add($this->form);
  129. }
  130. /**
  131. * Executed when user leaves start hour field
  132. */
  133. public static function onChangeStartHour($param=NULL)
  134. {
  135. $obj = new stdClass;
  136. if (empty($param['start_minute']))
  137. {
  138. $obj->start_minute = '0';
  139. TForm::sendData('form_event', $obj);
  140. }
  141. if (empty($param['end_hour']) AND empty($param['end_minute']))
  142. {
  143. $obj->end_hour = $param['start_hour'] +1;
  144. $obj->end_minute = '0';
  145. TForm::sendData('form_event', $obj);
  146. }
  147. }
  148. /**
  149. * Executed when user leaves end hour field
  150. */
  151. public static function onChangeEndHour($param=NULL)
  152. {
  153. if (empty($param['end_minute']))
  154. {
  155. $obj = new stdClass;
  156. $obj->end_minute = '0';
  157. TForm::sendData('form_event', $obj);
  158. }
  159. }
  160. /**
  161. * Executed when user leaves start date field
  162. */
  163. public static function onChangeStartDate($param=NULL)
  164. {
  165. if (empty($param['end_date']) AND !empty($param['start_date']))
  166. {
  167. $obj = new stdClass;
  168. $obj->end_date = $param['start_date'];
  169. TForm::sendData('form_event', $obj);
  170. }
  171. }
  172. /**
  173. * Executed when user leaves end date field
  174. */
  175. public static function onChangeEndDate($param=NULL)
  176. {
  177. if (empty($param['end_hour']) AND empty($param['end_minute']) AND !empty($param['start_hour']))
  178. {
  179. $obj = new stdClass;
  180. $obj->end_hour = min($param['start_hour'],22) +1;
  181. $obj->end_minute = '0';
  182. TForm::sendData('form_event', $obj);
  183. }
  184. }
  185. /**
  186. * method onSave()
  187. * Executed whenever the user clicks at the save button
  188. */
  189. public function onSave()
  190. {
  191. try
  192. {
  193. // open a transaction
  194. TTransaction::open('permission');
  195. $this->form->validate(); // form validation
  196. // get the form data into an active record Entry
  197. $data = $this->form->getData();
  198. if (empty($data->id))
  199. {
  200. $conn = TTransaction::get();
  201. $status = 'agendada';
  202. $id_sala = $data->id_sala;
  203. $dh_start = $data->start_date . ' ' . str_pad($data->start_hour, 2, '0', STR_PAD_LEFT) . ':' . str_pad($data->start_minute, 2, '0', STR_PAD_LEFT) . ':30';
  204. $mssql = "select id from calendar_event where id_sala = '{$id_sala}' and ( '{$dh_start}' between start_time and end_time )";
  205. // executa a instrução SQL
  206. $result = $conn->query($mssql);
  207. $resp = $result->fetchObject();
  208. }
  209. if (isset($resp) and ($resp))
  210. {
  211. new TMessage('info', 'Não foi possível gravar, já tem reunião nesse horário');
  212. }
  213. else
  214. {
  215. $object = new CalendarEvent;
  216. $status = ($status <> '')? $status : 'alterada';
  217. // $object->color = $data->color;
  218. $object->id = $data->id;
  219. $object->title = $data->title;
  220. $object->description = $data->description;
  221. $object->start_time = $data->start_date . ' ' . str_pad($data->start_hour, 2, '0', STR_PAD_LEFT) . ':' . str_pad($data->start_minute, 2, '0', STR_PAD_LEFT) . ':00';
  222. $object->end_time = $data->end_date . ' ' . str_pad($data->end_hour , 2, '0', STR_PAD_LEFT) . ':' . str_pad($data->end_minute , 2, '0', STR_PAD_LEFT) . ':00';
  223. $object->login = (empty($data->login)) ? TSession::getValue('login') : $data->login ;
  224. $object->id_sala = $data->id_sala;
  225. $key_participantes = array_keys($data->participantes);
  226. // gravar os participantes em um único campo
  227. //------------------------------------------------------------------
  228. $membros = '';
  229. if ($key_participantes)
  230. {
  231. $membros = implode(';', $key_participantes);
  232. }
  233. $object->participantes = $membros;
  234. $object->store(); // stores the object
  235. $data->id = $object->id;
  236. $this->form->setData($data); // keep form data
  237. $posAction = new TAction(array('FullCalendarDatabaseView', 'onReload'));
  238. $posAction->setParameter('view', $data->view);
  239. $posAction->setParameter('date', $data->start_date);
  240. // shows the success message
  241. // new TMessage('info', TAdiantiCoreTranslator::translate('Record saved'), $posAction);
  242. $param['view'] = $data->view;
  243. $param['date'] = $data->start_date;
  244. AdiantiCoreApplication::loadPage('FullCalendarDatabaseView', 'onReload', $param);
  245. $param = [];
  246. $pessoas = [];
  247. foreach($key_participantes as $id)
  248. {
  249. $user = SystemUser::find($id);
  250. if ($user)
  251. {
  252. $pessoas[] = [$user->email,$user->name];
  253. }
  254. }
  255. $sala = new Sala($data->id_sala);
  256. $param['dt_ini'] = $object->start_time;
  257. $param['dt_fim'] = $object->end_time;
  258. $param['titulo'] = $data->title;
  259. $param['descricao']= $data->description;
  260. $param['pessoas'] = $pessoas;
  261. $param['status'] = $status;
  262. $param['sala'] = $sala->sg_sala;
  263. TTransaction::close(); // close the transaction
  264. $action = new TAction(['FullCalendarDatabaseView', 'EnviarEmail']);
  265. $action->setParameters($param);
  266. new TQuestion('Registro Salvo!!!, deseja enviar email?', $action);
  267. }
  268. TTransaction::close(); // close the transaction
  269. }
  270. catch (Exception $e) // in case of exception
  271. {
  272. // shows the exception error message
  273. new TMessage('error', $e->getMessage());
  274. $this->form->setData( $this->form->getData() ); // keep form data
  275. // undo all pending operations
  276. TTransaction::rollback();
  277. }
  278. }
  279. /**
  280. * method onEdit()
  281. * Executed whenever the user clicks at the edit button da datagrid
  282. */
  283. public function onEdit($param)
  284. {
  285. try
  286. {
  287. $data = new stdClass;
  288. if (isset($param['key']))
  289. {
  290. // get the parameter $key
  291. $key=$param['key'];
  292. // open a transaction with database
  293. TTransaction::open('permission');
  294. // instantiates object CalendarEvent
  295. $object = new CalendarEvent($key);
  296. // $data = new stdClass;
  297. $data->id = $object->id;
  298. $data->color = $object->color;
  299. $data->id_sala = $object->id_sala;
  300. $data->title = $object->title;
  301. $data->description = $object->description;
  302. $data->start_date = substr($object->start_time,0,10);
  303. $data->start_hour = substr($object->start_time,11,2);
  304. $data->start_minute = substr($object->start_time,14,2);
  305. $data->end_date = substr($object->end_time,0,10);
  306. $data->end_hour = substr($object->end_time,11,2);
  307. $data->end_minute = substr($object->end_time,14,2);
  308. $data->view = $param['view'];
  309. $data->login = $object->login;
  310. //Carregar os participantes
  311. $vetor = explode(';',$object->participantes);
  312. $participantes = [];
  313. foreach($vetor as $id)
  314. {
  315. $user = SystemUser::find($id);
  316. if ($user)
  317. {
  318. $participantes[$user->id] = $user->name;
  319. }
  320. }
  321. $data->participantes = $participantes;
  322. // fill the form with the active record data
  323. $this->form->setData($data);
  324. if ($object->login <> TSession::getValue('login'))
  325. {
  326. TButton::disableField('form_event', 'save');
  327. TButton::disableField('form_event', 'new');
  328. TButton::disableField('form_event', 'del');
  329. }
  330. // close the transaction
  331. TTransaction::close();
  332. }
  333. else
  334. {
  335. $this->form->clear();
  336. $data->login = TSession::getValue('login');
  337. $this->form->setData($data);
  338. }
  339. }
  340. catch (Exception $e) // in case of exception
  341. {
  342. // shows the exception error message
  343. new TMessage('error', $e->getMessage());
  344. // undo all pending operations
  345. TTransaction::rollback();
  346. }
  347. }
  348. /**
  349. * Delete event
  350. */
  351. public static function onDelete($param)
  352. {
  353. // define the delete action
  354. $action = new TAction(array('CalendarEventForm', 'Delete'));
  355. $action->setParameters($param); // pass the key parameter ahead
  356. // shows a dialog to the user
  357. new TQuestion(AdiantiCoreTranslator::translate('Do you really want to delete ?'), $action);
  358. }
  359. /**
  360. * Delete a record
  361. */
  362. public static function Delete($param)
  363. {
  364. try
  365. {
  366. var_dump($param);
  367. // get the parameter $key
  368. $key = $param['id'];
  369. // open a transaction with database
  370. TTransaction::open('permission');
  371. // instantiates object
  372. $object = new CalendarEvent($key, FALSE);
  373. // deletes the object from the database
  374. $object->delete();
  375. // close the transaction
  376. TTransaction::close();
  377. $posAction = new TAction(array('FullCalendarDatabaseView', 'onReload'));
  378. $posAction->setParameter('view', $param['view']);
  379. $posAction->setParameter('date', $param['start_date']);
  380. // shows the success message
  381. new TMessage('info', AdiantiCoreTranslator::translate('Record deleted'), $posAction);
  382. }
  383. catch (Exception $e) // in case of exception
  384. {
  385. // shows the exception error message
  386. new TMessage('error', $e->getMessage());
  387. // undo all pending operations
  388. TTransaction::rollback();
  389. }
  390. }
  391. /**
  392. * Fill form from the user selected time
  393. */
  394. public function onStartEdit($param)
  395. {
  396. $this->form->clear();
  397. $data = new stdClass;
  398. $data->view = $param['view']; // calendar view
  399. $data->color = '#3a87ad';
  400. if ($param['date'])
  401. {
  402. if (strlen($param['date']) == 10)
  403. {
  404. $data->start_date = $param['date'];
  405. $data->end_date = $param['date'];
  406. }
  407. if (strlen($param['date']) == 19)
  408. {
  409. $data->start_date = substr($param['date'],0,10);
  410. $data->start_hour = substr($param['date'],11,2);
  411. $data->start_minute = substr($param['date'],14,2);
  412. $data->end_date = substr($param['date'],0,10);
  413. $data->end_hour = substr($param['date'],11,2) +1;
  414. $data->end_minute = substr($param['date'],14,2);
  415. }
  416. $this->form->setData( $data );
  417. }
  418. }
  419. /**
  420. * Update event. Result of the drag and drop or resize.
  421. */
  422. public static function onUpdateEvent($param)
  423. {
  424. try
  425. {
  426. if (isset($param['id']))
  427. {
  428. // get the parameter $key
  429. $key=$param['id'];
  430. // open a transaction with database
  431. TTransaction::open('permission');
  432. // instantiates object CalendarEvent
  433. $object = new CalendarEvent($key);
  434. $object->start_time = str_replace('T', ' ', $param['start_time']);
  435. $object->end_time = str_replace('T', ' ', $param['end_time']);
  436. $object->store();
  437. // close the transaction
  438. TTransaction::close();
  439. }
  440. }
  441. catch (Exception $e) // in case of exception
  442. {
  443. new TMessage('error', '<b>Error</b> ' . $e->getMessage());
  444. TTransaction::rollback();
  445. }
  446. }
  447. public static function onPrint($param)
  448. {
  449. TScript::create('window.open("https://drive.google.com/file/d/15XypKw8KXA58yYwZTB3qvcaWxL9Tf31X/view?usp=sharing","_blank")');
  450. }
  451. }
  452. ?>
NR

Declare a função changeCombo fora do construtor. Veja o exemplo:
adianti.com.br/framework_files/tutor/index.php?class=FormInteraction