Lançado Adianti Framework 7.6!
Clique aqui para saber mais
Dados não Carrega na datagrid Olá a todos, Tenho a seguinte estrutura no banco Pessoa IdPessoa, Nome ... PessoaFisica IdPessoa, CPF, ... PessoaEndereco IdPessoa, IdEndereco, .... Endereco IdEndereco, Logradouro .... Criei as classes conforme abaixo. Model Pessoa ...
RB
Dados não Carrega na datagrid  
Olá a todos,

Tenho a seguinte estrutura no banco

Pessoa
IdPessoa,
Nome
...

PessoaFisica
IdPessoa,
CPF,
...

PessoaEndereco
IdPessoa,
IdEndereco,
....
Endereco
IdEndereco,
Logradouro
....


Criei as classes conforme abaixo.

Model Pessoa
  1. <?php
  2. /**
  3.  * Pessoa Active Record
  4.  * @author  <your-name-here>
  5.  */
  6. class Pessoa extends TRecord
  7. {
  8.     const TABLENAME 'Pessoa';
  9.     const PRIMARYKEY'IdPessoa';
  10.     const IDPOLICY =  'max'// {max, serial}    
  11.     /**
  12.      * Constructor method
  13.      */
  14.     public function __construct($id NULL$callObjectLoad TRUE)
  15.     {
  16.         parent::__construct($id$callObjectLoad);
  17.         parent::addAttribute('Nome');
  18.     }
  19. }
  20. ?>


Model PessoaFisica

  1. <?php
  2. /**
  3.  * Pessoafisica Active Record
  4.  * @author  <your-name-here>
  5.  */
  6. class Pessoafisica extends TRecord
  7. {
  8.     const TABLENAME 'PessoaFisica';
  9.     const PRIMARYKEY'IdPessoaFisica';
  10.     const IDPOLICY =  'max'// {max, serial}
  11.     
  12.      private $pessoa;
  13.     
  14.     /**
  15.      * Constructor method
  16.      */
  17.     public function __construct($id NULL$callObjectLoad TRUE)
  18.     {
  19.         parent::__construct($id$callObjectLoad);
  20.         parent::addAttribute('IdPessoa');
  21.         parent::addAttribute('CPF');
  22.        
  23.     }
  24. }
  25. ?>


Model PessoaEndereco
  1. <?php
  2. /**
  3.  * PessoaPessoaEndereco Active Record
  4.  * @author  <your-name-here>
  5.  */
  6. class PessoaEndereco extends TRecord
  7. {
  8.     const TABLENAME 'PessoaEndereco';
  9.     const PRIMARYKEY'id';
  10.     const IDPOLICY =  'max'// {max, serial}
  11.     
  12.     
  13.     /**
  14.      * Constructor method
  15.      */
  16.     public function __construct($id NULL$callObjectLoad TRUE)
  17.     {
  18.         parent::__construct($id$callObjectLoad);
  19.         parent::addAttribute('Id');
  20.         parent::addAttribute('IdPessoa');
  21.     }
  22. }
  23. Model Endereco
  1. <?php
  2. /**
  3.  * Endereco Active Record
  4.  * @author  <your-name-here>
  5.  */
  6. class Endereco extends TRecord
  7. {
  8.     const TABLENAME 'Endereco';
  9.     const PRIMARYKEY'IdEndereco';
  10.     const IDPOLICY =  'max'// {max, serial}
  11.     
  12.     /**
  13.      * Constructor method
  14.      */
  15.     public function __construct($id NULL$callObjectLoad TRUE)
  16.     {
  17.         parent::__construct($id$callObjectLoad);
  18.         parent::addAttribute('Logradouro');
  19.         parent::addAttribute('Bairro');
  20.         parent::addAttribute('Cep');
  21.         parent::addAttribute('Cidade');
  22.         parent::addAttribute('Estado');
  23.         parent::addAttribute('Pais');
  24.         parent::addAttribute('Latitude');
  25.         parent::addAttribute('Longitude');
  26.         parent::addAttribute('CodigoIbge');
  27.         parent::addAttribute('Gia');
  28.         parent::addAttribute('Criacao');
  29.         parent::addAttribute('Atualizacao');
  30.     }
  31.     
  32. }
  33. ?>



