Lançado Adianti Framework 7.6!
Clique aqui para saber mais
Carregar dados de tabelas relacionadas na grid e editar Senhores, estou aqui novamente com o problema de não conseguir acessar dados de tabelas relacionadas em uma grid e editar, alguém pode me ajudar a resolver este problema, pois já tentei de tudo e não consegui identificar onde estou errando. segue abaixo os dados do problema ...
RB
Carregar dados de tabelas relacionadas na grid e editar  
Senhores, estou aqui novamente com o problema de não conseguir acessar dados de tabelas relacionadas em uma grid e editar, alguém pode me ajudar a resolver este problema, pois já tentei de tudo e não consegui identificar onde estou errando.

segue abaixo os dados do problema

<?
//Estrura da tabela

// Pessoa(id,nome,data_nascimento,criacao,atualizacao)

// Cliente(id,pessoa_id,criacao,atualizacao,empresa_id)

// Fisica (id,pessoa_id,cpf,rg,cnh,genero_id,civil_id)

// PessoaEndereco(id,pessoa_id,endereco_id,numero,complemento,observacao)

// Endereco (id,cep,logradouro,cidade,uf,ibge,gia)

// Model Pessoa

class Pessoa extends TRecord {

const TABLENAME = 'Pessoa';
const PRIMARYKEY = 'id';
const IDPOLICY = 'serial'; // {max, serial}

private $contatos;
private $enderecos;
private $pessoa_endereco;
private $pessoa;

/**
* Constructor method
*/
public function __construct($id = NULL, $callObjectLoad = TRUE){
parent::__construct($id, $callObjectLoad);
parent::addAttribute('nome');
parent::addAttribute('data_nascimento');
parent::addAttribute('organizacao_id');
parent::addAttribute('criacao');
parent::addAttribute('atualizacao');
parent::addAttribute('ativo');
}


/**
* Method addContato
* Add a Contato to the Pessoa
* @param $object Instance of Contato
*/
public function addContato(Contato $object) {
$this->contatos[] = $object;
}
/**
* Method getContatos
* Return the Pessoa' Contato's
* @return Collection of Contato
*/
public function getContatos() {
return $this->contatos;
}

/**
* Method addEndereco
* Add a Endereco to the Pessoa
* @param $object Instance of Endereco
*/
public function addEndereco(Endereco $object) {
$this->enderecos[] = $object;
}

/**
* Method getEnderecos
* Return the Pessoa' Endereco's
* @return Collection of Endereco
*/
public function getEnderecos() {
return $this->enderecos;
}

/**
* Reset aggregates
*/
public function clearParts() {
$this->contatos = array();
$this->enderecos = array();
}

/**
* Load the object and its aggregates
* @param $id object ID
*/
public function load($id) {

// load the related Contato objects
$repository = new TRepository('Contato');
$criteria = new TCriteria;
$criteria->add(new TFilter('pessoa_id', '=', $id));
$this->contatos = $repository->load($criteria);

// load the related Endereco objects
$repository = new TRepository('PessoaEndereco');
$criteria = new TCriteria;
$criteria->add(new TFilter('pessoa_id', '=', $id));
$pessoa_enderecos = $repository->load($criteria);

if ($pessoa_enderecos) {
foreach ($pessoa_enderecos as $pessoa_endereco) {
$endereco = new Endereco($pessoa_endereco->endereco_id);
$this->addEndereco($endereco);
}
}

$this->pessoa_endereco = parent::loadAggregate('Endereco','PessoaEndereco','pessoa_id','endereco_id',$id);
// load the object itself
return parent::load($id);
}

/**
* Store the object and its aggregates
*/
public function store() {
// store the object itself
parent::store(); // alterar
}

/**
* Delete the object and its aggregates
* @param $id object ID
*/
public function delete($id = NULL) {
$id = isset($id) ? $id : $this->id;
// delete the related Contato objects
$repository = new TRepository('Contato');
$criteria = new TCriteria;
$criteria->add(new TFilter('pessoa_id', '=', $id));
$repository->delete($criteria);

// delete the related PessoaEndereco objects
$repository = new TRepository('PessoaEndereco');
$criteria = new TCriteria;
$criteria->add(new TFilter('pessoa_id', '=', $id));
$repository->delete($criteria);

// delete the object itself
parent::delete($id);
}

}

