2 frames para duas imagens no mesmo form Pessoal tenho um formulário com dois campos de imagem para isso criei 2 frames, conforme código abaixo. Porém ao exibir a imagem está indo para a imagem da resposta creio eu por ter sido a ultima imagem adicionada ao frame. Como faço para identificar em qual frame quero carregar minha imagem? ...
LB
2 frames para duas imagens no mesmo form  
Fechado
Pessoal tenho um formulário com dois campos de imagem para isso criei 2 frames, conforme código abaixo. Porém ao exibir a imagem está indo para a imagem da resposta creio eu por ter sido a ultima imagem adicionada ao frame. Como faço para identificar em qual frame quero carregar minha imagem?
 
  1. <?php e
  2. //adicionando imagem
  3. $this->form->addQuickField('Imagem para Enunciado', $imagem, 400);
  4. $this->frame = new TElement('div');
  5. $this->frame->id = 'photo_frame';
  6. $this->frame->style = 'width:400px;height:auto;min-height:200px;border:1px solid gray;padding:4px;';
  7. $row = $this->form->addRow();
  8. $row->addCell('');
  9. $row->addCell($this->frame);
  10. //adiconando imagem resposta
  11. $this->form->addQuickField('Imagem para Resposta', $imagem_resposta, 400);
  12. $this->frame = new TElement('div');
  13. $this->frame->id = 'photo_frame_respota';
  14. $this->frame->style = 'width:400px;height:auto;min-height:200px;border:1px solid gray;padding:4px;';
  15. $row = $this->form->addRow();
  16. $row->addCell('');
  17. $row->addCell($this->frame);
  18. ?>



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


NR

Leandro, poste todo o código, não consegui simular o problema.
LB