Classe que Carrega a datagrid

  1. <?php
  2. class ClienteFisicoForm extends TPage {
  3.   
  4.     private $datagrid;  // listing
  5.     private $pageNavigation;
  6.     private $loaded;
  7.   public function __construct() {
  8.     parent::__construct();
  9.     // creates one datagrid
  10.     $this -> datagrid = new TQuickGrid;
  11.     $this -> datagrid -> style 'width: 100%';
  12.     $this -> datagrid -> makeScrollable();
  13.     $this -> datagrid -> setHeight(300);
  14.     // add the columns
  15.     $this -> datagrid -> addQuickColumn('#''IdPessoa''right''5%');
  16.     $this -> datagrid -> addQuickColumn('Nome''name''left''20%');
  17.     $this -> datagrid -> addQuickColumn('Data Nasc''dataNasc''left''8%');
  18.     $this -> datagrid -> addQuickColumn('Estado Cívil''civil''left''10%');
  19.     $this -> datagrid -> addQuickColumn('Genero''genero''left''8%');
  20.     $this -> datagrid -> addQuickColumn('CPF''cpf''left''7%');
  21.     $this -> datagrid -> addQuickColumn('RG / CNH''rg''left''10%');
  22.     $this -> datagrid -> addQuickColumn('Telefone''telefone''left''10%');
  23.     $this -> datagrid -> addQuickColumn('Celular''celular''left''10%');
  24.     $this -> datagrid -> addQuickColumn('E-mail''email''left''10%');
  25.     $this -> datagrid -> addQuickColumn('Site''site');
  26.     $this -> datagrid -> addQuickColumn('Cep''cep''left''10%');
  27.     $this -> datagrid -> addQuickColumn('Logradouro''logradouro');
  28.     $this -> datagrid -> addQuickColumn('Número''numero');
  29.     $this -> datagrid -> addQuickColumn('Bairro''bairro');
  30.     $this -> datagrid -> addQuickColumn('UF''uf');
  31.     $this -> datagrid -> addQuickColumn('Cidade''cidade');
  32.     $this -> datagrid -> addQuickColumn('Tipo Endereço''tipoEndereco');
  33.     $this -> datagrid -> addQuickColumn('Complemento''complemento');
  34.     // add the actions
  35.     $this -> datagrid -> addQuickAction('Input', new TDataGridAction( array($this'onInputDialog')), 'name''fa:external-link');
  36.     // creates the datagrid model
  37.     $this -> datagrid -> createModel();
  38.     // wrap the page content using vertical box
  39.     $vbox = new TVBox;
  40.     $vbox -> add(new TXMLBreadCrumb('menu.xml'__CLASS__));
  41.     $vbox -> add($this -> datagrid);
  42.     parent::add($vbox);
  43.   }
  44.   /**
  45.    * Load the data into the datagrid
  46.    */
  47.   function onReload($param null) {
  48.     try {
  49.       parent::setDatabast('sgvo');//abre a transação
  50.            
  51.       //cria o repositorio Pessoa
  52.       $rep_pessoa = new TRepository('Pessoa');
  53.       $limit 10;
  54.       //cria o critério de seleção
  55.       $criteria = new TCriteria;
  56.       $criteria -> setProperties($param);//oredr, offsset
  57.       $criteria -> setProperty('limit'$limit);
  58.       //carrega os objetos
  59.       $obj $rep_pessoa -> load($criteria);
  60.       //limpa a datagrid
  61.       $this -> datagrid -> clear();
  62.       if ($obj) {
  63.         //percorre a coleção de Active Records
  64.         foreach ($obj as $object) {
  65.           //adiciona o objeto na datagrid
  66.           $this -> datagrid -> addItem($object);
  67.         }
  68.       }
  69.       //conta o total de registros
  70.       $criteria -> resetProperties();
  71.       $count $rep_pessoa -> count($criteria);
  72.       $this -> pageNavigation -> setCount($count); // count of records
  73.       $this -> pageNavigation -> setProperties($param); // order, page
  74.       $this -> pageNavigation -> setLimit($limit);// limit
  75.       // close the transaction
  76.       TTransaction::close();
  77.       $this -> loaded true;
  78.     } catch(Exception $e) {
  79.         new  TMessage('error',$e->getMessage());
  80.         TTransaction::rollback();
  81.     }
  82.   }
  83.   /**
  84.   * Terminar adaptação
  85.    * Open an input dialog
  86.    */
  87.   public function onInputDialog($param) {
  88.     $nome = new TEntry('nome');
  89.     $cpf = new TEntry('cpf');
  90.     $name -> setValue($param['key']);
  91.     $form = new TForm('input_form');
  92.     $form -> style 'padding:20px';
  93.     $table = new TTable;
  94.     $table -> addRowSet(new TLabel('Nome: '), $name);
  95.     $table -> addRowSet($lbl = new TLabel('CPF: '), $cpf);
  96.     $lbl -> setFontColor('red');
  97.     $form -> setFields(array($nome$cpf));
  98.     $form -> add($table);
  99.     // show the input dialog
  100.     $action = new TAction( array($this'onConfirm'));
  101.     $action -> setParameter('stay-open'1);
  102.     new TInputDialog('Input dialog'$form$action'Confirm');
  103.   }
  104.   /**
  105.    * Show the input dialog data 
  106.    */
  107.   public static function onConfirm($param) {
  108.     if (isset($param['amount']) AND $param['amount'])// validate required field
  109.     {
  110.       new TMessage('info'"Name: " $param['name'] . ';Amount: ' $param['amount'], new TAction( array('ClienteFisicoForm''onReload')));
  111.     } else {
  112.       new TMessage('error''Amount is required');
  113.     }
  114.   }
  115.   /**
  116.    * shows the page
  117.    */
  118.   function show() {
  119.     if ($this->loaded) {
  120.       $this->onReload();
  121.     }
  122.     parent::show();
  123.   }
  124. }
  125. ?>



Porém não carrega nada e também não da erro algum /

Alguém poderia me dar uma luz.

Obs.: estou utilizando banco de dados Mysql, Adianti studio v.40


No aguardo,

desde já obrigado.

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


AC

Na base de dados tem algum registro na tabela pessoa?

Porque pessoa física não é um atributo de pessoa (uma coluna dentro da tabela pessoa)?

Em pessoa endereço está faltando uma referência a endereço, não (IdEndereço)?
NR

A função onReload não está sendo executada. Imagino que o problema esteja na função show. O "if($this->loaded)" sempre retorna false e com isso a função onReload não é chamada. É necessário alterar o if, adicionando a negação (!):
  1. <?php
  2. function show()
  3. {
  4.     // chamar a onReload quando loaded = false, pois quem define loaded = true é justamente a função onReload
  5.     if (! $this->loaded)
  6.     {
  7.          $this->onReload();
  8.     }
  9.     parent::show();
  10. }
  11. ?>

Outra coisa, sugiro alterar o nome da classe para ClienteFisicoList por tratar-se de uma grid e não de um formulário. Além disso, como essa classe é simples, não há a necessidade de reeescrever as funções onReload e show, basta herdar a classe padrão TStandardList.
RB

Alexandre,

Sim a tabela pessoa esta populada,

Quanto ao IdEndereco também esta adicionado.

*******************************************************

Nataniel,

Fiz a alteração conforme mencionou, porém ainda não carrega os dados das tabelas relacionadas, Só esta carregando informações da tabela pessoa.
NR

Acho que há alguma confusão nos relacionamentos. Você está usando o model Pessoa como repositório para carregamento da grid, mas não há nenhum relacionamento nesse model.
RB

Então,

Sei que o objetivo aqui não é ensinar a programar, porém realmente não estou conseguindo entender,

Tem como dar uma luz de como fazer para que funcione.

NR

Rubens, nesse caso acho que o mais simples seria criar uma view no banco de dados trazendo as informações de todas tabelas em uma consulta. Depois você cria um model para essa view e utiliza esse novo model como repositório da função onReload.
RB

Nataniel,

Eu comprei o livre na esperança de haveria um exemplo completo de como fazer, porém .... tudo em pedaço.....

Não tem um modelo completo .... decepção.

