Lançado Adianti Framework 7.6!
Clique aqui para saber mais
Mestre / Detalhe Boa tarde! Amigos! Preciso substituir o código do produto (produto_pk) pelo Nome (nome_produto). abaixo segue cód do Formulário e Models usados! Obs.: Criei o form usando o Adianti Studio! Desde já, Obrigado! class EntradaForm extends TPage { protected $form; // form protected $detail_list; /** * Page constructor */ public function __construct() ...
CN
Mestre / Detalhe  
Boa tarde!

Amigos! Preciso substituir o código do produto (produto_pk) pelo Nome (nome_produto). abaixo segue cód do Formulário e Models usados! Obs.: Criei o form usando o Adianti Studio!

Desde já, Obrigado!

class EntradaForm extends TPage
{
protected $form; // form
protected $detail_list;

/**
* Page constructor
*/
public function __construct()
{
parent::__construct();

// creates the form
$this->form = new BootstrapFormBuilder('form_Entrada');
$this->form->setFormTitle('Entrada');

// master fields
$id = new TEntry('id');
$nota_fiscal = new TEntry('nota_fiscal');

// detail fields
$detail_id = new THidden('detail_id');
$detail_produto_pk = new TDBUniqueSearch('detail_produto_pk', 'conn', 'Produtos', 'id', 'nome_produto');
$detail_marca = new TEntry('detail_marca');

$detail_produto_pk->setMinLength(0);

if (!empty($id))
{
$id->setEditable(FALSE);
}

// master fields
$this->form->addFields( [new TLabel('ID')], [$id] );
$this->form->addFields( [new TLabel('NOTA FISCAL')], [$nota_fiscal] );

// detail fields
$this->form->addContent( ['<h4>Details</h4><hr>'] );
$this->form->addFields( [$detail_id] );

$this->form->addFields( [new TLabel('PRODUTO')], [$detail_produto_pk] );
$this->form->addFields( [new TLabel('MARCA')], [$detail_marca] );

$add = TButton::create('add', [$this, 'onSaveDetail'], 'Register', 'fa:save');
$this->form->addFields( [], [$add] )->style = 'background: whitesmoke; padding: 5px; margin: 1px;';

$this->detail_list = new BootstrapDatagridWrapper(new TQuickGrid);
$this->detail_list->style = "min-width: 700px; width:100%;margin-bottom: 10px";
$this->detail_list->setId('Entrada_list');

// items

$this->detail_list->addQuickColumn('PRODUTO', 'produto_pk', 'left', 100);
$this->detail_list->addQuickColumn('MARCA', 'marca', 'left', 100);

// detail actions
$this->detail_list->addQuickAction( 'Edit', new TDataGridAction([$this, 'onEditDetail']), 'id', 'fa:edit blue');
$this->detail_list->addQuickAction( 'Delete', new TDataGridAction([$this, 'onDeleteDetail']), 'id', 'fa:trash red');
$this->detail_list->createModel();

$panel = new TPanelGroup;
$panel->add($this->detail_list);
$panel->getBody()->style = 'overflow-x:auto';
$this->form->addContent( [$panel] );

$btn = $this->form->addAction( _t('Save'), new TAction([$this, 'onSave']), 'fa:save');
$btn->class = 'btn btn-sm btn-primary';
$this->form->addAction( _t('Clear'), new TAction([$this, 'onClear']), 'fa:eraser red');

// create the page container
$container = new TVBox;
$container->style = 'width: 90%';
// $container->add(new TXMLBreadCrumb('menu.xml', __CLASS__));
$container->add($this->form);
parent::add($container);
}


/**
* Clear form
* @param $param URL parameters
*/
public function onClear($param)
{
$this->form->clear(TRUE);
TSession::setValue(__CLASS__.'_items', array());
$this->onReload( $param );
}

/**
* Save an item from form to session list
* @param $param URL parameters
*/
public function onSaveDetail( $param )
{
try
{
TTransaction::open('conn');
$data = $this->form->getData();

$items = TSession::getValue(__CLASS__.'_items');
$key = empty($data->detail_id) ? 'X'.mt_rand(1000000000, 1999999999) : $data->detail_id;

$items[ $key ] = array();
$items[ $key ]['id'] = $key;
$items[ $key ]['produto_pk'] = $data->detail_produto_pk;
$items[ $key ]['marca'] = $data->detail_marca;

TSession::setValue(__CLASS__.'_items', $items);

// clear detail form fields
$data->detail_id = '';
$data->detail_produto_pk = '';
$data->detail_produto = '';
$data->detail_marca = '';

TTransaction::close();
$this->form->setData($data);

$this->onReload( $param ); // reload the items
}
catch (Exception $e)
{
$this->form->setData( $this->form->getData());
new TMessage('error', $e->getMessage());
}
}

/**
* Load an item from session list to detail form
* @param $param URL parameters
*/
public static function onEditDetail( $param )
{
// read session items
$items = TSession::getValue(__CLASS__.'_items');

// get the session item
$item = $items[ $param['key'] ];

$data = new stdClass;
$data->detail_id = $item['id'];
$data->detail_produto_pk = $item['produto_pk'];
$data->detail_marca = $item['marca'];

// fill detail fields
TForm::sendData( 'form_Entrada', $data );
}

/**
* Delete an item from session list
* @param $param URL parameters
*/
public static function onDeleteDetail( $param )
{
// reset items
$data = new stdClass;
$data->detail_produto_pk = '';
$data->detail_marca = '';

// clear form data
TForm::sendData('form_Entrada', $data );

// read session items
$items = TSession::getValue(__CLASS__.'_items');

// get detail id
$detail_id = $param['key'];

// delete the item from session
unset($items[ $detail_id ] );

// rewrite session items
TSession::setValue(__CLASS__.'_items', $items);

// delete item from screen
TScript::create("ttable_remove_row_by_id('Entrada_list', '{$detail_id}')");
}

/**
* Load the items list from session
* @param $param URL parameters
*/
public function onReload($param)
{
// read session items
$items = TSession::getValue(__CLASS__.'_items');

$this->detail_list->clear(); // clear detail list

if ($items)
{
foreach ($items as $list_item)
{
$item = (object) $list_item;

$row = $this->detail_list->addItem( $item );
$row->id = $list_item['id'];
}
}

$this->loaded = TRUE;
}

/**
* Load Master/Detail data from database to form/session
*/
public function onEdit($param)
{
try
{
TTransaction::open('conn');

if (isset($param['key']))
{
$key = $param['key'];

$object = new Entrada($key);
$items = EntradaItens::where('entrada_pk', '=', $key)->load();

$session_items = array();
foreach( $items as $item )
{
$item_key = $item->id;
$session_items[$item_key] = $item->toArray();
$session_items[$item_key]['id'] = $item->id;
$session_items[$item_key]['produto_pk'] = $item->produto_pk;
$session_items[$item_key]['marca'] = $item->marca;
}
TSession::setValue(__CLASS__.'_items', $session_items);

$this->form->setData($object); // fill the form with the active record data
$this->onReload( $param ); // reload items list
TTransaction::close(); // close transaction
}
else
{
$this->form->clear(TRUE);
TSession::setValue(__CLASS__.'_items', null);
$this->onReload( $param );
}
}
catch (Exception $e) // in case of exception
{
new TMessage('error', $e->getMessage());
TTransaction::rollback();
}
}

/**
* Save the Master/Detail data from form/session to database
*/
public function onSave()
{
try
{
// open a transaction with database
TTransaction::open('conn');

$data = $this->form->getData();
$master = new Entrada;
$master->fromArray( (array) $data);
$this->form->validate(); // form validation

$master->store(); // save master object
// delete details
$old_items = EntradaItens::where('entrada_pk', '=', $master->id)->load();

$keep_items = array();

// get session items
$items = TSession::getValue(__CLASS__.'_items');

if( $items )
{
foreach( $items as $item )
{
if (substr($item['id'],0,1) == 'X' ) // new record
{
$detail = new EntradaItens;
}
else
{
$detail = new EntradaItens;
$detail->id = $item['id'];
}

$detail->produto_pk = $item['produto_pk'];
$detail->marca = $item['marca'];
$detail->entrada_pk = $master->id;
$detail->store();

$keep_items[] = $detail->id;
}
}

if ($old_items)
{
foreach ($old_items as $old_item)
{
if (!in_array( $old_item->id, $keep_items))
{
$old_item->delete();
}
}
}
TTransaction::close(); // close the transaction

// reload form and session items
$this->onEdit(array('key'=>$master->id));

new TMessage('info', TAdiantiCoreTranslator::translate('Record saved'));
}
catch (Exception $e) // in case of exception
{
new TMessage('error', $e->getMessage());
$this->form->setData( $this->form->getData() ); // keep form data
TTransaction::rollback();
}
}

/**
* Show the page
*/
public function show()
{
// check if the datagrid is already loaded
if (!$this->loaded AND (!isset($_GET['method']) OR $_GET['method'] !== 'onReload') )
{
$this->onReload( func_get_arg(0) );
}
parent::show();
}
}


MODELS
class Produtos extends TRecord
{
const TABLENAME = 'produtos';
const PRIMARYKEY= 'id';
const IDPOLICY = 'max'; // {max, serial}


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


}


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


private $entrada_itenss;

/**
* Constructor method
*/
public function __construct($id = NULL, $callObjectLoad = TRUE)
{
parent::__construct($id, $callObjectLoad);
parent::addAttribute('nota_fiscal');
}


/**
* Method addEntradaItens
* Add a EntradaItens to the Entrada
* @param $object Instance of EntradaItens
*/
public function addEntradaItens(EntradaItens $object)
{
$this->entrada_itenss[] = $object;
}

/**
* Method getEntradaItenss
* Return the Entrada' EntradaItens's
* @return Collection of EntradaItens
*/
public function getEntradaItenss()
{
return $this->entrada_itenss;
}

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

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

// load the related EntradaItens objects
$repository = new TRepository('EntradaItens');
$criteria = new TCriteria;
$criteria->add(new TFilter('entrada_pk', '=', $id));
$this->entrada_itenss = $repository->load($criteria);

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

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

// delete the related EntradaItens objects
$criteria = new TCriteria;
$criteria->add(new TFilter('entrada_pk', '=', $this->id));
$repository = new TRepository('EntradaItens');
$repository->delete($criteria);
// store the related EntradaItens objects
if ($this->entrada_itenss)
{
foreach ($this->entrada_itenss as $entrada_itens)
{
unset($entrada_itens->id);
$entrada_itens->entrada_pk = $this->id;
$entrada_itens->store();
}
}
}

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


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


}

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


