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

Pacotão Dominando o Adianti Framework 7
O material mais completo de treinamento do Framework.
Curso em vídeo aulas + Livro completo + Códigos fontes do projeto ERPHouse.
Conteúdo Atualizado! Versão 7.4


Dominando o Adianti 7 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?