Mas valeu pela atenção vou continuar tentando.....

obrigado


RB

Ola, a todos,

Então eu ainda não consegui carregar os dados de tabelas relacionadas como citado no post , será que alguém poderia me ajudara identificar o problema.
RB

Ola a todos,

Pessoa venho aqui mais uma vez pedir ajuda de vocês, pois não estou conseguindo carregar de tabela relacionadas em uma datagrid.


segue classe com os relacionamentos.

  1. <?php
  2. /**
  3.  * Pessoa Active Record
  4.  * @author  <your-name-here>
  5.  */
  6. class ClienteFisico extends TRecord
  7. {
  8.     const TABLENAME 'Pessoa';
  9.     const PRIMARYKEY'IdPessoa';
  10.     const IDPOLICY =  'max'// {max, serial}
  11.     
  12.     private $cliente;
  13.     private $pessoa_fisica;
  14.     private $pessoa_endereco;
  15.     /**
  16.      * Constructor method
  17.      */
  18.     public function __construct($id NULL$callObjectLoad TRUE)
  19.     {
  20.         parent::__construct($id$callObjectLoad);
  21.         parent::addAttribute('Nome');
  22.         parent::addAttribute('DataCadastro');
  23.         parent::addAttribute('Atualizacao');
  24.         parent::addAttribute('IdTipoVinculo');
  25.         parent::addAttribute('IdOrganizacao');
  26.         parent::addAttribute('Ativo');
  27.     }
  28.     /**
  29.      * Method addCliente
  30.      * Add a Cliente to the Pessoa
  31.      * @param $object Instance of Cliente
  32.      */
  33.     public function addCliente(Cliente $object)
  34.     {
  35.         $this->cliente[] = $object;
  36.     }
  37.     
  38.     /**
  39.      * Method getClientes
  40.      * Return the Pessoa' Cliente's
  41.      * @return Collection of Cliente
  42.      */
  43.     public function getClientes()
  44.     {
  45.         return $this->cliente;
  46.     }
  47.     
  48.     /**
  49.      * Method addPessoaFisica
  50.      * Add a PessoaFisica to the Pessoa
  51.      * @param $object Instance of PessoaFisica
  52.      */
  53.     public function addPessoaFisica(PessoaFisica $object)
  54.     {
  55.         $this->pessoa_fisica[] = $object;
  56.     }
  57.     
  58.     /**
  59.      * Method getPessoaFisicas
  60.      * Return the Pessoa' PessoaFisica's
  61.      * @return Collection of PessoaFisica
  62.      */
  63.     public function getPessoaFisicas()
  64.     {
  65.         return $this->pessoa_fisica;
  66.     }
  67.     
  68.     /**
  69.      * Method addPessoaEndereco
  70.      * Add a PessoaEndereco to the Pessoa
  71.      * @param $object Instance of PessoaEndereco
  72.      */
  73.     public function addPessoaEndereco(PessoaEndereco $object)
  74.     {
  75.         $this->pessoa_endereco[] = $object;
  76.     }
  77.     
  78.     /**
  79.      * Method getPessoaEnderecos
  80.      * Return the Pessoa' PessoaEndereco's
  81.      * @return Collection of PessoaEndereco
  82.      */
  83.     public function getPessoaEndereco()
  84.     {
  85.         return $this->pessoa_endereco;
  86.     }
  87.     /**
  88.      * Reset aggregates
  89.      */
  90.     public function clearParts()
  91.     {
  92.         $this->cliente = array();
  93.         $this->pessoa_fisica = array();
  94.         $this->pessoa_endereco = array();
  95.     }
  96.     /**
  97.      * Load the object and its aggregates
  98.      * @param $id object ID
  99.      */
  100.     public function load($id)
  101.     {
  102.         $this->cliente parent::loadComposite('Cliente''IdPessoa'$id);
  103.         // load the object itself
  104.         return parent::load($id);
  105.     }
  106.     /**
  107.      * Store the object and its aggregates
  108.      */
  109.     public function store()
  110.     {
  111.         // store the object itself
  112.         parent::store();
  113.     
  114.         parent::saveComposite('Cliente''IdPessoa'$this->id$this->cliente);
  115.         parent::saveComposite('PessoaFisica''IdPessoa'$this->id$this->pessoa_fisica);
  116.         parent::saveAggregate('PessoaEndereco''IdPessoa''IdPessoa'$this->id$this->pessoa_endereco);
  117.     }
  118.     /**
  119.      * Delete the object and its aggregates
  120.      * @param $id object ID
  121.      */
  122.     public function delete($id NULL)
  123.     {
  124.         $id = isset($id) ? $id $this->id;
  125.         parent::deleteComposite('Cliente''IdPessoa'$id);
  126.         parent::deleteComposite('PessoaFisica''IdPessoa'$id);
  127.         parent::deleteComposite('PessoaPessoaEndereco''IdPessoa'$id);
  128.     
  129.         // delete the object itself
  130.         parent::delete($id);
  131.     }
  132.     
  133. }
  134. ?>


