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. private $pessoa;
  12. /**
  13. * Constructor method
  14. */
  15. public function __construct($id = NULL, $callObjectLoad = TRUE)
  16. {
  17. parent::__construct($id, $callObjectLoad);
  18. parent::addAttribute('IdPessoa');
  19. parent::addAttribute('CPF');
  20. }
  21. }
  22. ?>


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. * Constructor method
  13. */
  14. public function __construct($id = NULL, $callObjectLoad = TRUE)
  15. {
  16. parent::__construct($id, $callObjectLoad);
  17. parent::addAttribute('Id');
  18. parent::addAttribute('IdPessoa');
  19. }
  20. }
  21. 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. * Constructor method
  13. */
  14. public function __construct($id = NULL, $callObjectLoad = TRUE)
  15. {
  16. parent::__construct($id, $callObjectLoad);
  17. parent::addAttribute('Logradouro');
  18. parent::addAttribute('Bairro');
  19. parent::addAttribute('Cep');
  20. parent::addAttribute('Cidade');
  21. parent::addAttribute('Estado');
  22. parent::addAttribute('Pais');
  23. parent::addAttribute('Latitude');
  24. parent::addAttribute('Longitude');
  25. parent::addAttribute('CodigoIbge');
  26. parent::addAttribute('Gia');
  27. parent::addAttribute('Criacao');
  28. parent::addAttribute('Atualizacao');
  29. }
  30. }
  31. ?>