// Model Fisica
class Fisica extends TRecord
{
const TABLENAME = 'Fisica';
const PRIMARYKEY= 'id';
const IDPOLICY = 'serial'; // {max, serial}


private $pessoa;
private $civil;
private $contato;

/**
* Constructor method
*/
public function __construct($id = NULL, $callObjectLoad = TRUE)
{
parent::__construct($id, $callObjectLoad);
parent::addAttribute('pessoa_id');
parent::addAttribute('cpf');
parent::addAttribute('rg');
parent::addAttribute('genero_id');
parent::addAttribute('civil_id');
parent::addAttribute('cnh');
parent::addAttribute('criacao');
parent::addAttribute('atualizacao');
}

/**
* Method set_pessoa
* Sample of usage: $fisica->pessoa = $object;
* @param $object Instance of Pessoa
*/
public function set_pessoa(Pessoa $object)
{
$this->pessoa = $object;
$this->pessoa_id = $object->id;
}

/**
* Method get_pessoa
* Sample of usage: $fisica->pessoa->attribute;
* @returns Pessoa instance
*/
public function get_pessoa()
{
// loads the associated object
if (empty($this->pessoa))
$this->pessoa = new Pessoa($this->pessoa_id);

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

public function set_contato(Contato $object)
{
$this->contato = $object;
$this->contato_id = $object->id;
}

/**
* Method get_contato
* Sample of usage: $fisica->contato->attribute;
* @returns Contato instance
*/
public function get_contato()
{
// loads the associated object
if (empty($this->contato))
$this->contato = new Contato;
$this->contato->pessoa_id = $this->pessoa_id;

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

/**
* Method set_civil
* Sample of usage: $fisica->civil = $object;
* @param $object Instance of Civil
*/
public function set_civil(Civil $object)
{
$this->civil = $object;
$this->civil_id = $object->id;
}

/**
* Method get_civil
* Sample of usage: $fisica->civil->attribute;
* @returns Civil instance
*/
public function get_civil()
{
// loads the associated object
if (empty($this->civil))
$this->civil = new Civil($this->civil_id);

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

// Model Cliente
class Cliente extends TRecord
{
const TABLENAME = 'Cliente';
const PRIMARYKEY= 'id';
const IDPOLICY = 'serial'; // {max, serial}

private $pessoa;

/**
* Constructor method
*/
public function __construct($id = NULL, $callObjectLoad = TRUE)
{
parent::__construct($id, $callObjectLoad);
parent::addAttribute('pessoa_id');
parent::addAttribute('organizacao_id');
parent::addAttribute('criacao');
parent::addAttribute('atualizacao');
parent::addAttribute('ativo');
}

/**
* Method set_pessoa
* Sample of usage: $cliente->pessoa = $object;
* @param $object Instance of Pessoa
*/
public function set_pessoa(Pessoa $object)
{
$this->pessoa = $object;
$this->pessoa_id = $object->id;
}

/**
* Method get_pessoa
* Sample of usage: $cliente->pessoa->attribute;
* @returns Pessoa instance
*/
public function get_pessoa()
{
// loads the associated object
if (empty($this->pessoa))
$this->pessoa = new Pessoa($this->pessoa_id);

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

public function get_fisica()
{
$criteria = new TCriteria;
$criteria->add(new TFilter('pessoa_id', '=', $this->pessoa_id));
return Fisica::getObjects( $criteria );
}
}

//model PessoaEndereco
class PessoaEndereco extends TRecord
{
const TABLENAME = 'PessoaEndereco';
const PRIMARYKEY= 'id';
const IDPOLICY = 'serial'; // {max, serial}

private $endereco;

/**
* Constructor method
*/
public function __construct($id = NULL, $callObjectLoad = TRUE)
{
parent::__construct($id, $callObjectLoad);
parent::addAttribute('pessoa_id');
parent::addAttribute('endereco_id');
parent::addAttribute('tipoendereco_id');
parent::addAttribute('numero');
parent::addAttribute('complemento');
parent::addAttribute('criacao');
parent::addAttribute('atualizacao');
}
/**
* Method set_endereco
* Sample of usage: $pessoaendereco->endereco = $object;
* @param $object Instance of Endereco
*/
public function set_endereco(Endereco $object)
{
$this->endereco = $object;
$this->endereco_id = $object->id;
}

/**
* Method get_endereco
* Sample of usage: $pessoaendereco->endereco->attribute;
* @returns Endereco instance
*/
public function get_endereco()
{
// loads the associated object
if (empty($this->endereco))
$this->endereco = new Endereco($this->endereco_id);

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

//model endereco

class Endereco extends TRecord
{

const TABLENAME = 'Endereco';
const PRIMARYKEY = 'id';
const IDPOLICY = 'serial'; // {max, serial}

/**
* Constructor method
*/

public function __construct($id = NULL, $callObjectLoad = TRUE) {
parent::__construct($id, $callObjectLoad);
parent::addAttribute('cep');
parent::addAttribute('logradouro');
parent::addAttribute('bairro');
parent::addAttribute('cidade');
parent::addAttribute('estado');
parent::addAttribute('codigo_ibge');
parent::addAttribute('gia');
parent::addAttribute('pais');
parent::addAttribute('latitude');
parent::addAttribute('longitude');
parent::addAttribute('criacao');
parent::addAttribute('atualizacao');
}

public static function BuscaCep($Cep)
{
$Cep = preg_replace("/D/","", $Cep);
if ($Cep != "")
{
$resultado = simplexml_load_string( @file_get_contents("viacep.com.br/ws/".$Cep."/xml/"));

$erro = (string) $resultado->erro;
if ( !$erro )
{
$objects['cep'] = (string) $resultado->cep;
$objects['ibge'] = (string) $resultado->ibge;
$objects['gia'] = (string) $resultado->gia;
$objects['logradouro'] = (string) $resultado->logradouro;
$objects['complemento'] = (string) $resultado->complemento;
$objects['bairro'] = (string) $resultado->bairro;
$objects['localidade'] = (string) $resultado->localidade;
$objects['uf'] = (string) $resultado->uf;
$objects['unidade'] = (string) $resultado->unidade;

return $objects;

} else return FALSE;
} else return FALSE;
}
}


// Pagina onde quero carregar os dados
class ClienteFisicoGrid extends TPage
{
private $datagrid;
private $pageNavigation;
private $loaded;
private $form;

public function __construct(){
parent::__construct();

// creates one datagrid
$this->form = new TForm;
$this->datagrid = new TQuickGrid;
$this->datagrid->setHeight(300);
$this->datagrid->disableDefaultClick();
$this->form->add($this->datagrid);

// add the columns
$this->datagrid->addQuickColumn('#','pessoa->id','center', '3%', new TAction(array($this, 'onColumnAction')), array('column', 'pessoa->id'));
$this->datagrid->addQuickColumn('Nome','pessoa->nome', 'left', '20%', new TAction(array($this, 'onColumnAction')), array('column', 'pessoa->nome'));
$this->datagrid->addQuickColumn('Nascto.','pessoa->data_nascimento', 'left', '9%', new TAction(array($this, 'onColumnAction')), array('column', 'pessoa->data_nascimento')); //aqui não estou conseguindo acessar os dados
$this->datagrid->addQuickColumn('Estado Cívil','pessoa->fisica->civil', 'left', '5%', new TAction(array($this, 'onColumnAction')), array('column', 'pessoa->civil_id'));//aqui não estou conseguindo acessar os dados
$this->datagrid->addQuickColumn('telefone','pessoa->contato->telefone', 'left', '5%', new TAction(array($this, 'onColumnAction')), array('column', 'pessoa->contato->telefone'));//aqui não estou conseguindo acessar os dados
$this->datagrid->addQuickColumn('CPF','pessoa->fisica->cpf','left', '5%', new TAction(array($this, 'onColumnAction')), array('column', 'pessoa->fisica->cpf'));//aqui não estou conseguindo acessar os dados
$this->datagrid->addQuickColumn('RG','pessoa->fisica->rg', 'left', '5%', new TAction(array($this, 'onColumnAction')), array('column', 'pessoa->fisica->rg'));// aqui não estou conseguindo acessar os dados
$this->datagrid->addQuickColumn('Criação','pessoa->criacao','left', '10%', new TAction(array($this, 'onColumnAction')), array('column', 'criacao')); //aqui não estou conseguindo acessar os dados
$this->datagrid->addQuickColumn('Cep','pessoa->endereco->cep','left', '5%', new TAction(array($this, 'onColumnAction')), array('column', 'cep')); // aqui não estou conseguindo acessar os dados
$this->datagrid->addQuickColumn('Logradouro','pessoa->endereco->logradouro','left', '30%', new TAction(array($this, 'onColumnAction')), array('column', 'logradouro')); //aqui não estou conseguindo acessar os dados
$this->datagrid->addQuickColumn('Organizacao','pessoa->organizacao_id','left', '30%', new TAction(array($this, 'onColumnAction')), array('column', 'pessoa->organizacao_id'));

// add the actions
//$this->datagrid->addQuickAction('View', new TDataGridAction(array($this, 'onView')), 'nome', 'fa:search blue'); //aqui não estou conseguindo acessar os dados
//$this->datagrid->addQuickAction('Edit', new TDataGridAction(array('ClienteFisicoForm', 'onEdit')),'pessoa->id', 'fa:edit'); //aqui não estou conseguindo acessar os dados
//$this->datagrid->addQuickAction('Delete', new TDataGridAction(array($this, 'onDelete')), 'id', 'fa:trash red'); //aqui não estou conseguindo acessar os dados

// creates the datagrid model
$this->datagrid->createModel();

$button = new TButton('action1');
$button->setAction(new TAction(array('ClienteFisicoForm','onEdit')),'Novo');
$button->setImage('ico_edit.png');

$this->form->setFields(array($button));

// creates the page navigation
$this->pageNavigation = new TPageNavigation;
$this->pageNavigation->setAction(new TAction(array($this, 'onReload')));
$this->pageNavigation->setWidth($this->datagrid->getWidth());

// wrap the page content using vertical box
$vbox = new TVBox;
$vbox->add(new TXMLBreadCrumb('menu.xml', __CLASS__));
$vbox->add($button);
$vbox->add($this->form);
$vbox->add($this->pageNavigation);

parent::add($vbox);
}

/**
* Load the data into the datagrid
*/
function onReload($param = NULL) {
try{
//abre a transação com a base
TTransaction::open('sgvo');

//cria um repositório para manipular 'Pessoa'
$cliente = new TRepository('ClienteFisico');
$pessoa = new TRepository('Pessoa');
$limit = 10;

//cria um critério para seleção de dados
$criteria = new TCriteria;

// default order
if (empty($param['order']))
{
$param['order'] = 'pessoa_id';
$param['direction'] = 'desc';
}
$get_session = TSession::getValue('organizacion_id'); //pega id da empresa
$criteria->setProperties($param); // order, offset
$criteria->add(new TFilter('ativo', '=', 1));
$criteria->add(new TFilter('organizacao_id', '=', $get_session));
$criteria->setProperties($param);
$criteria->setProperty('limit',$limit);

$objects = $cliente->load($criteria);

$this->datagrid->clear();

if($objects)
{
$fisica = new Fisica;
$fisica->pessoa_id = $objects->pessoa_id;

foreach($objects as $object)
{
$this->datagrid->addItem($object);
}
foreach($fisica as $fisico)
{
$this->datagrid->addItem($fisico);
}
}
// reset the criteria for record count
$criteria->resetProperties();
$count= $cliente->count($criteria);

$this->pageNavigation->setCount($count); // count of records
$this->pageNavigation->setProperties($param); // order, page
$this->pageNavigation->setLimit($limit); // limit

TTransaction::close();
$this->loaded = TRUE;

}
catch (Exception $e)
{
new TMessage('error',$e->getMessage());
TTransaction::rollback();
}
}

/**
* method onColumnAction()
* Executed when the user clicks at the column title
*/
function onColumnAction($param){
// get the parameter and shows the message
$key=$param['column'];
new TMessage('info', "You clicked at the column $key");
}

/**
* method onDelete()
* Executed when the user clicks at the delete button
*/
function onDelete($param){
// get the parameter and shows the message
$code = $param['pessoa->id'];
new TMessage('error', "The register $code may not be deleted");
}

/**
* method onView()
* Executed when the user clicks at the view button
*/
function onView($param){
// get the parameter and shows the message
$name = $param['nome'];
new TMessage('info', "The name is : $name");
}

public function onInput($param){
$form = new TQuickForm('input-form');
$form->style='padding:2px';
$win = new ClienteFisicoForm;

$form->add($win);

new TInputDialog('',$form);

//new TMessage('info','O Objeto clicado é: '.$param['key']);
}

public function formataData($data,$objeto,$row){
$obj = new DateTime($data);
return $obj->format('d/m/y');
}

public function onEdit($param){
//terminar
}
/**
* shows the page
*/
function show(){
// check if the datagrid is already loaded
if (!$this->loaded){
$this->onReload( func_get_arg(0) );
}
parent::show();
}
}


?>

desde já obrigado pela atenção.

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


NR

Partindo do princípio que a datagrid está sendo populada pelo model ClienteFisico e usando como exemplo a coluna estado civil:
$this->datagrid->addQuickColumn('Estado Cívil','pessoa->fisica->civil', 'left', '5%', new TAction(array($this, 'onColumnAction')), array('column', 'pessoa->civil_id'));

Desmembrando teríamos os seguintes níveis:
1) pessoa
2) fisica
3) civil

Assim, a primeira coisa que precisa verificar é se no model ClienteFisico existe uma função chamada get_pessoa. Se existe, verificar se ela está retornando corretamente uma instância do model Pessoa.

Depois é preciso verificar se no model Pessoa existe uma função chamada get_fisica e se ela também retorna uma instância do model Fisica. No código que você passou essa função não existe.

Por último, você não pode apontar diretamente para civil, pois como existe a função get_civil no model Fisica será retornado um objeto. Você precisa definir o atributo, por exemplo:
pessoa->fisica->civil->descricao