Segue Nataniel o código do meu Form

 
  1. <?php e
  2. /**
  3. * QuestoesFormList Registration
  4. * @author Leandro J N Barbosa
  5. */
  6. class QuestoesFormList extends TPage
  7. {
  8. protected $form; // form
  9. private $frame;
  10. protected $datagrid; // datagrid
  11. protected $pageNavigation;
  12. protected $loaded;
  13. /**
  14. * Class constructor
  15. * Creates the page and the registration form
  16. */
  17. function __construct()
  18. {
  19. parent::__construct();
  20. // creates the form
  21. $this->form = new TQuickForm('form_Questoes');
  22. $this->form->class = 'tform'; // CSS class
  23. $this->form->setFormTitle('Questões'); // define the form title
  24. // create the form fields
  25. $cod_quest = new TEntry('cod_quest');
  26. $cod_cont = new ">TDBSeekButton('cod_cont','super_prova','form_Questoes','Conteudo','descricao','cod_cont','conteudo_descricao');
  27. $conteudo_descricao = new TEntry('conteudo_descricao');
  28. $enunciado = new TText('enunciado');
  29. $imagem = new TFile('imagem');
  30. $alternativas = new TText('alternativas');
  31. $resposta = new TText('resposta');
  32. $imagem_resposta = new TFile('imagem_resposta');
  33. // complete upload action
  34. $imagem->setCompleteAction(new TAction(array($this, 'onComplete')));
  35. // complete upload action resposta
  36. $imagem_resposta->setCompleteAction(new TAction(array($this, 'onCompleteResposta')));
  37. // add the fields
  38. $this->form->addQuickField('Cód. Questão', $cod_quest, 100);
  39. $this->form->addQuickField('Cód. Conteúdo', $cod_cont, 100, new TRequiredValidator );
  40. $this->form->addQuickField('Conteúdo/Tema', $conteudo_descricao, 400);
  41. $this->form->addQuickField('Enunciado', $enunciado, 600, new TRequiredValidator );
  42. $this->form->addQuickField('Alternativas', $alternativas, 600);
  43. $this->form->addQuickField('Resposta', $resposta, 600, new TRequiredValidator );
  44. //adicionando imagem
  45. $this->form->addQuickField('Imagem para Enunciado', $imagem, 400);
  46. $this->frame = new TElement('div');
  47. $this->frame->id = 'photo_frame';
  48. $this->frame->style = 'width:400px;height:auto;min-height:200px;border:1px solid gray;padding:4px;';
  49. $row = $this->form->addRow();
  50. $row->addCell('');
  51. $row->addCell($this->frame);
  52. //adiconando imagem resposta
  53. $this->form->addQuickField('Imagem para Resposta', $imagem_resposta, 400);
  54. $this->frame = new TElement('div');
  55. $this->frame->id = 'photo_frame_respota';
  56. $this->frame->style = 'width:400px;height:auto;min-height:200px;border:1px solid gray;padding:4px;';
  57. $row = $this->form->addRow();
  58. $row->addCell('');
  59. $row->addCell($this->frame);
  60. //desbilitando campo
  61. $cod_quest->setEditable(FALSE);
  62. $conteudo_descricao->setEditable(FALSE);
  63. //Definindo Tamnahos
  64. $imagem->setSize(400, 40);
  65. $imagem_resposta->setSize(400, 40);
  66. $conteudo_descricao->setSize(400, 40);
  67. $enunciado->setSize(600, 100);
  68. $resposta->setSize(600, 100);
  69. $alternativas->setSize(600, 100);
  70. // create the form actions
  71. $this->form->addQuickAction(_t('Save'), new TAction(array($this, 'onSave')), 'ico_save.png');
  72. $this->form->addQuickAction(_t('New'), new TAction(array($this, 'onEdit')), 'ico_new.png');
  73. // creates a DataGrid
  74. $this->datagrid = new TQuickGrid;
  75. $this->datagrid->setHeight(320);
  76. // creates the datagrid columns
  77. $cod_quest = $this->datagrid->addQuickColumn('Cód. Questão', 'cod_quest', 'left', 80);
  78. //$cod_cont = $this->datagrid->addQuickColumn('Cód. Conteúdo', 'cod_cont', 'left', 80);
  79. $conteudo_descricao = $this->datagrid->addQuickColumn('Conteúdo/Tema', 'conteudo_descricao', 'left', 300);
  80. $enunciado = $this->datagrid->addQuickColumn('Enunciado', 'enunciado', 'left', 450);
  81. $alternativas = $this->datagrid->addQuickColumn('Alternativas', 'alternativas', 'left', 400);
  82. $imagem = $this->datagrid->addQuickColumn('Imagem', 'imagem', 'left', 300);
  83. $resposta = $this->datagrid->addQuickColumn('Resposta', 'resposta', 'left', 450);
  84. $imagem_resposta = $this->datagrid->addQuickColumn('Imagem Resposta', 'imagem_resposta', 'left', 300);
  85. // create the datagrid actions
  86. $edit_action = new TDataGridAction(array($this, 'onEdit'));
  87. $delete_action = new TDataGridAction(array($this, 'onDelete'));
  88. // add the actions to the datagrid
  89. $this->datagrid->addQuickAction(_t('Edit'), $edit_action, 'cod_quest', 'ico_edit.png');
  90. $this->datagrid->addQuickAction(_t('Delete'), $delete_action, 'cod_quest', 'ico_delete.png');
  91. // create the datagrid model
  92. $this->datagrid->createModel();
  93. //Cria popover de imagem
  94. $this->datagrid->enablePopover('Imagem', "<img src='{imagem}'>");
  95. // creates the page navigation
  96. $this->pageNavigation = new TPageNavigation;
  97. $this->pageNavigation->setAction(new TAction(array($this, 'onReload')));
  98. $this->pageNavigation->setWidth($this->datagrid->getWidth());
  99. // create the datagrid model
  100. $this->datagrid->createModel();
  101. // creates the page navigation
  102. $this->pageNavigation = new TPageNavigation;
  103. $this->pageNavigation->setAction(new TAction(array($this, 'onReload')));
  104. $this->pageNavigation->setWidth($this->datagrid->getWidth());
  105. // create the page container
  106. $container = TVBox::pack( $this->form, $this->datagrid, $this->pageNavigation);
  107. parent::add($container);
  108. }
  109. /**
  110. * method onReload()
  111. * Load the datagrid with the database objects
  112. */
  113. function onReload($param = NULL)
  114. {
  115. try
  116. {
  117. // open a transaction with database 'super_prova'
  118. TTransaction::open('super_prova');
  119. // creates a repository for Questoes
  120. $repository = new TRepository('Questoes');
  121. $limit = 10;
  122. // creates a criteria
  123. $criteria = new TCriteria;
  124. // default order
  125. if (empty($param['order']))
  126. {
  127. $param['order'] = 'cod_quest';
  128. $param['direction'] = 'asc';
  129. }
  130. $criteria->setProperties($param); // order, offset
  131. $criteria->setProperty('limit', $limit);
  132. if (TSession::getValue('Questoes_filter'))
  133. {
  134. // add the filter stored in the session to the criteria
  135. $criteria->add(TSession::getValue('Questoes_filter'));
  136. }
  137. // load the objects according to criteria
  138. $objects = $repository->load($criteria, FALSE);
  139. $this->datagrid->clear();
  140. if ($objects)
  141. {
  142. // iterate the collection of active records
  143. foreach ($objects as $object)
  144. {
  145. // add the object inside the datagrid
  146. $this->datagrid->addItem($object);
  147. }
  148. }
  149. // reset the criteria for record count
  150. $criteria->resetProperties();
  151. $count= $repository->count($criteria);
  152. $this->pageNavigation->setCount($count); // count of records
  153. $this->pageNavigation->setProperties($param); // order, page
  154. $this->pageNavigation->setLimit($limit); // limit
  155. // close the transaction
  156. TTransaction::close();
  157. $this->loaded = true;
  158. }
  159. catch (Exception $e) // in case of exception
  160. {
  161. new TMessage('error', '<b>Error</b> ' . $e->getMessage()); // shows the exception error message
  162. TTransaction::rollback(); // undo all pending operations
  163. }
  164. }
  165. /**
  166. * method onDelete()
  167. * executed whenever the user clicks at the delete button
  168. * Ask if the user really wants to delete the record
  169. */
  170. function onDelete($param)
  171. {
  172. // define the delete action
  173. $action = new TAction(array($this, 'Delete'));
  174. $action->setParameters($param); // pass the key parameter ahead
  175. // shows a dialog to the user
  176. new TQuestion(TAdiantiCoreTranslator::translate('Do you really want to delete ?'), $action);
  177. }
  178. /**
  179. * method Delete()
  180. * Delete a record
  181. */
  182. function Delete($param)
  183. {
  184. try
  185. {
  186. // get the parameter $key
  187. $key=$param['key'];
  188. TTransaction::open('super_prova'); // open the transaction
  189. $object = new Questoes($key, FALSE); // instantiates the Active Record
  190. if ($object->imagem != '')
  191. unlink($object->imagem);
  192. if ($object->imagem_resposta != '')
  193. unlink($object->imagem_resposta);
  194. $object->delete(); // deletes the object
  195. TTransaction::close(); // close the transaction
  196. $this->onReload( $param ); // reload the listing
  197. new TMessage('info', TAdiantiCoreTranslator::translate('Record deleted')); // success message
  198. }
  199. catch (Exception $e) // in case of exception
  200. {
  201. new TMessage('error', '<b>Error</b> ' . $e->getMessage()); // shows the exception error message
  202. TTransaction::rollback(); // undo all pending operations
  203. }
  204. }
  205. /**
  206. * method onSave()
  207. * Executed whenever the user clicks at the save button
  208. */
  209. function onSave()
  210. {
  211. try
  212. {
  213. TTransaction::open('super_prova'); // open a transaction with database
  214. // get the form data into an active record Questoes
  215. $object = $this->form->getData('Questoes');
  216. $this->form->validate(); // form validation
  217. //Gravando Imagem
  218. $source_file = 'tmp/'.$object->imagem;
  219. $target_file = 'images/' . $object->imagem;
  220. $extensao = pathinfo ( $object->imagem, PATHINFO_EXTENSION );
  221. $source_file_resp = 'tmp/'.$object->imagem_resposta;
  222. $target_file_resp = 'images/' . $object->imagem_resposta;
  223. $extensao_resp = pathinfo ( $object->imagem_resposta, PATHINFO_EXTENSION );
  224. if($extensao != '')
  225. if ( ($extensao != 'jpg') AND ($extensao != 'jpeg') AND ($extensao != 'bmp') AND ($extensao != 'gif') AND ($extensao != 'png'))
  226. {
  227. unlink($source_file);
  228. throw new Exception(' <b>Arquivo inválido, o arquivo não é uma extensão de imagem, selecione outro arquivo de imagem!</b><br>
  229. <b>Extensões permitidas (JPG, JPEG, BMP, GIF, PNG)</b>');
  230. }
  231. if($extensao_resp != '')
  232. if ( ($extensao_resp != 'jpg') AND ($extensao_resp != 'jpeg') AND ($extensao_resp != 'bmp') AND ($extensao_resp != 'gif') AND ($extensao_resp != 'png'))
  233. {
  234. unlink($source_file_resp);
  235. throw new Exception(' <b>Arquivo inválido, o arquivo não é uma extensão de imagem, selecione outro arquivo de imagem!</b><br>
  236. <b>Extensões permitidas (JPG, JPEG, BMP, GIF, PNG)</b>');
  237. }
  238. // if the user uploaded a source file
  239. //new TMessage($object->cod_quest);
  240. if (file_exists($source_file) AND ($extensao != ''))
  241. {
  242. //move to the target directory
  243. $novoNome = uniqid ( time () ) .'.'. $extensao;
  244. $target_file = 'images/'.$novoNome;
  245. rename($source_file, $target_file);
  246. //atualizando a imagem
  247. $object->imagem = $target_file;
  248. $image = new TImage($object->imagem);
  249. $image->style = 'width: 100%';
  250. $this->frame->add( $image );
  251. }
  252. if (file_exists($source_file_resp) AND ($extensao_resp != ''))
  253. {
  254. //move to the target directory
  255. $novoNome_resp = uniqid ( time () ) .'.'. $extensao_resp;
  256. $target_file_resp = 'images/'.$novoNome_resp;
  257. rename($source_file_resp, $target_file_resp);
  258. //atualizando a imagem
  259. $object->imagem_resposta = $target_file_resp;
  260. $image_resp = new TImage($object->imagem_resposta);
  261. $image_resp->style = 'width: 100%';
  262. $this->frame->add( $image_resp );
  263. }
  264. //Fim Gravação imagem
  265. $object->store(); // stores the object
  266. $this->form->setData($object); // fill the form with the active record data
  267. TTransaction::close(); // close the transaction
  268. new TMessage('info', TAdiantiCoreTranslator::translate('Record saved')); // success message
  269. $this->onReload(); // reload the listing
  270. }
  271. catch (Exception $e) // in case of exception
  272. {
  273. new TMessage('error', '<b>Error</b> ' . $e->getMessage()); // shows the exception error message
  274. TTransaction::rollback(); // undo all pending operations
  275. }
  276. }
  277. /**
  278. * method onEdit()
  279. * Executed whenever the user clicks at the edit button da datagrid
  280. */
  281. function onEdit($param)
  282. {
  283. try
  284. {
  285. if (isset($param['key']))
  286. {
  287. $key=$param['key']; // get the parameter $key
  288. TTransaction::open('super_prova'); // open a transaction with the database
  289. $object = new Questoes($key); // instantiates the Active Record
  290. //mostra imagem
  291. if ($object)
  292. {
  293. $image = new TImage($object->imagem);
  294. $image->style = 'width: 100%';
  295. $this->frame->id = 'photo_frame';
  296. $this->frame->add( $image );
  297. $image_resp = new TImage($object->imagem_resposta);
  298. $image_resp->style = 'width: 100%';
  299. $this->frame->id = 'photo_frame_resposta';
  300. $this->frame->add( $image_resp );
  301. }
  302. $this->form->setData($object); // fill the form with the active record data
  303. TTransaction::close(); // close the transaction
  304. }
  305. else
  306. {
  307. $this->form->clear();
  308. }
  309. }
  310. catch (Exception $e) // in case of exception
  311. {
  312. new TMessage('error', '<b>Error</b> ' . $e->getMessage()); // shows the exception error message
  313. TTransaction::rollback(); // undo all pending operations
  314. }
  315. }
  316. /**
  317. * method show()
  318. * Shows the page e seu conteúdo
  319. */
  320. function show()
  321. {
  322. // check if the datagrid is already loaded
  323. if (!$this->loaded AND (!isset($_GET['method']) OR $_GET['method'] !== 'onReload') )
  324. {
  325. $this->onReload( func_get_arg(0) );
  326. }
  327. parent::show();
  328. }
  329. /**
  330. * On complete upload
  331. */
  332. public static function onComplete($param)
  333. {
  334. new TMessage('info', 'Upload completed: '.$param['imagem']);
  335. // refresh photo_frame
  336. TScript::create("$('#photo frame').html('')");
  337. TScript::create("$('#photo_frame').append(\\"<img style='width:100%' src='tmp/{$param['imagem']}'>\\");");
  338. }
  339. /**
  340. * On complete upload
  341. */
  342. public static function onCompleteResposta($param)
  343. {
  344. new TMessage('info', 'Upload completed: '.$param['imagem_resposta']);
  345. // refresh photo_frame_reposta
  346. TScript::create("$('#photo frame_resposta').html('')");
  347. TScript::create("$('#photo_frame_resposta').append(\\"<img style='width:100%' src='tmp/{$param['imagem_resposta']}'>\\");");
  348. }
  349. }
  350. ?>

NR

Leandro, verifique a linha 62, há um erro na escrita. Deveria ser RESPOSTA ao invés de RESPOTA. Tá faltando o S.
 
  1. <?php
  2. $this->frame->id = 'photo_frame_respota';
  3. ?>

LB

Nataniel, apesar do erro de digitação nã é ele quem está causando o problema, a imagem está carregando no frame errado, tenho dois campos de imagem e a "Imagem Enunciado" está sendo carregada dento do frame destinado a "Imagem Resposta". Estou meio perdido com esse problema.
NR

Aqui funcionou certinho, cada imagem em seu frame.
LB

Nataniel tem como identificar a frame que quero que a imagem seja criada tipo quando dou o comando $this->frame->add( $image );
NR

Leandro, provavelmente teu problema está em utilizar a mesma variável para os 2 frames: $this->frame
Acontece que ao sair do construct, $this->frame só corresponde ao frame2 e você não tem mais a instância do frame1.

Criando 2 variáveis o problema deve ser resolvido
LB

Vou tentar e reporto o resultado.
Obrigado por enquanto.
LB

Nataniel, você é o mestre do pHP kkkkkk, funcionou perfeitamente com duas variáveis, muito obrigado!

Um abraço.