erro: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'id Boa tarde Pessoal, Estou tendo problema com uma classe. Tenho um formulário de cadastro de pessoa e não consigo abrir para editar. Efetua o cadastro más não abre para edição. Já tentei de tudo, desde a recriação da classe Pessoa até criar novamente a listagem e o próprio formulário. Nem utilizando o Trait está funcionando. Vou postar o código da classe, do banco de dad...
AR
erro: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'id  
Boa tarde Pessoal,

Estou tendo problema com uma classe.

Tenho um formulário de cadastro de pessoa e não consigo abrir para editar. Efetua o cadastro más não abre para edição.

Já tentei de tudo, desde a recriação da classe Pessoa até criar novamente a listagem e o próprio formulário.

Nem utilizando o Trait está funcionando.

Vou postar o código da classe, do banco de dados e também do formulário.

 
  1. <?php
  2. /**
  3. * Pessoa Active Record
  4. * @author Alexandre M. Roberto
  5. */
  6. class Pessoa extends TRecord
  7. {
  8. const TABLENAME = 'pessoa';
  9. const PRIMARYKEY= 'id';
  10. const IDPOLICY = 'max'; // {max, serial}
  11. const CREATEDAT = 'created_at';
  12. const UPDATEDAT = 'updated_at';
  13. private $status;
  14. private $cidade;
  15. private $comunidade;
  16. private $grupos;
  17. /**
  18. * Constructor method
  19. */
  20. public function __construct($id = NULL, $callObjectLoad = TRUE)
  21. {
  22. parent::__construct($id, $callObjectLoad);
  23. parent::addAttribute('nome');
  24. parent::addAttribute('status_id');
  25. parent::addAttribute('nascimento');
  26. parent::addAttribute('comunidade_id');
  27. parent::addAttribute('cep');
  28. parent::addAttribute('logradouro');
  29. parent::addAttribute('numero');
  30. parent::addAttribute('complemento');
  31. parent::addAttribute('bairro');
  32. parent::addAttribute('cidade_id');
  33. parent::addAttribute('celular');
  34. parent::addAttribute('telefone_coml');
  35. parent::addAttribute('telefone_resid');
  36. parent::addAttribute('email');
  37. parent::addAttribute('contribuinte');
  38. parent::addAttribute('created_at');
  39. parent::addAttribute('updated_at');
  40. }
  41. /**
  42. * Method set_status
  43. * Sample of usage: $pessoa->status = $object;
  44. * @param $object Instance of Status
  45. */
  46. public function set_status(Status $object)
  47. {
  48. $this->status = $object;
  49. $this->status_id = $object->id;
  50. }
  51. /**
  52. * Method get_status
  53. * Sample of usage: $pessoa->status->attribute;
  54. * @returns Status instance
  55. */
  56. public function get_status()
  57. {
  58. // loads the associated object
  59. if (empty($this->status))
  60. $this->status = new Status($this->status_id);
  61. // returns the associated object
  62. return $this->status;
  63. }
  64. /**
  65. * Method set_cidade
  66. * Sample of usage: $pessoa->cidade = $object;
  67. * @param $object Instance of Cidade
  68. */
  69. public function set_cidade(Cidade $object)
  70. {
  71. $this->cidade = $object;
  72. $this->cidade_id = $object->id;
  73. }
  74. /**
  75. * Method get_cidade
  76. * Sample of usage: $pessoa->cidade->attribute;
  77. * @returns Cidade instance
  78. */
  79. public function get_cidade()
  80. {
  81. // loads the associated object
  82. if (empty($this->cidade))
  83. $this->cidade = new Cidade($this->cidade_id);
  84. // returns the associated object
  85. return $this->cidade;
  86. }
  87. /**
  88. * Method set_system_unit
  89. * Sample of usage: $pessoa->system_unit = $object;
  90. * @param $object Instance of SystemUnit
  91. */
  92. public function set_comunidade(SystemUnit $object)
  93. {
  94. $this->comunidade = $object;
  95. $this->comunidade_id = $object->id;
  96. }
  97. /**
  98. * Method get_system_unit
  99. * Sample of usage: $pessoa->system_unit->attribute;
  100. * @returns SystemUnit instance
  101. */
  102. public function get_comunidade()
  103. {
  104. // loads the associated object
  105. if (empty($this->comunidade))
  106. $this->comunidade = new SystemUnit($this->comunidade_id);
  107. // returns the associated object
  108. return $this->comunidade;
  109. }
  110. /**
  111. * Method addGrupo
  112. * Add a Grupo to the Pessoa
  113. * @param $object Instance of Grupo
  114. */
  115. public function addGrupo(Grupo $object)
  116. {
  117. $this->grupos[] = $object;
  118. }
  119. /**
  120. * Method getGrupos
  121. * Return the Pessoa' Grupo's
  122. * @return Collection of Grupo
  123. */
  124. public function getGrupos()
  125. {
  126. return $this->grupos;
  127. }
  128. /**
  129. * Reset aggregates
  130. */
  131. public function clearParts()
  132. {
  133. $this->grupos = array();
  134. }
  135. /**
  136. * Load the object and its aggregates
  137. * @param $id object ID
  138. */
  139. public function load($id)
  140. {
  141. $this->grupos = parent::loadAggregate('Grupo', 'PessoaGrupo', 'pessoa_id', 'grupo_id', $id);
  142. // load the object itself
  143. return parent::load($id);
  144. }
  145. /**
  146. * Store the object and its aggregates
  147. */
  148. public function store()
  149. {
  150. // store the object itself
  151. parent::store();
  152. parent::saveAggregate('PessoaGrupo', 'pessoa_id', 'grupo_id', $this->id, $this->grupos);
  153. }
  154. /**
  155. * Delete the object and its aggregates
  156. * @param $id object ID
  157. */
  158. public function delete($id = NULL)
  159. {
  160. $id = isset($id) ? $id : $this->id;
  161. parent::deleteComposite('PessoaGrupo', 'pessoa_id', $id);
  162. // delete the object itself
  163. parent::delete($id);
  164. }
  165. }
 
  1. <?php
  2. /**
  3. * PessoaForm Form
  4. * @author Alexandre M. Roberto
  5. */
  6. class PessoaForm extends TPage
  7. {
  8. protected $form; // form
  9. /**
  10. * Form constructor
  11. * @param $param Request
  12. */
  13. public function __construct( $param )
  14. {
  15. parent::__construct();
  16. // creates the form
  17. $this->form = new BootstrapFormBuilder('form_Pessoa');
  18. $this->form->setFormTitle('Pessoa');
  19. $this->form->setFieldSizes('100%');
  20. // create the form fields
  21. $id = new TEntry('id');
  22. $nome = new TEntry('nome');
  23. $status_id = new TDBUniqueSearch('status_id', 'permission', 'Status', 'id', 'nome');
  24. $nascimento = new TDate('nascimento');
  25. $filter = new TCriteria();
  26. $filter->add(new TFilter('system_perfil_id', '>', '4'));
  27. $comunidade_id = new TDBCombo('comunidade_id', 'permission', 'SystemUnit', 'id', 'name', 'name asc', $filter);
  28. $cep = new TEntry('cep');
  29. $logradouro = new TEntry('logradouro');
  30. $numero = new TEntry('numero');
  31. $complemento = new TEntry('complemento');
  32. $bairro = new TEntry('bairro');
  33. $filter = new TCriteria;
  34. $filter->add(new TFilter('id', '<', '0'));
  35. $cidade_id = new TDBCombo('cidade_id', 'permission', 'Cidade', 'id', 'nome', 'nome', $filter);
  36. $estado_id = new TDBCombo('estado_id', 'permission', 'Estado', 'id', '{nome} ({uf})');
  37. $celular = new TEntry('celular');
  38. $telefone_coml = new TEntry('telefone_coml');
  39. $telefone_resid = new TEntry('telefone_resid');
  40. $email = new TEntry('email');
  41. $contribuinte = new TCombo('contribuinte');
  42. $grupos = new TDBMultiSearch('grupos', 'permission', 'Grupo', 'id', 'nome');
  43. $nascimento->setMask('dd/mm/yyyy');
  44. $nascimento->setDatabaseMask('yyyy-mm-dd');
  45. $contribuinte->addItems( ['S' => 'Sim', 'N' => 'Não' ] );
  46. $estado_id->setChangeAction( new TAction( [$this, 'onChangeEstado'] ) );
  47. $cep->setExitAction( new TAction([ $this, 'onExitCEP']) );
  48. $comunidade_id->enableSearch();
  49. $cidade_id->enableSearch();
  50. $estado_id->enableSearch();
  51. $cep->setMask('99.999-999');
  52. $grupos->setMinLength(0);
  53. $status_id->setMinLength(0);
  54. // add the fields
  55. $row = $this->form->addFields( [ new TLabel('Id') , $id ],
  56. [ new TLabel('Nome'), $nome ],
  57. [ new TLabel('Status'), $status_id],
  58. [ new TLabel('Dt Nascimento'), $nascimento ] );
  59. $row->layout = [ 'col-sm-2', 'col-sm-6', 'col-sm-2', 'col-sm-2'];
  60. $row = $this->form->addFields( [ new TLabel('Paróquia/Comunidade') , $comunidade_id ],
  61. [ new TLabel('cep'), $cep ],
  62. [ new TLabel('Logradouro'), $logradouro ],
  63. [ new TLabel('Número'), $numero ] );
  64. $row->layout = [ 'col-sm-4', 'col-sm-2', 'col-sm-4', 'col-sm-2'];
  65. $row = $this->form->addFields( [ new TLabel('Complemento') , $complemento ],
  66. [ new TLabel('Bairro'), $bairro ],
  67. [ new TLabel('Cidade'), $cidade_id ],
  68. [ new TLabel('Estado'), $estado_id ] );
  69. $row->layout = [ 'col-sm-2', 'col-sm-4', 'col-sm-4', 'col-sm-2'];
  70. $row = $this->form->addFields( [ new TLabel('Celular') , $celular ],
  71. [ new TLabel('Telefone Coml.'), $telefone_coml ],
  72. [ new TLabel('Telefone Resid.'), $telefone_resid ],
  73. [ new TLabel('E-mail'), $email ],
  74. [ new TLabel('Contribuinte'), $contribuinte ] );
  75. $row->layout = [ 'col-sm-3', 'col-sm-2', 'col-sm-2', 'col-sm-3', 'col-sm-2'];
  76. $row = $this->form->addFields( [ new TLabel('Grupos') , $grupos ] );
  77. $row->layout = [ 'col-sm-12'];
  78. // set sizes
  79. $id->setSize('100%');
  80. $nome->setSize('100%');
  81. $status_id->setSize('100%');
  82. $nascimento->setSize('100%');
  83. $comunidade_id->setSize('100%');
  84. $cep->setSize('100%');
  85. $logradouro->setSize('100%');
  86. $numero->setSize('100%');
  87. $complemento->setSize('100%');
  88. $bairro->setSize('100%');
  89. $cidade_id->setSize('100%');
  90. $celular->setSize('100%');
  91. $telefone_coml->setSize('100%');
  92. $telefone_resid->setSize('100%');
  93. $email->setSize('100%');
  94. $contribuinte->setSize('100%');
  95. $grupos->setSize('100%');
  96. $comunidade_id->addValidation('Paróquia/Comunidade', new TRequiredValidator);
  97. $nome->addValidation('Nome', new TRequiredValidator);
  98. $status_id->addValidation('Status', new TRequiredValidator);
  99. $nascimento->addValidation('Data de Nascimento', new TRequiredValidator);
  100. $email->addValidation('Email', new TRequiredValidator);
  101. $contribuinte->addValidation('Contribuinte', new TRequiredValidator);
  102. if (!empty($id))
  103. {
  104. $id->setEditable(FALSE);
  105. }
  106. /** samples
  107. $fieldX->addValidation( 'Field X', new TRequiredValidator ); // add validation
  108. $fieldX->setSize( '100%' ); // set size
  109. **/
  110. // create the form actions
  111. $btn = $this->form->addAction(_t('Save'), new TAction([$this, 'onSave']), 'fa:save');
  112. $btn->class = 'btn btn-sm btn-primary';
  113. $this->form->addActionLink(_t('New'), new TAction([$this, 'onEdit']), 'fa:eraser red');
  114. $this->form->addActionLink(_t('Back'),new TAction(array('PessoaList','onReload')),'far:arrow-alt-circle-left blue');
  115. // vertical box container
  116. $container = new TVBox;
  117. $container->style = 'width: 100%';
  118. // $container->add(new TXMLBreadCrumb('menu.xml', __CLASS__));
  119. $container->add($this->form);
  120. parent::add($container);
  121. }
  122. /**
  123. * Action to be executed when the user changes the state
  124. * @param $param Action parameters
  125. */
  126. public static function onChangeEstado($param)
  127. {
  128. try
  129. {
  130. TTransaction::open('permission');
  131. if (!empty($param['estado_id']))
  132. {
  133. $criteria = TCriteria::create( ['estado_id' => $param['estado_id'] ] );
  134. // formname, field, database, model, key, value, ordercolumn = NULL, criteria = NULL, startEmpty = FALSE
  135. TDBCombo::reloadFromModel('form_Pessoa', 'cidade_id', 'permission', 'Cidade', 'id', '{nome} ({id})', 'nome', $criteria, TRUE);
  136. }
  137. else
  138. {
  139. TCombo::clearField('form_Pessoa', 'cidade_id');
  140. }
  141. TTransaction::close();
  142. }
  143. catch (Exception $e)
  144. {
  145. new TMessage('error', $e->getMessage());
  146. }
  147. }
  148. /**
  149. * Autocompleta outros campos a partir do CEP
  150. */
  151. public static function onExitCEP($param)
  152. {
  153. session_write_close();
  154. try
  155. {
  156. $cep = preg_replace('/[^0-9]/', '', $param['cep']);
  157. $url = 'https://viacep.com.br/ws/'.$cep.'/json/unicode/';
  158. $content = @file_get_contents($url);
  159. if ($content !== false)
  160. {
  161. $cep_data = json_decode($content);
  162. $data = new stdClass;
  163. if (is_object($cep_data) && empty($cep_data->erro))
  164. {
  165. TTransaction::open('permission');
  166. $estado = Estado::where('uf', '=', $cep_data->uf)->first();
  167. $cidade = Cidade::where('codigo_ibge', '=', $cep_data->ibge)->first();
  168. TTransaction::close();
  169. $data->logradouro = $cep_data->logradouro;
  170. $data->bairro = $cep_data->bairro;
  171. $data->estado_id = $estado->id ?? '';
  172. $data->cidade_id = $cidade->id ?? '';
  173. TForm::sendData('form_Pessoa', $data, false, true);
  174. }
  175. else
  176. {
  177. $data->logradouro = '';
  178. $data->complemento = '';
  179. $data->bairro = '';
  180. $data->estado_id = '';
  181. $data->cidade_id = '';
  182. TForm::sendData('form_Pessoa', $data, false, true);
  183. }
  184. }
  185. }
  186. catch (Exception $e)
  187. {
  188. new TMessage('error', $e->getMessage());
  189. }
  190. }
  191. /**
  192. * Save form data
  193. * @param $param Request
  194. */
  195. public function onSave( $param )
  196. {
  197. try
  198. {
  199. TTransaction::open('permission'); // open a transaction
  200. /**
  201. // Enable Debug logger for SQL operations inside the transaction
  202. TTransaction::setLogger(new TLoggerSTD); // standard output
  203. TTransaction::setLogger(new TLoggerTXT('log.txt')); // file
  204. **/
  205. $this->form->validate(); // validate form data
  206. $data = $this->form->getData(); // get form data as array
  207. $object = new Pessoa; // create an empty object
  208. $object->fromArray( (array) $data); // load the object with data
  209. $object->store(); // save the object
  210. PessoaGrupo::where('pessoa_id', '=', $object->id)->delete();
  211. if ($data->grupos)
  212. {
  213. foreach ($data->grupos as $grupo_id)
  214. {
  215. $pp = new PessoaGrupo;
  216. $pp->pessoa_id = $object->id;
  217. $pp->grupo_id = $grupo_id;
  218. $pp->store();
  219. }
  220. }
  221. // get the generated id
  222. $data->id = $object->id;
  223. $this->form->setData($data); // fill form data
  224. TTransaction::close(); // close the transaction
  225. new TMessage('info', AdiantiCoreTranslator::translate('Record saved'));
  226. }
  227. catch (Exception $e) // in case of exception
  228. {
  229. new TMessage('error', $e->getMessage()); // shows the exception error message
  230. $this->form->setData( $this->form->getData() ); // keep form data
  231. TTransaction::rollback(); // undo all pending operations
  232. }
  233. }
  234. /**
  235. * Clear form data
  236. * @param $param Request
  237. */
  238. public function onClear( $param )
  239. {
  240. $this->form->clear(TRUE);
  241. }
  242. /**
  243. * Load object to form data
  244. * @param $param Request
  245. */
  246. public function onEdit( $param )
  247. {
  248. try
  249. {
  250. if (isset($param['key']))
  251. {
  252. $key = $param['key']; // get the parameter $key
  253. TTransaction::open('permission'); // open a transaction
  254. $object = new Pessoa($key); // instantiates the Active Record
  255. $object->papeis_id = PessoaPapel::where('pessoa_id', '=', $object->id)->getIndexedArray('papel_id');
  256. $this->form->setData($object);
  257. // force fire events
  258. $data = new stdClass;
  259. $data->estado_id = $object->cidade->estado->id;
  260. $data->cidade_id = $object->cidade_id;
  261. TForm::sendData('form_Pessoa', $data);
  262. $this->form->setData($object); // fill the form
  263. TTransaction::close(); // close the transaction
  264. }
  265. else
  266. {
  267. $this->form->clear(TRUE);
  268. }
  269. }
  270. catch (Exception $e) // in case of exception
  271. {
  272. new TMessage('error', $e->getMessage()); // shows the exception error message
  273. TTransaction::rollback(); // undo all pending operations
  274. }
  275. }
  276. }

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