Classe que monta o datagrid.

  1. <?php
  2. class ClienteFisicoForm extends TPage {
  3.   private $datagrid;
  4.   private $form;
  5.   private $table_contato;
  6.   // listing
  7.   private $pageNavigation;
  8.   private $loaded;
  9.   public function __construct() {
  10.     parent::__construct();
  11.     // creates one datagrid
  12.     $this->datagrid = new TQuickGrid;
  13.     $this->datagrid->style 'width: 100%';
  14.     $this->datagrid->makeScrollable();
  15.     // add the columns
  16.     $this->datagrid->addQuickColumn('Código''IdPessoa''colspan=2''left');
  17.     $this->datagrid->addQuickColumn('Nome''Nome''left');
  18.     $this->datagrid->addQuickColumn('Nasc.''DataNascimento''left');
  19.     $this->datagrid->addQuickColumn('Estado Cívil''IdEstadoCivil''left');
  20.     $this->datagrid->addQuickColumn('Sexo''Sexo''left');
  21.     $this->datagrid->addQuickColumn('CPF''CPF''left');
  22.     $this->datagrid->addQuickColumn('RG / CNH''RG''left');
  23.     $this->datagrid->addQuickColumn('Telefone / Celular''Telefone''left');
  24.     $this->datagrid->addQuickColumn('E-mail''Email''left');
  25.     $this->datagrid->addQuickColumn('Site''Site');
  26.     $this->datagrid->addQuickColumn('Cep''Cep''left');
  27.     $this->datagrid->addQuickColumn('Logradouro''Logradouro');
  28.     $this->datagrid->addQuickColumn('Número''Numero');
  29.     $this->datagrid->addQuickColumn('Bairro''Bairro');
  30.     $this->datagrid->addQuickColumn('UF''Estado');
  31.     $this->datagrid->addQuickColumn('Cidade''Cidade');
  32.     $this->datagrid->addQuickColumn('Tipo Endereço''TipoEnderecoId');
  33.     $this->datagrid->addQuickColumn('Complemento''Complemento');
  34.     // add the actions
  35.     $this->datagrid->addQuickAction('Input', new TDataGridAction(array($this'onInputDialog')), 'Nome''fa:external-link');
  36.     // creates the datagrid model
  37.     $this->datagrid->createModel();
  38.     // wrap the page content using vertical box
  39.     $vbox = new TVBox;
  40.     $vbox->add(new TXMLBreadCrumb('menu.xml'__CLASS__));
  41.     $vbox->add($this->datagrid);
  42.     parent::add($vbox);
  43.   }
  44.   /**
  45.    * Load the data into the datagrid
  46.    */
  47.   function onReload($param null) {
  48.     try {
  49.       TTransaction::open('sgvo'); //abre a transação      
  50.       //cria o repositorio Pessoa
  51.       $rep_pessoa = new TRepository('ClienteFisico');
  52.       $limit 15;
  53.       //cria o critério de seleção
  54.       $criteria = new TCriteria;
  55.       $criteria->setProperties($param);
  56.       //order, offsset
  57.       $criteria->setProperty('limit'$limit);
  58.       //carrega os objetos
  59.       $obj $rep_pessoa->load($criteria);
  60.       //limpa a datagrid
  61.       $this->datagrid->clear();
  62.       if ($obj) {
  63.         //percorre a coleção de Active Records
  64.         foreach ($obj as $object) {
  65.           //adiciona o objeto na datagrid
  66.           $this->datagrid->addItem($object);
  67.         }
  68.       }
  69.       //conta o total de registros
  70.       $criteria->resetProperties();
  71.       $count $rep_pessoa->count($criteria);
  72.       //$this -> pageNavigation -> setCount($count); // count of records
  73.       //$this -> pageNavigation -> setProperties($param); // order, page
  74.       //$this -> pageNavigation -> setLimit($limit);// limit
  75.       // close the transaction
  76.       TTransaction::close();
  77.       $this->loaded true;
  78.     } catch (Exception $e) {
  79.       new TMessage('error'$e->getMessage());
  80.       TTransaction::rollback();
  81.     }
  82.   }
  83.   /**
  84.    * Open an input dialog
  85.    */
  86.   public function onInputDialog($param) {
  87.     $this->form = new BootstrapFormBuilder('form_cliente_fisico');
  88.     //$this->form->setFormTitle('Cliente');
  89.     //cria os campos : parametros(nome,banco,modelo,chave,valor)
  90.     $code = new TEntry('IdPessoa');
  91.     $nome = new TEntry('Nome');
  92.     $cpf = new TEntry('CPF');
  93.     $rg = new TEntry('RG');
  94.     $data_nasc = new TDate('data_nasc');
  95.     $genero = new TRadioGroup('genero');
  96.     $estado_civil = new TDBCombo('IdEstadoCivil''sgvo''EstadoCivil''IdEstadoCivil''EstadoCivil');
  97.     $cnh = new TEntry('CNH');
  98.     $tipo_endereco = new TDBCombo('TipoEndereco''sgvo''TipoEndereco''IdTipoEndereco''Descricao');
  99.     //adicona combo 
  100.     $genero->addItems([ '1' => 'M''2' => 'F']);
  101.     $genero->setLayout('horizontal');
  102.     $nome->setValue($param['key']);
  103.     //define propriedades 
  104.     $code->setEditable(FALSE);
  105.     $code->setSize(100);
  106.     $data_nasc->setSize(100);
  107.     $rg->setSize(150);
  108.     $this->form->style='padding:0';
  109.     
  110.     $this->form->appendPage('Dados Pessoais');
  111.     $this->form->addFields([new TLabel('Código')],[$code]);
  112.     $this->form->addFields([new TLabel('Nome')],[$nome],[new TLabel('Sexo')],[$genero]);
  113.     $this->form->addFields([new TLabel('CPF')], [$cpf], [new TLabel('RG')], [$rg]);
  114.     $this->form->addFields([new TLabel('Data Nasc')],[$data_nasc]);
  115.     $this->form->addFields([new TLabel('Estado Cívil')],[$estado_civil]);
  116.    // $this->form->addFields([new TLabel('CNH')], [$cnh]);
  117.     
  118.     //$this->form->addFields([new TLabel('Tipo de Endereço')],[$tipo_endereco]);
  119.         
  120.     $this->form->appendPage('Contato');
  121.     $this->table_contacts = new TTable;
  122.     $this->table_contacts->width '100%';
  123.     $this->table_contacts->addSection('thead');
  124.     $this->table_contacts->addRowSet( new TLabel('Type''#8082C3',10'b'), new TLabel('Value''#8082C3',10'b'));
  125.     $this->form->addContent( [ new TLabel('Contato') ],[ $this->table_contacts ] );
  126.     
  127.     $table_data = new TTable;
  128.     $table_contato = new TTable;
  129.     
  130.     $action = new TAction(array($this'onSave'));
  131.     $this->form->addAction('Save', new TAction(array($this'onSave')), 'fa:save green');
  132.     $this->form->addAction('Clear', new TAction(array($this'onClear')), 'fa:eraser red');
  133.     $this->form->addAction('List', new TAction(array('ClienteFisicoForm''onReload')), 'fa:table blue');
  134.     
  135.     
  136.     new TInputDialog('Adiciona Cliente'$this->form$action'Sair');
  137.     // show the input dialog
  138.     $action->setParameter('stay-open'1);
  139.   }
  140.   /**
  141.    * Show the input dialog data
  142.    */
  143.   public static function onConfirm($param) {
  144.     if (isset($param['CPF']) AND $param['CPF']) {// validate required field
  145.       new TMessage('info'"Nome: " $param['Nome'] . ';CPF: ' $param['CPF'],
  146.           new TAction(array('ClienteFisicoForm''onReload')));
  147.     } else {
  148.       new TMessage('error''CPF is required');
  149.     }
  150.   }
  151.   /**
  152.    * shows the page
  153.    */
  154.   public function show() {
  155.     if (!$this->loaded) {
  156.       $this->onReload();
  157.     }
  158.     parent::show();
  159.   }
  160.   public static function onSave($param) {
  161.     try {
  162.       // open a transaction with database 'samples'
  163.       TTransaction::open('sgvo');
  164.     } catch (Exception $e) {
  165.       
  166.     }
  167.   }
  168.   
  169.   function onEdit($param)
  170.     {
  171.     
  172.     }
  173.     
  174.   public function addContactRow($item)
  175.     {
  176.     
  177.     }
  178.      public function onClear($param)
  179.     {
  180.        
  181.      }
  182.   }
  183. ?>



