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.
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.
- <?php
- /**
- * Pessoa Active Record
- * @author Alexandre M. Roberto
- */
- class Pessoa extends TRecord
- {
- const TABLENAME = 'pessoa';
- const PRIMARYKEY= 'id';
- const IDPOLICY = 'max'; // {max, serial}
- const CREATEDAT = 'created_at';
- const UPDATEDAT = 'updated_at';
- private $status;
- private $cidade;
- private $comunidade;
- private $grupos;
- /**
- * Constructor method
- */
- public function __construct($id = NULL, $callObjectLoad = TRUE)
- {
- parent::__construct($id, $callObjectLoad);
- parent::addAttribute('nome');
- parent::addAttribute('status_id');
- parent::addAttribute('nascimento');
- parent::addAttribute('comunidade_id');
- parent::addAttribute('cep');
- parent::addAttribute('logradouro');
- parent::addAttribute('numero');
- parent::addAttribute('complemento');
- parent::addAttribute('bairro');
- parent::addAttribute('cidade_id');
- parent::addAttribute('celular');
- parent::addAttribute('telefone_coml');
- parent::addAttribute('telefone_resid');
- parent::addAttribute('email');
- parent::addAttribute('contribuinte');
- parent::addAttribute('created_at');
- parent::addAttribute('updated_at');
- }
- /**
- * Method set_status
- * Sample of usage: $pessoa->status = $object;
- * @param $object Instance of Status
- */
- public function set_status(Status $object)
- {
- $this->status = $object;
- $this->status_id = $object->id;
- }
- /**
- * Method get_status
- * Sample of usage: $pessoa->status->attribute;
- * @returns Status instance
- */
- public function get_status()
- {
- // loads the associated object
- if (empty($this->status))
- $this->status = new Status($this->status_id);
- // returns the associated object
- return $this->status;
- }
- /**
- * Method set_cidade
- * Sample of usage: $pessoa->cidade = $object;
- * @param $object Instance of Cidade
- */
- public function set_cidade(Cidade $object)
- {
- $this->cidade = $object;
- $this->cidade_id = $object->id;
- }
- /**
- * Method get_cidade
- * Sample of usage: $pessoa->cidade->attribute;
- * @returns Cidade instance
- */
- public function get_cidade()
- {
- // loads the associated object
- if (empty($this->cidade))
- $this->cidade = new Cidade($this->cidade_id);
- // returns the associated object
- return $this->cidade;
- }
- /**
- * Method set_system_unit
- * Sample of usage: $pessoa->system_unit = $object;
- * @param $object Instance of SystemUnit
- */
- public function set_comunidade(SystemUnit $object)
- {
- $this->comunidade = $object;
- $this->comunidade_id = $object->id;
- }
- /**
- * Method get_system_unit
- * Sample of usage: $pessoa->system_unit->attribute;
- * @returns SystemUnit instance
- */
- public function get_comunidade()
- {
- // loads the associated object
- if (empty($this->comunidade))
- $this->comunidade = new SystemUnit($this->comunidade_id);
- // returns the associated object
- return $this->comunidade;
- }
- /**
- * Method addGrupo
- * Add a Grupo to the Pessoa
- * @param $object Instance of Grupo
- */
- public function addGrupo(Grupo $object)
- {
- $this->grupos[] = $object;
- }
- /**
- * Method getGrupos
- * Return the Pessoa' Grupo's
- * @return Collection of Grupo
- */
- public function getGrupos()
- {
- return $this->grupos;
- }
- /**
- * Reset aggregates
- */
- public function clearParts()
- {
- $this->grupos = array();
- }
- /**
- * Load the object and its aggregates
- * @param $id object ID
- */
- public function load($id)
- {
- $this->grupos = parent::loadAggregate('Grupo', 'PessoaGrupo', 'pessoa_id', 'grupo_id', $id);
- // load the object itself
- return parent::load($id);
- }
- /**
- * Store the object and its aggregates
- */
- public function store()
- {
- // store the object itself
- parent::store();
- parent::saveAggregate('PessoaGrupo', 'pessoa_id', 'grupo_id', $this->id, $this->grupos);
- }
- /**
- * Delete the object and its aggregates
- * @param $id object ID
- */
- public function delete($id = NULL)
- {
- $id = isset($id) ? $id : $this->id;
- parent::deleteComposite('PessoaGrupo', 'pessoa_id', $id);
- // delete the object itself
- parent::delete($id);
- }
- }
- <?php
- /**
- * PessoaForm Form
- * @author Alexandre M. Roberto
- */
- class PessoaForm extends TPage
- {
- protected $form; // form
- /**
- * Form constructor
- * @param $param Request
- */
- public function __construct( $param )
- {
- parent::__construct();
- // creates the form
- $this->form = new BootstrapFormBuilder('form_Pessoa');
- $this->form->setFormTitle('Pessoa');
- $this->form->setFieldSizes('100%');
- // create the form fields
- $id = new TEntry('id');
- $nome = new TEntry('nome');
- $status_id = new TDBUniqueSearch('status_id', 'permission', 'Status', 'id', 'nome');
- $nascimento = new TDate('nascimento');
- $filter = new TCriteria();
- $filter->add(new TFilter('system_perfil_id', '>', '4'));
- $comunidade_id = new TDBCombo('comunidade_id', 'permission', 'SystemUnit', 'id', 'name', 'name asc', $filter);
- $cep = new TEntry('cep');
- $logradouro = new TEntry('logradouro');
- $numero = new TEntry('numero');
- $complemento = new TEntry('complemento');
- $bairro = new TEntry('bairro');
- $filter = new TCriteria;
- $filter->add(new TFilter('id', '<', '0'));
- $cidade_id = new TDBCombo('cidade_id', 'permission', 'Cidade', 'id', 'nome', 'nome', $filter);
- $estado_id = new TDBCombo('estado_id', 'permission', 'Estado', 'id', '{nome} ({uf})');
- $celular = new TEntry('celular');
- $telefone_coml = new TEntry('telefone_coml');
- $telefone_resid = new TEntry('telefone_resid');
- $email = new TEntry('email');
- $contribuinte = new TCombo('contribuinte');
- $grupos = new TDBMultiSearch('grupos', 'permission', 'Grupo', 'id', 'nome');
- $nascimento->setMask('dd/mm/yyyy');
- $nascimento->setDatabaseMask('yyyy-mm-dd');
- $contribuinte->addItems( ['S' => 'Sim', 'N' => 'Não' ] );
- $estado_id->setChangeAction( new TAction( [$this, 'onChangeEstado'] ) );
- $cep->setExitAction( new TAction([ $this, 'onExitCEP']) );
- $comunidade_id->enableSearch();
- $cidade_id->enableSearch();
- $estado_id->enableSearch();
- $cep->setMask('99.999-999');
- $grupos->setMinLength(0);
- $status_id->setMinLength(0);
- // add the fields
- $row = $this->form->addFields( [ new TLabel('Id') , $id ],
- [ new TLabel('Nome'), $nome ],
- [ new TLabel('Status'), $status_id],
- [ new TLabel('Dt Nascimento'), $nascimento ] );
- $row->layout = [ 'col-sm-2', 'col-sm-6', 'col-sm-2', 'col-sm-2'];
- $row = $this->form->addFields( [ new TLabel('Paróquia/Comunidade') , $comunidade_id ],
- [ new TLabel('cep'), $cep ],
- [ new TLabel('Logradouro'), $logradouro ],
- [ new TLabel('Número'), $numero ] );
- $row->layout = [ 'col-sm-4', 'col-sm-2', 'col-sm-4', 'col-sm-2'];
- $row = $this->form->addFields( [ new TLabel('Complemento') , $complemento ],
- [ new TLabel('Bairro'), $bairro ],
- [ new TLabel('Cidade'), $cidade_id ],
- [ new TLabel('Estado'), $estado_id ] );
- $row->layout = [ 'col-sm-2', 'col-sm-4', 'col-sm-4', 'col-sm-2'];
- $row = $this->form->addFields( [ new TLabel('Celular') , $celular ],
- [ new TLabel('Telefone Coml.'), $telefone_coml ],
- [ new TLabel('Telefone Resid.'), $telefone_resid ],
- [ new TLabel('E-mail'), $email ],
- [ new TLabel('Contribuinte'), $contribuinte ] );
- $row->layout = [ 'col-sm-3', 'col-sm-2', 'col-sm-2', 'col-sm-3', 'col-sm-2'];
- $row = $this->form->addFields( [ new TLabel('Grupos') , $grupos ] );
- $row->layout = [ 'col-sm-12'];
- // set sizes
- $id->setSize('100%');
- $nome->setSize('100%');
- $status_id->setSize('100%');
- $nascimento->setSize('100%');
- $comunidade_id->setSize('100%');
- $cep->setSize('100%');
- $logradouro->setSize('100%');
- $numero->setSize('100%');
- $complemento->setSize('100%');
- $bairro->setSize('100%');
- $cidade_id->setSize('100%');
- $celular->setSize('100%');
- $telefone_coml->setSize('100%');
- $telefone_resid->setSize('100%');
- $email->setSize('100%');
- $contribuinte->setSize('100%');
- $grupos->setSize('100%');
- $comunidade_id->addValidation('Paróquia/Comunidade', new TRequiredValidator);
- $nome->addValidation('Nome', new TRequiredValidator);
- $status_id->addValidation('Status', new TRequiredValidator);
- $nascimento->addValidation('Data de Nascimento', new TRequiredValidator);
- $email->addValidation('Email', new TRequiredValidator);
- $contribuinte->addValidation('Contribuinte', new TRequiredValidator);
- if (!empty($id))
- {
- $id->setEditable(FALSE);
- }
- /** samples
- $fieldX->addValidation( 'Field X', new TRequiredValidator ); // add validation
- $fieldX->setSize( '100%' ); // set size
- **/
- // create the form actions
- $btn = $this->form->addAction(_t('Save'), new TAction([$this, 'onSave']), 'fa:save');
- $btn->class = 'btn btn-sm btn-primary';
- $this->form->addActionLink(_t('New'), new TAction([$this, 'onEdit']), 'fa:eraser red');
- $this->form->addActionLink(_t('Back'),new TAction(array('PessoaList','onReload')),'far:arrow-alt-circle-left blue');
- // vertical box container
- $container = new TVBox;
- $container->style = 'width: 100%';
- // $container->add(new TXMLBreadCrumb('menu.xml', __CLASS__));
- $container->add($this->form);
- parent::add($container);
- }
- /**
- * Action to be executed when the user changes the state
- * @param $param Action parameters
- */
- public static function onChangeEstado($param)
- {
- try
- {
- TTransaction::open('permission');
- if (!empty($param['estado_id']))
- {
- $criteria = TCriteria::create( ['estado_id' => $param['estado_id'] ] );
- // formname, field, database, model, key, value, ordercolumn = NULL, criteria = NULL, startEmpty = FALSE
- TDBCombo::reloadFromModel('form_Pessoa', 'cidade_id', 'permission', 'Cidade', 'id', '{nome} ({id})', 'nome', $criteria, TRUE);
- }
- else
- {
- TCombo::clearField('form_Pessoa', 'cidade_id');
- }
- TTransaction::close();
- }
- catch (Exception $e)
- {
- new TMessage('error', $e->getMessage());
- }
- }
- /**
- * Autocompleta outros campos a partir do CEP
- */
- public static function onExitCEP($param)
- {
- session_write_close();
- try
- {
- $cep = preg_replace('/[^0-9]/', '', $param['cep']);
- $url = 'https://viacep.com.br/ws/'.$cep.'/json/unicode/';
- $content = @file_get_contents($url);
- if ($content !== false)
- {
- $cep_data = json_decode($content);
- $data = new stdClass;
- if (is_object($cep_data) && empty($cep_data->erro))
- {
- TTransaction::open('permission');
- $estado = Estado::where('uf', '=', $cep_data->uf)->first();
- $cidade = Cidade::where('codigo_ibge', '=', $cep_data->ibge)->first();
- TTransaction::close();
- $data->logradouro = $cep_data->logradouro;
- $data->bairro = $cep_data->bairro;
- $data->estado_id = $estado->id ?? '';
- $data->cidade_id = $cidade->id ?? '';
- TForm::sendData('form_Pessoa', $data, false, true);
- }
- else
- {
- $data->logradouro = '';
- $data->complemento = '';
- $data->bairro = '';
- $data->estado_id = '';
- $data->cidade_id = '';
- TForm::sendData('form_Pessoa', $data, false, true);
- }
- }
- }
- catch (Exception $e)
- {
- new TMessage('error', $e->getMessage());
- }
- }
- /**
- * Save form data
- * @param $param Request
- */
- public function onSave( $param )
- {
- try
- {
- TTransaction::open('permission'); // open a transaction
- /**
- // Enable Debug logger for SQL operations inside the transaction
- TTransaction::setLogger(new TLoggerSTD); // standard output
- TTransaction::setLogger(new TLoggerTXT('log.txt')); // file
- **/
- $this->form->validate(); // validate form data
- $data = $this->form->getData(); // get form data as array
- $object = new Pessoa; // create an empty object
- $object->fromArray( (array) $data); // load the object with data
- $object->store(); // save the object
- PessoaGrupo::where('pessoa_id', '=', $object->id)->delete();
- if ($data->grupos)
- {
- foreach ($data->grupos as $grupo_id)
- {
- $pp = new PessoaGrupo;
- $pp->pessoa_id = $object->id;
- $pp->grupo_id = $grupo_id;
- $pp->store();
- }
- }
- // get the generated id
- $data->id = $object->id;
- $this->form->setData($data); // fill form data
- TTransaction::close(); // close the transaction
- new TMessage('info', AdiantiCoreTranslator::translate('Record saved'));
- }
- catch (Exception $e) // in case of exception
- {
- new TMessage('error', $e->getMessage()); // shows the exception error message
- $this->form->setData( $this->form->getData() ); // keep form data
- TTransaction::rollback(); // undo all pending operations
- }
- }
- /**
- * Clear form data
- * @param $param Request
- */
- public function onClear( $param )
- {
- $this->form->clear(TRUE);
- }
- /**
- * Load object to form data
- * @param $param Request
- */
- public function onEdit( $param )
- {
- try
- {
- if (isset($param['key']))
- {
- $key = $param['key']; // get the parameter $key
- TTransaction::open('permission'); // open a transaction
- $object = new Pessoa($key); // instantiates the Active Record
- $object->papeis_id = PessoaPapel::where('pessoa_id', '=', $object->id)->getIndexedArray('papel_id');
- $this->form->setData($object);
- // force fire events
- $data = new stdClass;
- $data->estado_id = $object->cidade->estado->id;
- $data->cidade_id = $object->cidade_id;
- TForm::sendData('form_Pessoa', $data);
- $this->form->setData($object); // fill the form
- TTransaction::close(); // close the transaction
- }
- else
- {
- $this->form->clear(TRUE);
- }
- }
- catch (Exception $e) // in case of exception
- {
- new TMessage('error', $e->getMessage()); // shows the exception error message
- TTransaction::rollback(); // undo all pending operations
- }
- }
- }
Habilite a exibição do sql, fica mais fácil de descobrir o problema.
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:
{}
Na função onEdit, após abrir a transação:
Esse comando vai mostrar na tela todo o sql que está sendo executado dentro da função onEdit.
Debug: 2020-09-22 11:09:07 - SELECT id, grupo_id, pessoa_id FROM pessoa_grupo WHERE (pessoa_id = '1')
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.
Consegui resolver!
o Erro estava no Banco de dados!
Grato.
O que realizou para a correção deste erro?