Gravar e editar no banco de dados a informação de um TDBCombo 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 TDBCo...
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)
 
  1. <?php
  2. class Entregador extends TRecord
  3. {
  4. const TABLENAME = 'tbentregadores';
  5. const PRIMARYKEY = 'id_entregador';
  6. const IDPOLICY = 'max';
  7. public function __construct(1641 = NULL, $callObjectLoad = TRUE)
  8. {
  9. parent::__construct(1641, $callObjectLoad);
  10. parent::addAttribute('nome_entregador');
  11. parent::addAttribute('cpf_entregador');
  12. parent::addAttribute('rg_entregador');
  13. parent::addAttribute('celular_entregador');
  14. parent::addAttribute('nome_terceirizada');
  15. }
  16. }
  17. ?>


control (EntregadorForm)
 
  1. <?php
  2. class EntregadorForm extends TStandardForm
  3. {
  4. protected $form; // form
  5. function __construct()
  6. {
  7. parent::__construct();
  8. parent::setDatabase('conectabd'); // defines the database
  9. parent::setActiveRecord('Entregador'); // defines the active record
  10. // creates the form
  11. $this->form = new TQuickForm('form_Entregador');
  12. $this->form->class = 'tform'; // CSS class
  13. $this->form->style = 'width: 500px';
  14. // define the form title
  15. $this->form->setFormTitle('Cadastro de Entregadores');
  16. // create the form fields
  17. 1641_entregador = new TEntry('id_entregador');
  18. $nome_entregador = new TEntry('nome_entregador');
  19. $cpf_entregador = new TEntry('cpf_entregador');
  20. $rg_entregador = new TEntry('rg_entregador');
  21. $celular_entregador = new TEntry('celular_entregador');
  22. $terceirizada = new TDBCombo('tbterceirizadas','conectabd','Terceirizada','id_emp_terc','nome_emp_terc');
  23. 1641_entregador->setEditable(FALSE);
  24. // add the form fields
  25. $this->form->addQuickField('ID', 1641_entregador, 40);
  26. $this->form->addQuickField('Nome', $nome_entregador, 300);
  27. $this->form->addQuickField('CPF', $cpf_entregador, 120);
  28. $this->form->addQuickField('RG', $rg_entregador, 120);
  29. $this->form->addQuickField('Celular', $celular_entregador, 120);
  30. $this->form->addQuickField('Terceirizada', $terceirizada, 120);
  31. // define the form action
  32. $this->form->addQuickAction('Salvar', new TAction(array($this, 'onSave')), 'ico_save.png');
  33. $this->form->addQuickAction('Novo', new TAction(array($this, 'onEdit')), 'ico_new.png');
  34. $this->form->addQuickAction('Listar', new TAction(array('ListaEntregadorForm', 'onReload')), 'ico_datagrid.png');
  35. }
  36. }
  37. ?>


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


HL

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
ML

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.
HL

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

 
  1. <?php
  2. /**
  3. * UsuarioHasUnidade Active Record
  4. * @author <your-name-here>
  5. */
  6. class UsuarioHasUnidade extends TRecord
  7. {
  8. const TABLENAME = 'usuario_has_unidade';
  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_unidade');
  18. parent::addAttribute('id_system_user');
  19. }
  20. public function set_usuario_usuario(SystemUser $usuario)
  21. {
  22. $this->usuario = $usuario;
  23. $this->id_usuario = $usuario->id;
  24. }
  25. public function get_usuario_usuario()
  26. {
  27. if (empty($this->name))
  28. $this->name = new SystemUser($this->id_system_user);
  29. // returns the associated object
  30. return $this->name->name;
  31. }
  32. public function set_unidade_unidade(Unidade $unidade)
  33. {
  34. $this->unidade = $unidade;
  35. $this->id_unidade = $unidade->id;
  36. }
  37. public function get_unidade_unidade()
  38. {
  39. if (empty($this->unidade))
  40. $this->unidade = new Unidade($this->id_unidade);
  41. // returns the associated object
  42. return $this->unidade->unidade;
  43. }
  44. }
  45. ?>


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();
}
}

?>
ML

Vou verificar esse sua dica, assim que terminar retorno aqui no fórum.
PD

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,