Alguém pode me ajudar a identificar o problema ?
NR

Rubens, vou passar um exemplo básico de relacionamento entre pessoa e cidade, depois você tenta adaptar à sua necessidade:
  1. <?php
  2. Estrutura tabela pessoa(id intnome textcidade_id int)
  3. Estrutura tabela cidade(id intnome textuf char(2));
  4. // model Pessoa
  5. protected $cidade;
  6. ...
  7. // function construct
  8. ...
  9. // essa é a função responsável pelo relacionamento
  10. public function get_cidade()
  11. {
  12.      if (empty($this->cidade))
  13.             $this->cidade = new Cidade($this->cidade_id);
  14.     
  15.      // returns the associated object
  16.      return $this->cidade
  17. }
  18. // GRID
  19. // esta linha vai exibir o nome da cidade na grid, pois há uma função get_cidade no model de Pessoa
  20. $this->datagrid->addQuickColumn('Cidade''cidade->nome',  'left');
  21. // esta linha vai exibir o uf da cidade
  22. $this->datagrid->addQuickColumn('UF''cidade->uf',  'left');
  23. O nome da função deveobrigatoriamenteseguir esse padrão 'get_' nome do atributo.
  24. ?>
RB

Nataniel,

Então, fiz as alterações conforme mencionou, porém nada....

//get pessoa_fisica
public function get_pessoa()
{
if (empty($this->pessoa))
$this->pessoa = new Pessoa($this->IdPessoa);

// returns the associated object
return $this->pessoa;
}

agora da a seguinte mensagem : Tentaiva de acesso a uma propriedade inexisten(pessoa->DataNascimeto).

Não consegui identificar o erro, ta virando uma saga.......
RB

Ola a todos,

Na tentativa de resolver o problema citado acima, alterei o banco e geri novas classes pelo adianti pro, porém sem sucesso.

Alguém pode me ajudar /

Segue classe geradas pelo adianti.

  1. <?php
  2. /**
  3.  * Pessoa Active Record
  4.  * @author  <your-name-here>
  5.  */
  6. class Pessoa extends TRecord
  7. {
  8.     const TABLENAME 'Pessoa';
  9.     const PRIMARYKEY'id';
  10.     const IDPOLICY =  'max'// {max, serial}
  11.     
  12.     
  13.     private $pessoa_enderecos;
  14.     private $pessoa_fisicas;
  15.     private $contatos;
  16.     /**
  17.      * Constructor method
  18.      */
  19.     public function __construct($id NULL$callObjectLoad TRUE)
  20.     {
  21.         parent::__construct($id$callObjectLoad);
  22.         parent::addAttribute('nome');
  23.         parent::addAttribute('criacao');
  24.         parent::addAttribute('atualizacao');
  25.         parent::addAttribute('tipovinculo_Id');
  26.         parent::addAttribute('organizacao_Id');
  27.         parent::addAttribute('ativo');
  28.     }
  29.     
  30.     /**
  31.      * Method addPessoaEndereco
  32.      * Add a PessoaEndereco to the Pessoa
  33.      * @param $object Instance of PessoaEndereco
  34.      */
  35.     public function addPessoaEndereco(PessoaEndereco $object)
  36.     {
  37.         $this->pessoa_enderecos[] = $object;
  38.     }
  39.     
  40.     /**
  41.      * Method getPessoaEnderecos
  42.      * Return the Pessoa' PessoaEndereco's
  43.      * @return Collection of PessoaEndereco
  44.      */
  45.     public function getPessoaEnderecos()
  46.     {
  47.         return $this->pessoa_enderecos;
  48.     }
  49.     
  50.     /**
  51.      * Method addPessoaFisica
  52.      * Add a PessoaFisica to the Pessoa
  53.      * @param $object Instance of PessoaFisica
  54.      */
  55.     public function addPessoaFisica(PessoaFisica $object)
  56.     {
  57.         $this->pessoa_fisicas[] = $object;
  58.     }
  59.     
  60.     /**
  61.      * Method getPessoaFisicas
  62.      * Return the Pessoa' PessoaFisica's
  63.      * @return Collection of PessoaFisica
  64.      */
  65.     public function getPessoaFisicas()
  66.     {
  67.         return $this->pessoa_fisicas;
  68.     }
  69.     
  70.     /**
  71.      * Method addPessoaJuridica
  72.      * Add a PessoaJuridica to the Pessoa
  73.      * @param $object Instance of PessoaJuridica
  74.    
  75.     
  76.     /**
  77.      * Method getPessoaJuridicas
  78.      * Return the Pessoa' PessoaJuridica's
  79.      * @return Collection of PessoaJuridica
  80.      */
  81.        
  82.     /**
  83.      * Method addContato
  84.      * Add a Contato to the Pessoa
  85.      * @param $object Instance of Contato
  86.      */
  87.     public function addContato(Contato $object)
  88.     {
  89.         $this->contatos[] = $object;
  90.     }
  91.     
  92.     /**
  93.      * Method getContatos
  94.      * Return the Pessoa' Contato's
  95.      * @return Collection of Contato
  96.      */
  97.     public function getContatos()
  98.     {
  99.         return $this->contatos;
  100.     }
  101.     /**
  102.      * Reset aggregates
  103.      */
  104.     public function clearParts()
  105.     {
  106.         $this->pessoa_enderecos = array();
  107.         $this->pessoa_fisicas = array();
  108.         $this->contatos = array();
  109.     }
  110.     /**
  111.      * Load the object and its aggregates
  112.      * @param $id object ID
  113.      */
  114.     public function load($id)
  115.     {
  116.         $this->pessoa_enderecos parent::loadAggregate('Pessoa','PessoaEndereco','id','pessoa_id',$id);
  117.         $this->pessoa_fisicas parent::loadAggregate('Pessoa','PessoaFisica','id','pessoa_id',$id);
  118.         $this->contatos parent::loadComposite('Contato','pessoa_id'$id);
  119.     
  120.         // load the object itself
  121.         return parent::load($id);
  122.     }
  123.     /**
  124.      * Store the object and its aggregates
  125.      */
  126.     public function store()
  127.     {
  128.         // store the object itself
  129.         parent::store();
  130.     
  131.         parent::saveAggregate('PessoaEndereco','id','pessoa_id',$this->id,$this->pessoa_enderecos);
  132.         parent::saveAggregate('PessoaFisica','id','pessoa_id',$this->id,$this->pessoa_fisicas);
  133.         parent::saveComposite('Contato','pessoa_id',$this->id$this->contatos);
  134.     }
  135.     /**
  136.      * Delete the object and its aggregates
  137.      * @param $id object ID
  138.      */
  139.     public function delete($id NULL)
  140.     {
  141.         $id = isset($id) ? $id $this->id;
  142.         parent::deleteComposite('PessoaEndereco','pessoa_id'$id);
  143.         parent::deleteComposite('PessoaFisica','pessoa_id'$id);
  144.         parent::deleteComposite('Contato','pessoa_id'$id);
  145.     
  146.         // delete the object itself
  147.         parent::delete($id);
  148.     }
  149. }
  150. ?>


