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