ML
Gravar e editar no banco de dados a informação de um TDBCombo
Fechado
Pessoal!
To utilizando uma TDBCombo para listar o campo de uma tabela (tbterceirizadas) para gravar em outra tabela (tbentregadores). Ao cadastrar os entregadores consigo listar as empresas terceirizadas cadastradas no banco de dados, porém ao salvar não grava no banco de dados o valor setado na TDBCombo, o que ocorre também na hora de editar, os demais campos vem preenchidos somente a TDBCombo que não. Gostaria de orientação para resolver essa situação.
model (Entregador)
control (EntregadorForm)
To utilizando uma TDBCombo para listar o campo de uma tabela (tbterceirizadas) para gravar em outra tabela (tbentregadores). Ao cadastrar os entregadores consigo listar as empresas terceirizadas cadastradas no banco de dados, porém ao salvar não grava no banco de dados o valor setado na TDBCombo, o que ocorre também na hora de editar, os demais campos vem preenchidos somente a TDBCombo que não. Gostaria de orientação para resolver essa situação.
model (Entregador)
- <?php
- class Entregador extends TRecord
- {
- const TABLENAME = 'tbentregadores';
- const PRIMARYKEY = 'id_entregador';
- const IDPOLICY = 'max';
-
- public function __construct(1641 = NULL, $callObjectLoad = TRUE)
- {
- parent::__construct(1641, $callObjectLoad);
- parent::addAttribute('nome_entregador');
- parent::addAttribute('cpf_entregador');
- parent::addAttribute('rg_entregador');
- parent::addAttribute('celular_entregador');
- parent::addAttribute('nome_terceirizada');
-
- }
- }
- ?>
control (EntregadorForm)
- <?php
- class EntregadorForm extends TStandardForm
- {
- protected $form; // form
-
-
- function __construct()
- {
- parent::__construct();
-
- parent::setDatabase('conectabd'); // defines the database
- parent::setActiveRecord('Entregador'); // defines the active record
-
- // creates the form
- $this->form = new TQuickForm('form_Entregador');
- $this->form->class = 'tform'; // CSS class
- $this->form->style = 'width: 500px';
-
- // define the form title
- $this->form->setFormTitle('Cadastro de Entregadores');
-
- // create the form fields
- 1641_entregador = new TEntry('id_entregador');
- $nome_entregador = new TEntry('nome_entregador');
- $cpf_entregador = new TEntry('cpf_entregador');
- $rg_entregador = new TEntry('rg_entregador');
- $celular_entregador = new TEntry('celular_entregador');
- $terceirizada = new TDBCombo('tbterceirizadas','conectabd','Terceirizada','id_emp_terc','nome_emp_terc');
-
- 1641_entregador->setEditable(FALSE);
-
- // add the form fields
- $this->form->addQuickField('ID', 1641_entregador, 40);
- $this->form->addQuickField('Nome', $nome_entregador, 300);
- $this->form->addQuickField('CPF', $cpf_entregador, 120);
- $this->form->addQuickField('RG', $rg_entregador, 120);
- $this->form->addQuickField('Celular', $celular_entregador, 120);
- $this->form->addQuickField('Terceirizada', $terceirizada, 120);
-
- // define the form action
- $this->form->addQuickAction('Salvar', new TAction(array($this, 'onSave')), 'ico_save.png');
- $this->form->addQuickAction('Novo', new TAction(array($this, 'onEdit')), 'ico_new.png');
- $this->form->addQuickAction('Listar', new TAction(array('ListaEntregadorForm', 'onReload')), 'ico_datagrid.png');
-
- }
- }
- ?>
Boa noite Marcelo!
Você ja se certificou que tbterceirizadas realmente existe no seu modelo, pois é este que vai receber o id_emp_terc.
Procure repassa no seu form o nome real que se encontra no seu modelo.
Espero ter ajudado e qualquer dúvida.
Ótimo Framework
Helton boa noite!
Não entendi muito bem sua colocação. Vou tentar abstrair melhor minha ideia.
Através da TDBCombo vou gravar um valor na tabela tbentregadores. Esse valor virá da tabela tbterceirizadas, ou seja, quando eu for cadastrar um entregador ele será atrelado a uma empresa terceirizada. A TDBCombo está listando as empresas terceirizadas que estão sendo inseridas no banco de dados. A questão é na hora de salvar a inserção de um entregador, a informação que eu seto na TDBCombo não grava na tabela tbentregadores e consequentemente na hora edição ela vem em branco.
Boa noite!
Onde tem tbterceirizadas e $terceirizada deve ser trocado por o que está no modelo "nome_terceirizada", este campo vai pegar o valor id_emp_terc, e você deve se certificar que no seu BD este campo é um foreign key do tipo int.
Segue um exemplo funcional
Modelo
Controle
class UsuarioHasUnidadeFormList extends TPage
{
protected $form; // form
protected $datagrid; // datagrid
protected $pageNavigation;
protected $loaded;
/**
* Class constructor
* Creates the page and the registration form
*/
function __construct()
{
parent::__construct();
// creates the form
$this->form = new TQuickForm('form_UsuarioHasUnidade');
$this->form->class = 'tform'; // CSS class
$this->form->setFormTitle('Vínculos'); // define the form title
$this->form->style = 'width: 1000px';
// create the form fields
$id = new TEntry('id');
$id_system_user = new TDBSeekButton('id_system_user', 'chamado', 'form_UsuarioHasUnidade', 'SystemUser', 'name', 'id_system_user', 'name' );
$nome = new TEntry('name');
$id_unidade = new TDBCombo('id_unidade', 'chamado', 'unidade', 'id', 'unidade');
// add the fields
$this->form->addQuickField('ID', $id, 70);
$this->form->addQuickField('Buscar Usuário', $id_system_user, 50, new TRequiredValidator);
$this->form->addQuickField('Usuário',$nome, 200, new TRequiredValidator );
$this->form->addQuickField('Unidade', $id_unidade, 200, new TRequiredValidator);
$id->setEditable(FALSE);
$nome->setEditable(FALSE);
// create the form actions
$this->form->addQuickAction(_t('Save'), new TAction(array($this, 'onSave')), 'ico_save.png');
$this->form->addQuickAction(_t('New'), new TAction(array($this, 'onEdit')), 'ico_new.png');
// creates a DataGrid
$this->datagrid = new TQuickGrid;
$this->datagrid->setHeight(320);
$this->datagrid->style = 'width: 1000px';
// creates the datagrid columns
$id = $this->datagrid->addQuickColumn('ID', 'id', 'center', 100);
$id_system_user = $this->datagrid->addQuickColumn('Usuário', 'usuario_usuario', 'center', 100);
$id_unidade = $this->datagrid->addQuickColumn('Unidade', 'unidade_unidade', 'center', 100);
// create the datagrid actions
$edit_action = new TDataGridAction(array($this, 'onEdit'));
$delete_action = new TDataGridAction(array($this, 'onDelete'));
// add the actions to the datagrid
$this->datagrid->addQuickAction(_t('Edit'), $edit_action, 'id', 'ico_edit.png');
$this->datagrid->addQuickAction(_t('Delete'), $delete_action, 'id', 'ico_delete.png');
// create the datagrid model
$this->datagrid->createModel();
// creates the page navigation
$this->pageNavigation = new TPageNavigation;
$this->pageNavigation->setAction(new TAction(array($this, 'onReload')));
$this->pageNavigation->setWidth($this->datagrid->getWidth());
// create the datagrid model
$this->datagrid->createModel();
// creates the page navigation
$this->pageNavigation = new TPageNavigation;
$this->pageNavigation->setAction(new TAction(array($this, 'onReload')));
$this->pageNavigation->setWidth($this->datagrid->getWidth());
// create the page container
$container = TVBox::pack( $this->form, $this->datagrid, $this->pageNavigation);
parent::add($container);
}
/**
* method onReload()
* Load the datagrid with the database objects
*/
function onReload($param = NULL)
{
try
{
// open a transaction with database 'chamado'
TTransaction::open('chamado');
// creates a repository for UsuarioHasUnidade
$repository = new TRepository('UsuarioHasUnidade');
$limit = 10;
// creates a criteria
$criteria = new TCriteria;
// default order
if (empty($param['order']))
{
$param['order'] = 'id';
$param['direction'] = 'asc';
}
$criteria->setProperties($param); // order, offset
$criteria->setProperty('limit', $limit);
if (TSession::getValue('UsuarioHasUnidade_filter'))
{
// add the filter stored in the session to the criteria
$criteria->add(TSession::getValue('UsuarioHasUnidade_filter'));
}
// load the objects according to criteria
$objects = $repository->load($criteria, FALSE);
$this->datagrid->clear();
if ($objects)
{
// iterate the collection of active records
foreach ($objects as $object)
{
// add the object inside the datagrid
$this->datagrid->addItem($object);
}
}
// reset the criteria for record count
$criteria->resetProperties();
$count= $repository->count($criteria);
$this->pageNavigation->setCount($count); // count of records
$this->pageNavigation->setProperties($param); // order, page
$this->pageNavigation->setLimit($limit); // limit
// close the transaction
TTransaction::close();
$this->loaded = true;
}
catch (Exception $e) // in case of exception
{
new TMessage('error', 'Error ' . $e->getMessage()); // shows the exception error message
TTransaction::rollback(); // undo all pending operations
}
}
/**
* method onDelete()
* executed whenever the user clicks at the delete button
* Ask if the user really wants to delete the record
*/
function onDelete($param)
{
// define the delete action
$action = new TAction(array($this, 'Delete'));
$action->setParameters($param); // pass the key parameter ahead
// shows a dialog to the user
new TQuestion(TAdiantiCoreTranslator::translate('Do you really want to delete ?'), $action);
}
/**
* method Delete()
* Delete a record
*/
function Delete($param)
{
try
{
// get the parameter $key
$key=$param['key'];
TTransaction::open('chamado'); // open the transaction
$object = new UsuarioHasUnidade($key, FALSE); // instantiates the Active Record
$object->delete(); // deletes the object
TTransaction::close(); // close the transaction
$this->onReload( $param ); // reload the listing
new TMessage('info', TAdiantiCoreTranslator::translate('Record deleted')); // success message
}
catch (Exception $e) // in case of exception
{
new TMessage('error', 'Error ' . $e->getMessage()); // shows the exception error message
TTransaction::rollback(); // undo all pending operations
}
}
/**
* method onSave()
* Executed whenever the user clicks at the save button
*/
function onSave()
{
try
{
TTransaction::open('chamado'); // open a transaction with database
// get the form data into an active record UsuarioHasUnidade
$object = $this->form->getData('UsuarioHasUnidade');
$this->form->validate(); // form validation
$object->store(); // stores the object
$this->form->setData($object); // fill the form with the active record data
TTransaction::close(); // close the transaction
new TMessage('info', TAdiantiCoreTranslator::translate('Record saved')); // success message
$this->onReload(); // reload the listing
}
catch (Exception $e) // in case of exception
{
new TMessage('error', 'Error ' . $e->getMessage()); // shows the exception error message
TTransaction::rollback(); // undo all pending operations
}
}
/**
* method onEdit()
* Executed whenever the user clicks at the edit button da datagrid
*/
function onEdit($param)
{
try
{
if (isset($param['key']))
{
$key=$param['key']; // get the parameter $key
TTransaction::open('chamado'); // open a transaction with the database
$object = new UsuarioHasUnidade($key); // instantiates the Active Record
$this->form->setData($object); // fill the form with the active record data
TTransaction::close(); // close the transaction
}
else
{
$this->form->clear();
}
}
catch (Exception $e) // in case of exception
{
new TMessage('error', 'Error ' . $e->getMessage()); // shows the exception error message
TTransaction::rollback(); // undo all pending operations
}
}
/**
* method show()
* Shows the page e seu conteúdo
*/
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();
}
}
?>
Vou verificar esse sua dica, assim que terminar retorno aqui no fórum.
O Helton está certo, o primeiro parâmetro do componente é o campo do BD que vai receber a informação.
No seu caso está new TDBCombo('tbterceirizadas', ...)
Não faz muito sentido, deveria ser algo como new TDBCombo('id_terceirizada'...
Uma vez que normalmente se grava o id do registro relacionado, não o nome...
Att,