pagina onde estou tentando carregar a grid.

  1. <?php
  2. class ClienteFisicoForm extends TPage {
  3.   private $datagrid;
  4.   private $form;
  5.   private $table_contato;
  6.   // listing
  7.   private $pageNavigation;
  8.   private $loaded;
  9.     
  10.   public function __construct() {
  11.     parent::__construct();  
  12.     
  13.     // creates one datagrid
  14.     $this->datagrid = new TQuickGrid;
  15.     $this->datagrid->style 'width: 100%';
  16.     $this->datagrid->makeScrollable();
  17.     // add the columns
  18.     $this->datagrid->addQuickColumn('Código''id''colspan=2''left');
  19.     $this->datagrid->addQuickColumn('nome''nome''left');
  20.     $this->datagrid->addQuickColumn('Nascimento','pessoa_fisicas->data_nascimento''left');
  21.     $this->datagrid->addQuickColumn('Estado Cívil''descricao''left');
  22.     $this->datagrid->addQuickColumn('Sexo''sexo''left');
  23.     $this->datagrid->addQuickColumn('CPF''cpf''left');
  24.     $this->datagrid->addQuickColumn('RG''rg''left');
  25.     $this->datagrid->addQuickColumn('Telefone''telefone''left');
  26.     $this->datagrid->addQuickColumn('E-mail''email''left');
  27.     $this->datagrid->addQuickColumn('Site''site');
  28.     $this->datagrid->addQuickColumn('Cep''cep''left');
  29.     $this->datagrid->addQuickColumn('Logradouro''logradouro');
  30.     $this->datagrid->addQuickColumn('Número''numero');
  31.     $this->datagrid->addQuickColumn('Bairro''bairro');
  32.     $this->datagrid->addQuickColumn('UF''estado');
  33.     $this->datagrid->addQuickColumn('Cidade''cidade');
  34.     $this->datagrid->addQuickColumn('Tipo Endereço''descricao');
  35.     $this->datagrid->addQuickColumn('Complemento''complemento');
  36.     // add the actions
  37.     $this->datagrid->addQuickAction('Input', new TDataGridAction(array($this'onInputDialog')), 'nome''fa:external-link');
  38.     // creates the datagrid model
  39.     $this->datagrid->createModel();
  40.     // wrap the page content using vertical box
  41.     $vbox = new TVBox;
  42.     $vbox->add(new TXMLBreadCrumb('menu.xml'__CLASS__));
  43.     $vbox->add($this->datagrid);
  44.     parent::add($vbox);
  45.   }
  46.   
  47.   /**
  48.    * Load the data into the datagrid
  49.    */
  50.   function onReload($param null) {
  51.     try {
  52.       TTransaction::open('sgvo'); //abre a transação      
  53.       //cria o repositorio Pessoa
  54.       $rep_pessoa = new TRepository('Pessoa');
  55.       $limit 10;
  56.       //cria o critério de seleção
  57.       $criteria = new TCriteria;
  58.       $criteria->setProperties($param);
  59.       //order, offsset
  60.       $criteria->setProperty('limit'$limit);
  61.       //carrega os objetos
  62.       $obj $rep_pessoa->load($criteria);
  63.       //limpa a datagrid
  64.       $this->datagrid->clear();
  65.       if ($obj) {
  66.         //percorre a coleção de Active Records
  67.         foreach ($obj as $object) {
  68.           //adiciona o objeto na datagrid
  69.           $this->datagrid->addItem($object);
  70.         }
  71.       }
  72.       //conta o total de registros
  73.       //$criteria->resetProperties();
  74.       //$count = $rep_pessoa->count($criteria);
  75.       //$this -> pageNavigation -> setCount($count); // count of records
  76.      // $this -> pageNavigation -> setProperties($param); // order, page
  77.      // $this -> pageNavigation -> setLimit($limit);// limit
  78.       
  79. // close the transaction
  80.       TTransaction::close();
  81.       $this->loaded true;
  82.       
  83.     } catch (Exception $e) {
  84.       new TMessage('error'$e->getMessage());
  85.       TTransaction::rollback();
  86.     }
  87.   }
  88.   /**
  89.    * Open an input dialog
  90.    */
  91.   public function onInputDialog($param) {
  92.     $this->form = new BootstrapFormBuilder('form_cliente_fisico');
  93.     //$this->form->setFormTitle('Cliente');
  94.     //cria os campos : parametros(nome,banco,modelo,chave,valor)
  95.     $code = new TEntry('id');
  96.     $nome = new TEntry('nome');
  97.     $cpf = new TEntry('cpf');
  98.     $rg = new TEntry('rg');
  99.     $data_nasc = new TDate('data_nasc');
  100.     $genero = new TRadioGroup('genero');
  101.     $estado_civil = new TDBCombo('Estado Cívil''sgvo''EstadoCivil''id''descricao');
  102.     $cnh = new TEntry('CNH');
  103.     $tipo_endereco = new TDBCombo('TipoEndereco''sgvo''TipoEndereco''id''descricao');
  104.     //adicona combo 
  105.     $genero->addItems([ '1' => 'M''2' => 'F']);
  106.     $genero->setLayout('horizontal');
  107.     $nome->setValue($param['key']);
  108.     //define propriedades 
  109.     $code->setEditable(FALSE);
  110.     $code->setSize(100);
  111.     $data_nasc->setSize(100);
  112.     $rg->setSize(150);
  113.     $estado_civil->setSize(150);
  114.     $this->form->style='padding:0';
  115.     
  116.     $this->form->appendPage('Dados Pessoais');
  117.     $this->form->addFields([new TLabel('Código')],[$code]);
  118.     $this->form->addFields([new TLabel('Nome')],[$nome],[new TLabel('Sexo')],[$genero]);
  119.     $this->form->addFields([new TLabel('CPF')], [$cpf], [new TLabel('RG')], [$rg]);
  120.     $this->form->addFields([new TLabel('Data Nasc')],[$data_nasc],[new TLabel('Estado Cívil')],[$estado_civil]);
  121.            
  122.     $this->form->appendPage('Contato');
  123.     $this->table_contacts = new TTable;
  124.     $this->table_contacts->width '100%';
  125.     $this->table_contacts->addSection('thead');
  126.     $this->table_contacts->addRowSet( new TLabel('Type''#8082C3',10'b'), new TLabel('Value''#8082C3',10'b'));
  127.     $this->form->addContent( [ new TLabel('Contato') ],[ $this->table_contacts ] );
  128.     
  129.     $table_data = new TTable;
  130.     $table_contato = new TTable;
  131.     
  132.     $action = new TAction(array($this'onSave'));
  133.     $this->form->addAction('Save', new TAction(array($this'onSave')), 'fa:save green');
  134.     $this->form->addAction('Clear', new TAction(array($this'onClear')), 'fa:eraser red');
  135.     $this->form->addAction('List', new TAction(array('ClienteFisicoForm''onReload')), 'fa:table blue');
  136.     
  137.     
  138.     new TInputDialog('Adiciona Cliente'$this->form$action'Sair');
  139.     // show the input dialog
  140.     $action->setParameter('stay-open'1);
  141.   }
  142.   /**
  143.    * Show the input dialog data
  144.    */
  145.   public static function onConfirm($param) {
  146.     if (isset($param['cpf']) AND $param['cpf']) {// validate required field
  147.       new TMessage('info'"Nome: " $param['nome'] . ';CPF: ' $param['cpf'],
  148.           new TAction(array('ClienteFisicoForm''onReload')));
  149.     } else {
  150.       new TMessage('error''CPF is required');
  151.     }
  152.   }
  153.   /**
  154.    * shows the page
  155.    */
  156.   public function show() {
  157.     if (!$this->loaded) {
  158.       $this->onReload();
  159.     }
  160.     parent::show();
  161.   }
  162.   public static function onSave($param) {
  163.     try {
  164.       // open a transaction with database 'samples'
  165.       TTransaction::open('sgvo');
  166.     } catch (Exception $e) {
  167.       
  168.     }
  169.   }
  170.   
  171.   function onEdit($param)
  172.     {
  173.     
  174.     }
  175.     
  176.   public function addContactRow($item)
  177.     {
  178.     
  179.     }
  180.      public function onClear($param)
  181.     {
  182.        
  183.      }
  184.   }
  185. ?>


