Executar uma ação após upload de imagem Fiz um master/detail, o detail é fazer upload de imagens, gostaria de saber, se tem como adicionar automaticamento o detail, ou seja, executar a função onAddDetail após carregar a imagem, sem precisar clicar no "Incluir Anexo"...
A
Executar uma ação após upload de imagem  
Fiz um master/detail, o detail é fazer upload de imagens, gostaria de saber, se tem como adicionar automaticamento o detail, ou seja, executar a função onAddDetail após carregar a imagem, sem precisar clicar no "Incluir Anexo"

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


NR

O TFile permite definir uma ação para ser chamada após o término do upload. Veja a função setCompleteAction. Ex:
adianti.com.br/framework_files/tutor/index.php?class=FormEventsView
A

Deu este erro
A ação (ProntuarioobrigatorioForm::onDetailAddAnexos) deve ser estática para ser usada em AdiantiWidgetFormTFile::setCompleteAction

A

coloquei a função como estatica, mas não acontece nada
NR

Tente criar outra função e chamar a onDetailAddAnexos usando a função postData:
 
  1. <?php
  2. static function onUploadComplete($param)
  3. {
  4. //public static function postData($formName, $class, $method = NULL, $parameters = NULL)
  5. TApplication::postData('nome_form','classe','onDetailAddAnexos');
  6. }
  7. ?>
A

Funcionou, porém ele recarrega a pagina, peder os outros details uploads que ja tinha, e só deixa fazer upload de uma imagem.
Agradeço desde ja pela ajuda.
NR

Ao clicar no botão "Incluir Anexo" a página não é recarregada também?