private $produtos;

/**
* Constructor method
*/
public function __construct($id = NULL, $callObjectLoad = TRUE)
{
parent::__construct($id, $callObjectLoad);
parent::addAttribute('entrada_pk');
parent::addAttribute('produto_pk');
parent::addAttribute('marca');
}


/**
* Method set_produtos
* Sample of usage: $entrada_itens->produtos = $object;
* @param $object Instance of Produtos
*/
public function set_produtos(Produtos $object)
{
$this->produtos = $object;
$this->produto_pk = $object->id;
}

/**
* Method get_produtos
* Sample of usage: $entrada_itens->produtos->attribute;
* @returns Produtos instance
*/
public function get_produtos()
{
// loads the associated object
if (empty($this->produtos))
$this->produtos = new Produtos($this->id);

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



}

Curso completo Meu Negócio Pronto
Use para si, ou transforme em um negócio: Inclui aulas e códigos-fontes
Gestor de conteúdo (SITE) + Loja Virtual (E-Commerce) + Emissor de Notas para infoprodutos


Meu negócio pronto Quero me inscrever agora!

Comentários (1)


NR

Você pode usar a função setTransformer na coluna que deseja exibir a descrição. O id será o primeiro parâmetro da função e com ele pode buscar os dados do objeto vinculado.
adianti.com.br/framework_files/tutor/index.php?class=DatagridTransfo

Outra opção é fazer a busca pelo objeto diretamente na função onReload, antes de adicionar o objeto à grid.