Desde já obrigado pela atenção.
NR

Rubens, acredito que o relacionamento entre pessoa e pessoa física deve ser uma associação e não uma composição ou agregação. Do jeito que está uma pessoa pode ter várias pessoas físicas vinculadas. Não sei se essa foi sua intenção mas na minha visão está incorreto.

E também, para que o relacionamento funcione na grid, você precisa ter uma função correspondente no model. Por exemplo:
  1. <?php
  2. $this->datagrid->addQuickColumn('Nascimento','pessoa_fisicas->data_nascimento''left');
  3. ?>

Você tem que criar a função get_pessoa_fisicas no model Pessoa retornando a instância do objeto relacionado, que nesse caso seria PessoaFisica.
RB

Nataniel,

Então alterei a classe conforme citou acima, porém sem sucesso.

Segue abaixo:
  1. <?php
  2. class Pessoa extends TRecord {
  3.   const TABLENAME 'Pessoa';
  4.   const PRIMARYKEY 'id';
  5.   const IDPOLICY 'max'// {max, serial}
  6.   private $pessoa_fisica;
  7.   private $contatos;
  8.   /**
  9.    * Constructor method
  10.    */
  11.   public function __construct($id NULL$callObjectLoad TRUE) {
  12.     parent::__construct($id$callObjectLoad);
  13.     parent::addAttribute('nome');
  14.     parent::addAttribute('criacao');
  15.     parent::addAttribute('atualizacao');
  16.     parent::addAttribute('tipovinculo_id');
  17.     parent::addAttribute('organizacao_id');
  18.     parent::addAttribute('ativo');
  19.   }
  20.   public function get_pessoa_fisica() {
  21.     if (empty($this->pessoa_fisica)):
  22.       $this->pessoa_fisica = new PessoaFisica($this->pessoa_id);
  23.     endif;
  24.     return $this->pessoa_fisica;
  25.   }
  26.   public function set_pessoa_fisica(Pessoa $pessoa_fisica) {
  27.     $this->pessoa_fisica $pessoa_fisica;
  28.     $this->pessoa_id $pessoa_fisica->id;
  29.   }
  30. }
  31. ?>