Poste toda classe, fica mais fácil.
A

 
  1. <?php
  2. /**
  3. * ProntuarioobrigatorioForm Master/Detail
  4. * @author <your name here>
  5. */
  6. class ProntuarioobrigatorioForm extends TPage
  7. {
  8. protected $form; // form
  9. protected $detail_list;
  10. use Adianti\Base\AdiantiFileSaveTrait;
  11. /**
  12. * Page constructor
  13. */
  14. public function __construct()
  15. {
  16. parent::__construct();
  17. // creates the form
  18. $this->form = new BootstrapFormBuilder('form_Prontuarioobrigatorio');
  19. $this->form->setFormTitle('Prontuario Obrigatório');
  20. // master fields
  21. //buscar paciente
  22. $COD_PAC = new ">TDBSeekButton('COD_PAC', 'banco', $this->form->getName(),'Paciente', 'NOME_PAC');
  23. $NOME_PACIENTE = new TEntry('NOME_PACIENTE');
  24. $COD_PAC->setDisplayLabel('PACIENTE');
  25. $COD_PAC->setAuxiliar($NOME_PACIENTE);
  26. //formatacao BUSCAR paciente
  27. $NOME_PACIENTE->setEditable(FALSE);
  28. $COD_PAC->setSize(80);
  29. $NOME_PACIENTE->setSize('calc(100% - 105px)');
  30. $NOME_PACIENTE->style .= ';margin-left:3px';
  31. $NOME_PAC = new THidden('NOME_PAC');
  32. $CID = new TEntry('CID');
  33. $AVAL_DEMANDA = new THtmlEditor('AVAL_DEMANDA');
  34. $OBJ_TRATAMENTO = new THtmlEditor('OBJ_TRATAMENTO');
  35. $REG_ENCAMINHAMENTO = new THtmlEditor('REG_ENCAMINHAMENTO');
  36. $REG_ENCERRAMENTO = new THtmlEditor('REG_ENCERRAMENTO');
  37. //$ANEXOS = new TFile('ANEXOS');
  38. $COD_PAC->setExitAction(new TAction(array($this, 'onExitActionPac')));
  39. // detail fields
  40. $detail_uniqid = new THidden('detail_uniqid');
  41. $detail_ID = new THidden('detail_ID');
  42. $detail_DATA_EVOLUCAO = new TDate('detail_DATA_EVOLUCAO');
  43. $detail_OBS_EVOLUCAO = new THtmlEditor('detail_OBS_EVOLUCAO');
  44. // master fields
  45. $this->form->addFields( [new TLabel('Paciente')], [$COD_PAC] );
  46. $this->form->addFields( [new TLabel('CID')], [$CID] );
  47. $this->form->addFields( [new THidden('NOME')], [$NOME_PAC] );
  48. $this->form->addFields( [new TLabel('Avaliação Demanda')], [$AVAL_DEMANDA] );
  49. $this->form->addFields( [new TLabel('Objetivo Tratamento')], [$OBJ_TRATAMENTO] );
  50. $this->form->addFields( [new TLabel('Registro Encaminhamento')], [$REG_ENCAMINHAMENTO] );
  51. $this->form->addFields( [new TLabel('Registro Encerramento')], [$REG_ENCERRAMENTO] );
  52. //$this->form->addFields( [new TLabel('Anexos')], [$ANEXOS] );
  53. $AVAL_DEMANDA->setSize('100%',100);
  54. $OBJ_TRATAMENTO->setSize('100%',100);
  55. $REG_ENCAMINHAMENTO->setSize('100%',100);
  56. $REG_ENCERRAMENTO->setSize('100%',100);
  57. $CID->setValue("10/DSM5");
  58. //formatacao upload de imagem
  59. // $ANEXOS->enableFileHandling();
  60. // $ANEXOS->enableImageGallery();
  61. // $ANEXOS->enablePopover('Preview', '<img style="max-width:300px" src="download.php?file={file_name}">');
  62. // detail fields ANEXOS
  63. $this->form->addContent( ['<h5>Anexos</h5><hr>'] );
  64. $detail_uniqueid = new THidden('detail_uniqueid');
  65. $detail_ID_anexo = new THidden('detail_ID_anexo');
  66. $detail_DT_ANEXO = new THidden('detail_DT_ANEXO');
  67. $detail_CAMINHO_ANEXO = new TFile('detail_CAMINHO_ANEXO');
  68. $detail_DT_ANEXO->setValue(date('Y-m-d'));
  69. $detail_CAMINHO_ANEXO->setAllowedExtensions( ['gif', 'png', 'jpg', 'jpeg', 'pdf','docx'] );
  70. $this->form->addFields( [$detail_uniqueid] );
  71. $this->form->addFields( [$detail_ID_anexo] );
  72. $this->form->addFields( [new THidden('Dt Anexo')], [$detail_DT_ANEXO] );
  73. //$detail_CAMINHO_ANEXO->setExitAction( new TAction( array($this, 'onDetailAddAnexos' )) );
  74. //$addAnexo = TButton::create('addAnexo', [$this, 'onDetailAddAnexos'], 'Incluir upload', 'fas:cloud-upload-alt orange fa-lg');
  75. //$addAnexo->getAction()->setParameter('static','1');
  76. //$this->form->addFields( [], [$addAnexo] );
  77. $detail_CAMINHO_ANEXO->setCompleteAction(new TAction(array($this, 'onUploadComplete')));
  78. $this->form->addFields( [new TLabel('Caminho Anexo')], [$detail_CAMINHO_ANEXO] );
  79. //$detail_CAMINHO_ANEXO->setCompleteAction( new TAction( array($this, 'onDetailAddAnexos' )) );
  80. $this->detail_list_anexo = new BootstrapDatagridWrapper(new TDataGrid);
  81. $this->detail_list_anexo->setId('Anexos_list');
  82. $this->detail_list_anexo->generateHiddenFields();
  83. $this->detail_list_anexo->style = "min-width: 500px; width:100%;margin-bottom: 10px";
  84. // items
  85. $this->detail_list_anexo->addColumn( new TDataGridColumn('uniqueid', 'uniqid', 'center') )->setVisibility(false);
  86. $this->detail_list_anexo->addColumn( new TDataGridColumn('ID_anexo', 'Id', 'center') )->setVisibility(false);
  87. $this->detail_list_anexo->addColumn( new TDataGridColumn('DT_ANEXO', 'Data', 'left', 50) )->setVisibility(false);
  88. $img=$this->detail_list_anexo->addColumn( new TDataGridColumn('CAMINHO_ANEXO', 'Anexo', 'left', 100) );
  89. //$img->setTransformer( array($this, 'showImage') );
  90. $this->detail_list_anexo->enablePopover('Preview', '<img style="max-width:300px" src="download.php?file=tmp/{CAMINHO_ANEXO}">');
  91. // detail actions
  92. $actionEdit = new TDataGridAction([$this, 'onDetailEditAnexos'] );
  93. $actionEdit->setFields( ['uniqueid', '*'] );
  94. $actionDel = new TDataGridAction([$this, 'onDetailDeleteAnexos']);
  95. $actionDel->setField('uniqueid');
  96. $actionDown = new TDataGridAction([$this, 'onDownload'] );
  97. $actionDown->setFields( ['uniqueid', 'ID'] );
  98. //$actionDown->setField('');
  99. // add the actions to the datagrid
  100. $this->detail_list_anexo->addAction($actionEdit, _t('Edit'), 'fa:edit blue');
  101. $this->detail_list_anexo->addAction($actionDel, _t('Delete'), 'far:trash-alt red');
  102. $this->detail_list_anexo->addAction($actionDown, _t('Download'), 'fas:cloud-download-alt green fa-lg');
  103. $this->detail_list_anexo->createModel();
  104. $panelAnexo = new TPanelGroup;
  105. $panelAnexo->add($this->detail_list_anexo);
  106. $panelAnexo->getBody()->style = 'overflow-x:auto';
  107. $this->form->addContent( [$panelAnexo] );
  108. // detail fields Registro de Evolução
  109. $this->form->addContent( ['<h4>Registro de Evolução</h4><hr>'] );
  110. $this->form->addFields( [$detail_uniqid] );
  111. $this->form->addFields( [$detail_ID] );
  112. $this->form->addFields( [new TLabel('Data Evolucao')], [$detail_DATA_EVOLUCAO] );
  113. $this->form->addFields( [new TLabel('Obs Evolucao')], [$detail_OBS_EVOLUCAO] );
  114. //formatacao datas
  115. $detail_DATA_EVOLUCAO->setMask('dd/mm/yyyy');
  116. $detail_DATA_EVOLUCAO->setDatabaseMask('yyyy-mm-dd');
  117. $detail_OBS_EVOLUCAO->setSize('100%',100);
  118. $add = TButton::create('add', [$this, 'onDetailAdd'], 'Registrar', 'fa:plus-circle green');
  119. $add->getAction()->setParameter('static','1');
  120. $this->form->addFields( [], [$add] );
  121. $this->detail_list = new BootstrapDatagridWrapper(new TDataGrid);
  122. $this->detail_list->setId('Registroevolucao_list');
  123. $this->detail_list->generateHiddenFields();
  124. $this->detail_list->style = "min-width: 700px; width:100%;margin-bottom: 10px";
  125. $evolu = new TDataGridColumn('DATA_EVOLUCAO', 'Data da evolução', 'left', 10);
  126. $criteria = new TCriteria;
  127. $criteria->setProperty('order', 'DATA_EVOLUCAO');
  128. $criteria->setProperty('direction', 'asc');
  129. // items
  130. $this->detail_list->addColumn( new TDataGridColumn('uniqid', 'Uniqid', 'center') )->setVisibility(false);
  131. $this->detail_list->addColumn( new TDataGridColumn('ID', 'Id', 'center') )->setVisibility(false);
  132. $this->detail_list->addColumn( $evolu)->setTransformer(function($value, $object, $row)
  133. {
  134. if($value)
  135. {
  136. $date = new DateTime($value);
  137. return $date->format("d/m/Y");
  138. }
  139. });
  140. $this->detail_list->addColumn( new TDataGridColumn('OBS_EVOLUCAO', 'Observação da evolução', 'left', 100) );
  141. //$DATA_EVOLUCAO->setAction(new TAction([$this, 'onReload']), ['order' => 'DATA_EVOLUCAO']);
  142. $this->detail_list->disableHtmlConversion();
  143. // detail actions
  144. $action1 = new TDataGridAction([$this, 'onDetailEdit'] );
  145. $action1->setFields( ['uniqid', '*'] );
  146. $action2 = new TDataGridAction([$this, 'onDetailDelete']);
  147. $action2->setField('uniqid');
  148. // add the actions to the datagrid
  149. $this->detail_list->addAction($action1, _t('Edit'), 'fa:edit blue');
  150. $this->detail_list->addAction($action2, _t('Delete'), 'far:trash-alt red');
  151. $this->detail_list->createModel();
  152. $panel = new TPanelGroup;
  153. $panel->add($this->detail_list);
  154. $panel->getBody()->style = 'overflow-x:auto';
  155. $this->form->addContent( [$panel] );
  156. $this->form->addAction( 'Salvar', new TAction([$this, 'onSave'], ['static'=>'1']), 'fa:save green');
  157. $this->form->addAction( 'Limpar', new TAction([$this, 'onClear']), 'fa:eraser red');
  158. $this->form->addHeaderAction( 'Salvar até aqui', new TAction([$this, 'onSave']), 'fa:save green' );
  159. // create the page container
  160. $container = new TVBox;
  161. $container->style = 'width: 100%';
  162. $container->add(new TXMLBreadCrumb('menu.xml', __CLASS__));
  163. $container->add($this->form);
  164. parent::add($container);
  165. }
  166. /**
  167. * Clear form
  168. * @param $param URL parameters
  169. */
  170. public function onClear($param)
  171. {
  172. $this->form->clear(TRUE);
  173. }
  174. /**
  175. * Load Master/Detail data from database to form
  176. */
  177. public function onEdit($param)
  178. {
  179. try
  180. {
  181. TTransaction::open('banco');
  182. if (isset($param['key']))
  183. {
  184. $key = $param['key'];
  185. $object = new Prontuarioobrigatorio($key);
  186. //$object->ANEXOS = Prontuarioobrigatorio::where('COD_PAC', '=', $param['key'])->getIndexedArray('id', 'image');
  187. $items = Registroevolucao::where('COD_PAC', '=', $key)->load();
  188. foreach( $items as $item )
  189. {
  190. $item->uniqid = uniqid();
  191. $row = $this->detail_list->addItem( $item );
  192. $row->id = $item->uniqid;
  193. }
  194. $items = Anexos::where('COD_ANEXO', '=', $key)->load();
  195. foreach( $items as $item )
  196. {
  197. $item->uniqueid = uniqid();
  198. $row = $this->detail_list_anexo->addItem( $item );
  199. $row->id = $item->uniqueid;
  200. }
  201. $this->form->setData($object);
  202. TTransaction::close();
  203. }
  204. else
  205. {
  206. $this->form->clear(TRUE);
  207. }
  208. }
  209. catch (Exception $e) // in case of exception
  210. {
  211. new TMessage('error', $e->getMessage());
  212. TTransaction::rollback();
  213. }
  214. }
  215. /**
  216. * Save the Master/Detail data from form to database
  217. */
  218. public function onSave($param)
  219. {
  220. try
  221. {
  222. // open a transaction with database
  223. TTransaction::open('banco');
  224. $data = $this->form->getData();
  225. $this->form->validate();
  226. $master = new Prontuarioobrigatorio;
  227. $master->fromArray( (array) $data);
  228. //$master->ANEXOS = $file;
  229. $master->store();
  230. //$this->form->saveFiles($master, $data, 'ANEXOS', 'files/images','Prontuarioobrigatorio', 'ANEXOS', 'COD_PAC');
  231. //$this->form->saveFilesByComma($master, $data, 'ANEXOS', 'files/images');
  232. //Anexos::where('COD_ANEXO', '=', $master->COD_PAC)->delete();
  233. Anexos::where('COD_ANEXO', '=', $master->COD_PAC)->delete();
  234. if( $param['Anexos_list_DT_ANEXO'] )
  235. {
  236. foreach( $param['Anexos_list_DT_ANEXO'] as $key => $item_id )
  237. {
  238. $detail = new Anexos;
  239. $detail->DT_ANEXO = $param['Anexos_list_DT_ANEXO'][$key];
  240. $detail->CAMINHO_ANEXO = $param['Anexos_list_CAMINHO_ANEXO'][$key];
  241. $detail->COD_ANEXO = $master->COD_PAC;
  242. $detail->store();
  243. }
  244. }
  245. Registroevolucao::where('COD_PAC', '=', $master->COD_PAC)->delete();
  246. if( $param['Registroevolucao_list_DATA_EVOLUCAO'] )
  247. {
  248. foreach( $param['Registroevolucao_list_DATA_EVOLUCAO'] as $key => $item_id )
  249. {
  250. $detail = new Registroevolucao;
  251. $detail->DATA_EVOLUCAO = $param['Registroevolucao_list_DATA_EVOLUCAO'][$key];
  252. $detail->OBS_EVOLUCAO = $param['Registroevolucao_list_OBS_EVOLUCAO'][$key];
  253. $detail->COD_PAC = $master->COD_PAC;
  254. $detail->store();
  255. }
  256. }
  257. TTransaction::close(); // close the transaction
  258. TForm::sendData('form_Prontuarioobrigatorio', (object) ['id' => $master->COD_PAC]);
  259. new TMessage('info', AdiantiCoreTranslator::translate('Record saved'));
  260. }
  261. catch (Exception $e) // in case of exception
  262. {
  263. new TMessage('error', $e->getMessage());
  264. $this->form->setData( $this->form->getData() ); // keep form data
  265. TTransaction::rollback();
  266. }
  267. }
  268. static function onUploadComplete($param)
  269. {
  270. //public static function postData($formName, $class, $method = NULL, $parameters = NULL)
  271. TApplication::postData('form_Prontuarioobrigatorio','ProntuarioobrigatorioForm','onDetailAddAnexos');
  272. }
  273. public function onDetailAddAnexos( $param )
  274. {
  275. try
  276. {
  277. $this->form->validate();
  278. $data = $this->form->getData();
  279. /** validation sample
  280. if (empty($data->fieldX))
  281. {
  282. throw new Exception('The field fieldX is required');
  283. }
  284. **/
  285. $uniqid = !empty($data->detail_uniqueid) ? $data->detail_uniqueid : uniqid();
  286. $grid_data = [];
  287. $grid_data['uniqueid'] = $uniqid;
  288. $grid_data['ID_anexo'] = $data->detail_ID_anexo;
  289. $grid_data['DT_ANEXO'] = $data->detail_DT_ANEXO;
  290. $grid_data['CAMINHO_ANEXO'] = $data->detail_CAMINHO_ANEXO;
  291. // insert row dynamically
  292. $row = $this->detail_list_anexo->addItem( (object) $grid_data );
  293. $row->id = $uniqid;
  294. TDataGrid::replaceRowById('Anexos_list', $uniqid, $row);
  295. // clear detail form fields
  296. $data->detail_uniqueid = '';
  297. $data->detail_ID_anexo = '';
  298. $data->detail_DT_ANEXO = '';
  299. $data->detail_CAMINHO_ANEXO = '';
  300. // send data, do not fire change/exit events
  301. TForm::sendData( 'form_Prontuarioobrigatorio', $data, false, false );
  302. }
  303. catch (Exception $e)
  304. {
  305. $this->form->setData( $this->form->getData());
  306. new TMessage('error', $e->getMessage());
  307. }
  308. }
  309. /**
  310. * Edit detail item
  311. * @param $param URL parameters
  312. */
  313. public static function onDetailEditAnexos( $param )
  314. {
  315. $data = new stdClass;
  316. $data->detail_uniqueid = $param['uniqueid'];
  317. $data->detail_ID_anexo = $param['ID_anexo'];
  318. $data->detail_DT_ANEXO = $param['DT_ANEXO'];
  319. $data->detail_CAMINHO_ANEXO = $param['CAMINHO_ANEXO'];
  320. // send data, do not fire change/exit events
  321. TForm::sendData( 'form_Prontuarioobrigatorio', $data, false, false );
  322. }
  323. /**
  324. * Delete detail item
  325. * @param $param URL parameters
  326. */
  327. public static function onDetailDeleteAnexos( $param )
  328. {
  329. // clear detail form fields
  330. $data = new stdClass;
  331. $data->detail_uniqueid = '';
  332. $data->detail_ID_anexo = '';
  333. $data->detail_DT_ANEXO = '';
  334. $data->detail_CAMINHO_ANEXO = '';
  335. // send data, do not fire change/exit events
  336. TForm::sendData( 'form_Prontuarioobrigatorio', $data, false, false );
  337. // remove row
  338. TDataGrid::removeRowById('Anexos_list', $param['uniqueid']);
  339. }
  340. public function showImage($detail_CAMINHO_ANEXO, $object, $row)
  341. {
  342. $pasta = 'tmp/'; // supondo que a pasta seja tmp
  343. return new TImage($pasta.$detail_CAMINHO_ANEXO);
  344. }
  345. /**
  346. * Download file
  347. */
  348. public static function onDownload($param)
  349. {
  350. try
  351. {
  352. if (isset($param['ID']))
  353. {
  354. $id = $param['ID']; // get the parameter $key
  355. TTransaction::open('banco'); // open a transaction
  356. $object = new Anexos($id); // instantiates the Active Record
  357. if ($object->system_user_id == TSession::getValue('userid') OR TSession::getValue('login') === 'admin')
  358. {
  359. if (strtolower(substr($object->CAMINHO_ANEXO, -4)) == 'pdf')
  360. {
  361. $win = TWindow::create( $object->CAMINHO_ANEXO, 0.8, 0.8 );
  362. $win->add( file_get_contents( "tmp/".$object->CAMINHO_ANEXO ) );
  363. $win->show();
  364. //$this->form->setData( $object );
  365. //TForm::sendData( 'form_Prontuarioobrigatorio', $id, false, false );
  366. }
  367. else
  368. {
  369. TPage::openFile("tmp/".$object->CAMINHO_ANEXO);
  370. }
  371. }
  372. else
  373. {
  374. new TMessage('error', _t('Permission denied'));
  375. }
  376. //TTransaction::close(); // close the transaction
  377. }
  378. else
  379. {
  380. $this->form->clear();
  381. }
  382. //$this->form->setData( $this->form->getData() );
  383. }
  384. catch (Exception $e) // in case of exception
  385. {
  386. new TMessage('error', $e->getMessage()); // shows the exception error message
  387. TTransaction::rollback(); // undo all pending operations
  388. }
  389. }
  390. }
  391. ?>
</your>
A

Usando o botão ele tambem recarrega a pagina, mas não perco os outros details uploads e consigo adicionar varias imagens
NR

Veja que no botão é informado o parâmetro "static = 1". Precisa informar esse parâmetro na postData também:
 
  1. <?php
  2. static function onUploadComplete($param)
  3. {
  4. //public static function postData($formName, $class, $method = NULL, $parameters = NULL)
  5. TApplication::postData('form_Prontuarioobrigatorio','ProntuarioobrigatorioForm','onDetailAddAnexos',['static'=>1]);
  6. }
  7. ?>
A

Deu certo, muito obrigada!