Classe que Carrega a datagrid

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



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.

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 (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. private $cliente;
  12. private $pessoa_fisica;
  13. private $pessoa_endereco;
  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('DataCadastro');
  22. parent::addAttribute('Atualizacao');
  23. parent::addAttribute('IdTipoVinculo');
  24. parent::addAttribute('IdOrganizacao');
  25. parent::addAttribute('Ativo');
  26. }
  27. /**
  28. * Method addCliente
  29. * Add a Cliente to the Pessoa
  30. * @param $object Instance of Cliente
  31. */
  32. public function addCliente(Cliente $object)
  33. {
  34. $this->cliente[] = $object;
  35. }
  36. /**
  37. * Method getClientes
  38. * Return the Pessoa' Cliente's
  39. * @return Collection of Cliente
  40. */
  41. public function getClientes()
  42. {
  43. return $this->cliente;
  44. }
  45. /**
  46. * Method addPessoaFisica
  47. * Add a PessoaFisica to the Pessoa
  48. * @param $object Instance of PessoaFisica
  49. */
  50. public function addPessoaFisica(PessoaFisica $object)
  51. {
  52. $this->pessoa_fisica[] = $object;
  53. }
  54. /**
  55. * Method getPessoaFisicas
  56. * Return the Pessoa' PessoaFisica's
  57. * @return Collection of PessoaFisica
  58. */
  59. public function getPessoaFisicas()
  60. {
  61. return $this->pessoa_fisica;
  62. }
  63. /**
  64. * Method addPessoaEndereco
  65. * Add a PessoaEndereco to the Pessoa
  66. * @param $object Instance of PessoaEndereco
  67. */
  68. public function addPessoaEndereco(PessoaEndereco $object)
  69. {
  70. $this->pessoa_endereco[] = $object;
  71. }
  72. /**
  73. * Method getPessoaEnderecos
  74. * Return the Pessoa' PessoaEndereco's
  75. * @return Collection of PessoaEndereco
  76. */
  77. public function getPessoaEndereco()
  78. {
  79. return $this->pessoa_endereco;
  80. }
  81. /**
  82. * Reset aggregates
  83. */
  84. public function clearParts()
  85. {
  86. $this->cliente = array();
  87. $this->pessoa_fisica = array();
  88. $this->pessoa_endereco = array();
  89. }
  90. /**
  91. * Load the object and its aggregates
  92. * @param $id object ID
  93. */
  94. public function load($id)
  95. {
  96. $this->cliente = parent::loadComposite('Cliente', 'IdPessoa', $id);
  97. // load the object itself
  98. return parent::load($id);
  99. }
  100. /**
  101. * Store the object and its aggregates
  102. */
  103. public function store()
  104. {
  105. // store the object itself
  106. parent::store();
  107. parent::saveComposite('Cliente', 'IdPessoa', $this->id, $this->cliente);
  108. parent::saveComposite('PessoaFisica', 'IdPessoa', $this->id, $this->pessoa_fisica);
  109. parent::saveAggregate('PessoaEndereco', 'IdPessoa', 'IdPessoa', $this->id, $this->pessoa_endereco);
  110. }
  111. /**
  112. * Delete the object and its aggregates
  113. * @param $id object ID
  114. */
  115. public function delete($id = NULL)
  116. {
  117. $id = isset($id) ? $id : $this->id;
  118. parent::deleteComposite('Cliente', 'IdPessoa', $id);
  119. parent::deleteComposite('PessoaFisica', 'IdPessoa', $id);
  120. parent::deleteComposite('PessoaPessoaEndereco', 'IdPessoa', $id);
  121. // delete the object itself
  122. parent::delete($id);
  123. }
  124. }
  125. ?>


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. $this->form->appendPage('Dados Pessoais');
  110. $this->form->addFields([new TLabel('Código')],[$code]);
  111. $this->form->addFields([new TLabel('Nome')],[$nome],[new TLabel('Sexo')],[$genero]);
  112. $this->form->addFields([new TLabel('CPF')], [$cpf], [new TLabel('RG')], [$rg]);
  113. $this->form->addFields([new TLabel('Data Nasc')],[$data_nasc]);
  114. $this->form->addFields([new TLabel('Estado Cívil')],[$estado_civil]);
  115. // $this->form->addFields([new TLabel('CNH')], [$cnh]);
  116. //$this->form->addFields([new TLabel('Tipo de Endereço')],[$tipo_endereco]);
  117. $this->form->appendPage('Contato');
  118. $this->table_contacts = new TTable;
  119. $this->table_contacts->width = '100%';
  120. $this->table_contacts->addSection('thead');
  121. $this->table_contacts->addRowSet( new TLabel('Type', '#8082C3',10, 'b'), new TLabel('Value', '#8082C3',10, 'b'));
  122. $this->form->addContent( [ new TLabel('Contato') ],[ $this->table_contacts ] );
  123. $table_data = new TTable;
  124. $table_contato = new TTable;
  125. $action = new TAction(array($this, 'onSave'));
  126. $this->form->addAction('Save', new TAction(array($this, 'onSave')), 'fa:save green');
  127. $this->form->addAction('Clear', new TAction(array($this, 'onClear')), 'fa:eraser red');
  128. $this->form->addAction('List', new TAction(array('ClienteFisicoForm', 'onReload')), 'fa:table blue');
  129. new TInputDialog('Adiciona Cliente', $this->form, $action, 'Sair');
  130. // show the input dialog
  131. $action->setParameter('stay-open', 1);
  132. }
  133. /**
  134. * Show the input dialog data
  135. */
  136. public static function onConfirm($param) {
  137. if (isset($param['CPF']) AND $param['CPF']) {// validate required field
  138. new TMessage('info', "Nome: " . $param['Nome'] . ';CPF: ' . $param['CPF'],
  139. new TAction(array('ClienteFisicoForm', 'onReload')));
  140. } else {
  141. new TMessage('error', 'CPF is required');
  142. }
  143. }
  144. /**
  145. * shows the page
  146. */
  147. public function show() {
  148. if (!$this->loaded) {
  149. $this->onReload();
  150. }
  151. parent::show();
  152. }
  153. public static function onSave($param) {
  154. try {
  155. // open a transaction with database 'samples'
  156. TTransaction::open('sgvo');
  157. } catch (Exception $e) {
  158. }
  159. }
  160. function onEdit($param)
  161. {
  162. }
  163. public function addContactRow($item)
  164. {
  165. }
  166. public function onClear($param)
  167. {
  168. }
  169. }
  170. ?>



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 int, nome text, cidade_id int)
  3. Estrutura tabela cidade(id int, nome text, uf 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. // returns the associated object
  15. return $this->cidade;
  16. }
  17. // GRID
  18. // esta linha vai exibir o nome da cidade na grid, pois há uma função get_cidade no model de Pessoa
  19. $this->datagrid->addQuickColumn('Cidade', 'cidade->nome', 'left');
  20. // esta linha vai exibir o uf da cidade
  21. $this->datagrid->addQuickColumn('UF', 'cidade->uf', 'left');
  22. O nome da função deve, obrigatoriamente, seguir esse padrão 'get_' + nome do atributo.
  23. ?>
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. private $pessoa_enderecos;
  12. private $pessoa_fisicas;
  13. private $contatos;
  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. * Method addPessoaEndereco
  29. * Add a PessoaEndereco to the Pessoa
  30. * @param $object Instance of PessoaEndereco
  31. */
  32. public function addPessoaEndereco(PessoaEndereco $object)
  33. {
  34. $this->pessoa_enderecos[] = $object;
  35. }
  36. /**
  37. * Method getPessoaEnderecos
  38. * Return the Pessoa' PessoaEndereco's
  39. * @return Collection of PessoaEndereco
  40. */
  41. public function getPessoaEnderecos()
  42. {
  43. return $this->pessoa_enderecos;
  44. }
  45. /**
  46. * Method addPessoaFisica
  47. * Add a PessoaFisica to the Pessoa
  48. * @param $object Instance of PessoaFisica
  49. */
  50. public function addPessoaFisica(PessoaFisica $object)
  51. {
  52. $this->pessoa_fisicas[] = $object;
  53. }
  54. /**
  55. * Method getPessoaFisicas
  56. * Return the Pessoa' PessoaFisica's
  57. * @return Collection of PessoaFisica
  58. */
  59. public function getPessoaFisicas()
  60. {
  61. return $this->pessoa_fisicas;
  62. }
  63. /**
  64. * Method addPessoaJuridica
  65. * Add a PessoaJuridica to the Pessoa
  66. * @param $object Instance of PessoaJuridica
  67. /**
  68. * Method getPessoaJuridicas
  69. * Return the Pessoa' PessoaJuridica's
  70. * @return Collection of PessoaJuridica
  71. */
  72. /**
  73. * Method addContato
  74. * Add a Contato to the Pessoa
  75. * @param $object Instance of Contato
  76. */
  77. public function addContato(Contato $object)
  78. {
  79. $this->contatos[] = $object;
  80. }
  81. /**
  82. * Method getContatos
  83. * Return the Pessoa' Contato's
  84. * @return Collection of Contato
  85. */
  86. public function getContatos()
  87. {
  88. return $this->contatos;
  89. }
  90. /**
  91. * Reset aggregates
  92. */
  93. public function clearParts()
  94. {
  95. $this->pessoa_enderecos = array();
  96. $this->pessoa_fisicas = array();
  97. $this->contatos = array();
  98. }
  99. /**
  100. * Load the object and its aggregates
  101. * @param $id object ID
  102. */
  103. public function load($id)
  104. {
  105. $this->pessoa_enderecos = parent::loadAggregate('Pessoa','PessoaEndereco','id','pessoa_id',$id);
  106. $this->pessoa_fisicas = parent::loadAggregate('Pessoa','PessoaFisica','id','pessoa_id',$id);
  107. $this->contatos = parent::loadComposite('Contato','pessoa_id', $id);
  108. // load the object itself
  109. return parent::load($id);
  110. }
  111. /**
  112. * Store the object and its aggregates
  113. */
  114. public function store()
  115. {
  116. // store the object itself
  117. parent::store();
  118. parent::saveAggregate('PessoaEndereco','id','pessoa_id',$this->id,$this->pessoa_enderecos);
  119. parent::saveAggregate('PessoaFisica','id','pessoa_id',$this->id,$this->pessoa_fisicas);
  120. parent::saveComposite('Contato','pessoa_id',$this->id, $this->contatos);
  121. }
  122. /**
  123. * Delete the object and its aggregates
  124. * @param $id object ID
  125. */
  126. public function delete($id = NULL)
  127. {
  128. $id = isset($id) ? $id : $this->id;
  129. parent::deleteComposite('PessoaEndereco','pessoa_id', $id);
  130. parent::deleteComposite('PessoaFisica','pessoa_id', $id);
  131. parent::deleteComposite('Contato','pessoa_id', $id);
  132. // delete the object itself
  133. parent::delete($id);
  134. }
  135. }
  136. ?>


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. 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', 'id', 'colspan=2', 'left');
  17. $this->datagrid->addQuickColumn('nome', 'nome', 'left');
  18. $this->datagrid->addQuickColumn('Nascimento','pessoa_fisicas->data_nascimento', 'left');
  19. $this->datagrid->addQuickColumn('Estado Cívil', 'descricao', 'left');
  20. $this->datagrid->addQuickColumn('Sexo', 'sexo', 'left');
  21. $this->datagrid->addQuickColumn('CPF', 'cpf', 'left');
  22. $this->datagrid->addQuickColumn('RG', 'rg', 'left');
  23. $this->datagrid->addQuickColumn('Telefone', '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', 'descricao');
  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('Pessoa');
  52. $limit = 10;
  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('id');
  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('Estado Cívil', 'sgvo', 'EstadoCivil', 'id', 'descricao');
  97. $cnh = new TEntry('CNH');
  98. $tipo_endereco = new TDBCombo('TipoEndereco', 'sgvo', 'TipoEndereco', 'id', '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. $estado_civil->setSize(150);
  109. $this->form->style='padding:0';
  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],[new TLabel('Estado Cívil')],[$estado_civil]);
  115. $this->form->appendPage('Contato');
  116. $this->table_contacts = new TTable;
  117. $this->table_contacts->width = '100%';
  118. $this->table_contacts->addSection('thead');
  119. $this->table_contacts->addRowSet( new TLabel('Type', '#8082C3',10, 'b'), new TLabel('Value', '#8082C3',10, 'b'));
  120. $this->form->addContent( [ new TLabel('Contato') ],[ $this->table_contacts ] );
  121. $table_data = new TTable;
  122. $table_contato = new TTable;
  123. $action = new TAction(array($this, 'onSave'));
  124. $this->form->addAction('Save', new TAction(array($this, 'onSave')), 'fa:save green');
  125. $this->form->addAction('Clear', new TAction(array($this, 'onClear')), 'fa:eraser red');
  126. $this->form->addAction('List', new TAction(array('ClienteFisicoForm', 'onReload')), 'fa:table blue');
  127. new TInputDialog('Adiciona Cliente', $this->form, $action, 'Sair');
  128. // show the input dialog
  129. $action->setParameter('stay-open', 1);
  130. }
  131. /**
  132. * Show the input dialog data
  133. */
  134. public static function onConfirm($param) {
  135. if (isset($param['cpf']) AND $param['cpf']) {// validate required field
  136. new TMessage('info', "Nome: " . $param['nome'] . ';CPF: ' . $param['cpf'],
  137. new TAction(array('ClienteFisicoForm', 'onReload')));
  138. } else {
  139. new TMessage('error', 'CPF is required');
  140. }
  141. }
  142. /**
  143. * shows the page
  144. */
  145. public function show() {
  146. if (!$this->loaded) {
  147. $this->onReload();
  148. }
  149. parent::show();
  150. }
  151. public static function onSave($param) {
  152. try {
  153. // open a transaction with database 'samples'
  154. TTransaction::open('sgvo');
  155. } catch (Exception $e) {
  156. }
  157. }
  158. function onEdit($param)
  159. {
  160. }
  161. public function addContactRow($item)
  162. {
  163. }
  164. public function onClear($param)
  165. {
  166. }
  167. }
  168. ?>


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. private $pessoa_fisica;
  12. /**
  13. * Constructor method
  14. */
  15. public function __construct($id = NULL, $callObjectLoad = TRUE)
  16. {
  17. parent::__construct($id, $callObjectLoad);
  18. parent::addAttribute('nome');
  19. parent::addAttribute('criacao');
  20. parent::addAttribute('atualizacao');
  21. parent::addAttribute('tipovinculo_id');
  22. parent::addAttribute('organizacao_id');
  23. parent::addAttribute('ativo');
  24. }
  25. /**
  26. * Method set_pessoa_fisica
  27. * Sample of usage: $pessoa->pessoa_fisica = $object;
  28. * @param $object Instance of PessoaFisica
  29. */
  30. public function set_pessoa_fisica(PessoaFisica $object)
  31. {
  32. $this->pessoa_fisica = $object;
  33. $this->pessoa_fisica_id = $object->id;
  34. }
  35. /**
  36. * Method get_pessoa_fisica
  37. * Sample of usage: $pessoa->pessoa_fisica->attribute;
  38. * @returns PessoaFisica instance
  39. */
  40. public function get_pessoa_fisica()
  41. {
  42. // loads the associated object
  43. if (empty($this->pessoa_fisica))
  44. $this->pessoa_fisica = new PessoaFisica($this->pessoa_id);
  45. //trecho alteração sugerida e da error_get_last
  46. /*
  47. if (empty($this->pessoa_fisica))
  48. {
  49. $pessoa_fisica = PessoaFisica::where('pessoa_id','=',$this->id)->load();
  50. $this->pessoa_fisica = $pessoa_fisica[0];
  51. }
  52. return $this->pessoa_fisica;
  53. */
  54. // returns the associated object
  55. return $this->pessoa_fisica;
  56. }
  57. }
  58. ?>


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. outros campos .....
  13. ?>


Não funcionou ...