trecho Datagrid
  1. <?php
  2.  public function __construct() {
  3.     parent::__construct();
  4.     // creates one datagrid
  5.     $this->datagrid = new TQuickGrid;
  6.     $this->datagrid->style 'width: 100%';
  7.     $this->datagrid->makeScrollable();
  8.     // add the columns
  9.     $this->datagrid->addQuickColumn('Código''id''colspan=2''left');
  10.     $this->datagrid->addQuickColumn('nome''nome''left');
  11.     //$this->datagrid->addQuickColumn('Nascimento','pessoa->data_nascimento', 'left');
  12.     $this->datagrid->addQuickColumn('Nascimento','pessoa->pessoa_fisica->data_nascimento''left');
  13.   outros campos ....
  14. ?>



NR

Na função get_pessoa_fisica você está utilizando um atributo inexistente. O $this->pessoa_id não existe nessa tabela. Imagino que seja uma coluna da tabela pessoa_fisica. Nesse caso você vai ter que fazer outro tipo de consulta:
  1. <?php
  2. public function get_pessoa_fisica() {
  3.     if (empty($this->pessoa_fisica))
  4.     {
  5.         $pessoa_fisica PessoaFisica::where('pessoa_id','=',$this->id)->load();
  6.         $this->pessoa_fisica $pessoa_fisica[0];
  7.     }
  8.     return $this->pessoa_fisica;
  9. }
  10. ?>


E na grid deveria ser:
  1. <?php
  2. //$this->datagrid->addQuickColumn('Nascimento','pessoa->pessoa_fisica->data_nascimento', 'left');
  3. $this->datagrid->addQuickColumn('Nascimento','pessoa_fisica->data_nascimento''left');
  4. ?>
RB

Nataniel , bom dia,

Então, sei qual é o problema, mas simplesmente só carrega os dados da tabela principal ( Pessoa)

Segue todo o código que gerei novamente pelo assistente.

Model Pessoa.

  1. <?php
  2. /**
  3.  * Pessoa Active Record
  4.  * @author  <your-name-here>
  5.  */
  6. class Pessoa extends TRecord
  7. {
  8.     const TABLENAME 'Pessoa';
  9.     const PRIMARYKEY'id';
  10.     const IDPOLICY =  'max'// {max, serial}
  11.     
  12.     
  13.     private $pessoa_fisica;
  14.     /**
  15.      * Constructor method
  16.      */
  17.     public function __construct($id NULL$callObjectLoad TRUE)
  18.     {
  19.         parent::__construct($id$callObjectLoad);
  20.         parent::addAttribute('nome');
  21.         parent::addAttribute('criacao');
  22.         parent::addAttribute('atualizacao');
  23.         parent::addAttribute('tipovinculo_id');
  24.         parent::addAttribute('organizacao_id');
  25.         parent::addAttribute('ativo');
  26.     }
  27.     
  28.     /**
  29.      * Method set_pessoa_fisica
  30.      * Sample of usage: $pessoa->pessoa_fisica = $object;
  31.      * @param $object Instance of PessoaFisica
  32.      */
  33.     public function set_pessoa_fisica(PessoaFisica $object)
  34.     {
  35.         $this->pessoa_fisica $object;
  36.         $this->pessoa_fisica_id $object->id;
  37.     }
  38.     
  39.     /**
  40.      * Method get_pessoa_fisica
  41.      * Sample of usage: $pessoa->pessoa_fisica->attribute;
  42.      * @returns PessoaFisica instance
  43.      */
  44.     public function get_pessoa_fisica()
  45.     {
  46.         // loads the associated object
  47.         if (empty($this->pessoa_fisica))
  48.             $this->pessoa_fisica = new PessoaFisica($this->pessoa_id);
  49.             
  50.         //trecho alteração sugerida e da error_get_last
  51.         
  52.         
  53.         /*
  54.           if (empty($this->pessoa_fisica))
  55.             {
  56.                 $pessoa_fisica = PessoaFisica::where('pessoa_id','=',$this->id)->load();
  57.                 $this->pessoa_fisica = $pessoa_fisica[0];
  58.             }
  59.             return $this->pessoa_fisica;
  60.         */
  61.             
  62.     
  63.         // returns the associated object
  64.         return $this->pessoa_fisica;
  65.     } 
  66. }
  67. ?>


PessoaFisica
  1. <?php
  2. /**
  3.  * Pessoafisica Active Record
  4.  * @author  <your-name-here>
  5.  */
  6. class PessoaFisica extends TRecord {
  7.   const TABLENAME 'PessoaFisica';
  8.   const PRIMARYKEY 'id';
  9.   const IDPOLICY 'max'// {max, serial}
  10.   /**
  11.    * Constructor method
  12.    */
  13.   public function __construct($id NULL$callObjectLoad TRUE) {
  14.     parent::__construct($id$callObjectLoad);
  15.     parent::addAttribute('pessoa_id');
  16.     parent::addAttribute('cpf');
  17.     parent::addAttribute('rg');
  18.     parent::addAttribute('sexo');
  19.     parent::addAttribute('data_nascimento');
  20.     parent::addAttribute('estado_civil_id');
  21.     parent::addAttribute('cnh');
  22.     parent::addAttribute('ctps');
  23.     parent::addAttribute('criacao');
  24.     parent::addAttribute('atualizacao');
  25.   }
  26. }
  27. ?>


Trecho alterado data grid

  1. <?php
  2. public function __construct() {
  3.     parent::__construct();
  4.     // creates one datagrid
  5.     $this->datagrid = new TQuickGrid;
  6.     $this->datagrid->style 'width: 100%';
  7.     $this->datagrid->makeScrollable();
  8.     // add the columns
  9.     $this->datagrid->addQuickColumn('Código''id''colspan=2''left');
  10.     $this->datagrid->addQuickColumn('nome''nome''left');
  11.     $this->datagrid->addQuickColumn('Nascimento','pessoa_fisica->data_nascimento''left');
  12.   
  13.     outros campos .....
  14. ?>


Não funcionou ...