NR

Habilite a exibição do sql, fica mais fácil de descobrir o problema.
AR

Bom dia Natanael,
Desculpe a pergunta, más como eu faço isso?

No log de SQL, não aparece nada.

entrei em um outro cadastro para editar e ver se aparece a operação e apareceu normalmente.

Quando clico em editar, para abrir este formulário, não aparece nada.

No Debug Console, aparece a seguinte informação:
Request URL:
{
class: "PessoaForm",
method: "onEdit",
id: "2",
key: "2"
}

Request Data:
{}
NR

Na função onEdit, após abrir a transação:
 
  1. <?php
  2. TTransaction::setLogger(new TLoggerSTD);
  3. ?>

Esse comando vai mostrar na tela todo o sql que está sendo executado dentro da função onEdit.
AR


Debug: 2020-09-22 11:09:07 - SELECT id, grupo_id, pessoa_id FROM pessoa_grupo WHERE (pessoa_id = '1')
AR

Nataniel,
Obrigado por sua disponibilidade em ajudar!

Retirei a classe load da Model Pessoa.

O formulário carrega se eu tirar o relacionamento de agregação Grupo. Não estou conseguindo carregar a classe agregação Grupo.

Não estou sabendo fazer.
AR

Consegui resolver!
o Erro estava no Banco de dados!
Grato.
JC

O que realizou para a correção deste erro?