AR
Não grava os dados do form
Fechado
Boa noite!
Estou iniciando com o Adianti Studio e emperrei em um problema para gravar alguns campos de um formulário criado no FormDesigner; outros campos do mesmo form são salvos, mas os relacionados abaixo não:
- dt_aniversario = tipo TDate;
- telefone_cel = tipo TEntry;
- telefone_fixo = tipo TEntry;
- tp_usuarios = tipo TDBCombo;
- empresas = tipo TDBCombo;
- ativo = tipo TRadioGroup.
No código abaixo verifiquei que em onSave todos os campos, incluindo os citados acima, são lidos em diversas situações (linhas $message comentadas), mas não são gravados. Editei, diretamente no bd, um registro gravado incompleto e executei o onEdit com sucesso, ou seja: recuperou todos os dados que foram gravados (tanto pelo form como pela minha edição direta).
Model:
Controller:
Estou iniciando com o Adianti Studio e emperrei em um problema para gravar alguns campos de um formulário criado no FormDesigner; outros campos do mesmo form são salvos, mas os relacionados abaixo não:
- dt_aniversario = tipo TDate;
- telefone_cel = tipo TEntry;
- telefone_fixo = tipo TEntry;
- tp_usuarios = tipo TDBCombo;
- empresas = tipo TDBCombo;
- ativo = tipo TRadioGroup.
No código abaixo verifiquei que em onSave todos os campos, incluindo os citados acima, são lidos em diversas situações (linhas $message comentadas), mas não são gravados. Editei, diretamente no bd, um registro gravado incompleto e executei o onEdit com sucesso, ou seja: recuperou todos os dados que foram gravados (tanto pelo form como pela minha edição direta).
Model:
- <?php
- class Usuarios extends TRecord
- {
- const TABLENAME = 'usuarios';
- const PRIMARYKEY= 'id';
- const IDPOLICY = 'max'; // {max, serial}
- private $empresas;
- private $tp_usuarios;
- /**
- * Constructor method
- */
- public function __construct(985 = NULL, $callObjectLoad = TRUE)
- {
- parent::__construct(985, $callObjectLoad);
- parent::addAttribute('nome');
- parent::addAttribute('dt_aniversario');
- parent::addAttribute('email');
- parent::addAttribute('login');
- parent::addAttribute('senha');
- parent::addAttribute('telefone_cel');
- parent::addAttribute('telefone_fixo');
- parent::addAttribute('tp_usuarios');
- parent::addAttribute('empresas');
- parent::addAttribute('ativo');
- parent::addAttribute('dt_cadastro');
- }
- /**
- * Method set_empresas
- * Sample of usage: $usuarios->empresas = $object;
- * @param $object Instance of Empresas
- */
- public function set_empresas(Empresas $object)
- {
- $this->empresas = $object;
- $this->id_empresas = $object->id;
- }
- /**
- * Method get_empresas
- * Sample of usage: $usuarios->empresas->attribute;
- * @returns Empresas instance
- */
- public function get_empresas()
- {
- // loads the associated object
- if (empty($this->empresas))
- $this->empresas = new Empresas($this->id_empresas);
- // returns the associated object
- return $this->empresas;
- }
- /**
- * Method set_tp_usuarios
- * Sample of usage: $usuarios->tp_usuarios = $object;
- * @param $object Instance of TpUsuarios
- */
- public function set_tp_usuarios(TpUsuarios $object)
- {
- $this->tp_usuarios = $object;
- $this->id_tp_usuarios = $object->id;
- }
- /**
- * Method get_tp_usuarios
- * Sample of usage: $usuarios->tp_usuarios->attribute;
- * @returns TpUsuarios instance
- */
- public function get_tp_usuarios()
- {
- // loads the associated object
- if (empty($this->tp_usuarios))
- $this->tp_usuarios = new TpUsuarios($this->id_tp_usuarios);
- // returns the associated object
- return $this->tp_usuarios;
- }
- }
- ?>
Controller:
- <?php
- class FormCadAdminUsuarios extends TPage
- {
- private $form;
- private $datagrid;
- private $pageNavigation;
- private $loaded;
- /**
- * Class constructor
- * Creates the page and the registration form
- */
- function __construct()
- {
- parent::__construct();
- // creates the form
- $this->form = new TForm('form_Usuarios');
- try
- {
- // TUIBuilder object
- $ui = new TUIBuilder(500,500);
- $ui->setController($this);
- $ui->setForm($this->form);
- // reads the xml form
- $ui->parseFile('C:\webs\cadsb/app/forms\FormCadAdmUsuarios.form.xml');
- // get the interface widgets
- $fields = $ui->getWidgets();
- // look for the TDataGrid object
- foreach ($fields as $name => $field)
- {
- if ($field instanceof TDataGrid)
- {
- $this->datagrid = $field;
- $this->pageNavigation = $this->datagrid->getPageNavigation();
- }
- }
- // add the TUIBuilder panel inside the TForm object
- $this->form->add($ui);
- // set form fields from interface fields
- $this->form->setFields($ui->getFields());
- }
- catch (Exception $e)
- {
- new TMessage('error', $e->getMessage());
- }
- // add the form to the page
- parent::add($this->form);
- }
- /**
- * method onSave()
- * Executed whenever the user clicks at the save button
- */
- function onSave()
- {
- try
- {
- // open a transaction with database 'con_cadsb'
- TTransaction::open('con_cadsb');
- // get the form data into an active record Usuarios
- $object = $this->form->getData('Usuarios');
- /** $message = 'ID (antes validate) ' . $object->id . '<br>';
- $message.= 'Nome ' . $object->nome . '<br>';
- $message.= 'E-mail ' . $object->email . '<br>';
- $message.= 'Dt_aniversario ' . $object->dt_aniversario . '<br>';
- $message.= 'Tel Cel ' . $object->telefone_cel . '<br>';
- $message.= 'Tel Fixo ' . $object->telefone_fixo . '<br>';
- $message.= 'Tipo ' . $object->tp_usuarios . '<br>';
- $message.= 'Empresa ' . $object->empresas . '<br>';
- $message.= 'Login ' . $object->login . '<br>';
- $message.= 'Senha ' . $object->senha . '<br>';
- $message.= 'Ativo ' . $object->ativo . '<br>';
- $message.= 'Dt_cadastro' . $object->dt_cadastro;
- new TMessage('info', $message);
- */
- // form validation
- $this->form->validate();
- // criptografar senha no bd
- if ($object-> senha)
- {
- $object-> senha = md5($object-> senha);
- }
- else
- {
- unset($object-> senha);
- }
- /** $message = 'ID (depois getData) ' . $object->id . '<br>';
- $message.= 'Nome ' . $object->nome . '<br>';
- $message.= 'E-mail ' . $object->email . '<br>';
- $message.= 'Dt_aniversario ' . $object->dt_aniversario . '<br>';
- $message.= 'Tel Cel ' . $object->telefone_cel . '<br>';
- $message.= 'Tel Fixo ' . $object->telefone_fixo . '<br>';
- $message.= 'Tipo ' . $object->tp_usuarios . '<br>';
- $message.= 'Empresa ' . $object->empresas . '<br>';
- $message.= 'Login ' . $object->login . '<br>';
- $message.= 'Senha ' . $object->senha . '<br>';
- $message.= 'Ativo ' . $object->ativo . '<br>';
- $message.= 'Dt_cadastro' . $object->dt_cadastro;
- new TMessage('info', $message);
- */
- // stores the object
- $object->store();
- /** $message = 'ID (depois store) ' . $object->id . '<br>';
- $message.= 'Nome ' . $object->nome . '<br>';
- $message.= 'E-mail ' . $object->email . '<br>';
- $message.= 'Dt_aniversario ' . $object->dt_aniversario . '<br>';
- $message.= 'Tel Cel ' . $object->telefone_cel . '<br>';
- $message.= 'Tel Fixo ' . $object->telefone_fixo . '<br>';
- $message.= 'Tipo ' . $object->tp_usuarios . '<br>';
- $message.= 'Empresa ' . $object->empresas . '<br>';
- $message.= 'Login ' . $object->login . '<br>';
- $message.= 'Senha ' . $object->senha . '<br>';
- $message.= 'Ativo ' . $object->ativo . '<br>';
- $message.= 'Dt_cadastro' . $object->dt_cadastro;
- new TMessage('info', $message);
- */
- // set the data back to the form
- $this->form->setData($object);
- /** $message = 'ID (depois setData) ' . $object->id . '<br>';
- $message.= 'Nome ' . $object->nome . '<br>';
- $message.= 'E-mail ' . $object->email . '<br>';
- $message.= 'Dt_aniversario ' . $object->dt_aniversario . '<br>';
- $message.= 'Tel Cel ' . $object->telefone_cel . '<br>';
- $message.= 'Tel Fixo ' . $object->telefone_fixo . '<br>';
- $message.= 'Tipo ' . $object->tp_usuarios . '<br>';
- $message.= 'Empresa ' . $object->empresas . '<br>';
- $message.= 'Login ' . $object->login . '<br>';
- $message.= 'Senha ' . $object->senha . '<br>';
- $message.= 'Ativo ' . $object->ativo . '<br>';
- $message.= 'Dt_cadastro' . $object->dt_cadastro;
- new TMessage('info', $message);
- */
- // close the transaction
- TTransaction::close();
- // shows the success message
- new TMessage('info', TAdiantiCoreTranslator::translate('Record saved'));
- // reload the listing
- $this->form->clear();
- $this->onReload();
- }
- catch (Exception $e) // in case of exception
- {
- // shows the exception error message
- new TMessage('error', '<b>Error</b> ' . $e->getMessage());
- // undo all pending operations
- TTransaction::rollback();
- }
- }
- /**
- * method onEdit()
- * Executed whenever the user clicks at the edit button da datagrid
- */
- function onEdit($param)
- {
- try
- {
- if (isset($param['key']))
- {
- // get the parameter $key
- $key=$param['key'];
- // open a transaction with database 'con_cadsb'
- TTransaction::open('con_cadsb');
- // instantiates object Usuarios
- $object = new Usuarios($key);
- $message = 'ID (onEdit depois de instanciado o objeto) ' . $object->id . '<br>';
- $message.= 'Nome ' . $object->nome . '<br>';
- $message.= 'E-mail ' . $object->email . '<br>';
- $message.= 'Dt_aniversario ' . $object->dt_aniversario . '<br>';
- $message.= 'Tel Cel ' . $object->telefone_cel . '<br>';
- $message.= 'Tel Fixo ' . $object->telefone_fixo . '<br>';
- $message.= 'Tipo ' . $object->tp_usuarios . '<br>';
- $message.= 'Empresa ' . $object->empresas . '<br>';
- $message.= 'Login ' . $object->login . '<br>';
- $message.= 'Senha ' . $object->senha . '<br>';
- $message.= 'Ativo ' . $object->ativo . '<br>';
- $message.= 'Dt_cadastro' . $object->dt_cadastro;
- new TMessage('info', $message);
- // fill the form with the active record data
- $this->form->setData($object);
- // close the transaction
- TTransaction::close();
- }
- else
- {
- $this->form->clear();
- }
- }
- catch (Exception $e) // in case of exception
- {
- // shows the exception error message
- new TMessage('error', '<b>Error</b> ' . $e->getMessage());
- // undo all pending operations
- TTransaction::rollback();
- }
- }
- /**
- * method onDelete()
- * executed whenever the user clicks at the delete button
- * Ask if the user really wants to delete the record
- */
- function onDelete($param)
- {
- // get the parameter $key
- $key=$param['key'];
- // define two actions
- $action = new TAction(array($this, 'Delete'));
- // define the action parameters
- $action->setParameter('key', $key);
- // 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'];
- // open a transaction with database 'con_cadsb'
- TTransaction::open('con_cadsb');
- // instantiates object Usuarios
- $object = new Usuarios($key);
- // deletes the object from the database
- $object->delete();
- // close the transaction
- TTransaction::close();
- // reload the listing
- $this->onReload();
- // shows the success message
- new TMessage('info', TAdiantiCoreTranslator::translate('Record deleted'));
- }
- catch (Exception $e) // in case of exception
- {
- // shows the exception error message
- new TMessage('error', '<b>Error</b> ' . $e->getMessage());
- // undo all pending operations
- TTransaction::rollback();
- }
- }
- /**
- * method onReload()
- * Load the datagrid with the database objects
- */
- function onReload($param = NULL)
- {
- try
- {
- // open a transaction with database 'con_cadsb'
- TTransaction::open('con_cadsb');
- // creates a repository for Usuarios
- $repository = new TRepository('Usuarios');
- $limit = 10;
- // creates a criteria
- $criteria = new TCriteria;
- $criteria->setProperties($param); // order, offset
- $criteria->setProperty('limit', $limit);
- if (TSession::getValue('Usuarios_filter'))
- {
- // add the filter stored in the session to the criteria
- $criteria->add(TSession::getValue('Usuarios_filter'));
- }
- // load the objects according to criteria
- $objects = $repository->load($criteria);
- $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
- {
- // shows the exception error message
- new TMessage('error', '<b>Error</b> ' . $e->getMessage());
- // undo all pending operations
- TTransaction::rollback();
- }
- }
- /**
- * method show()
- * Shows the page
- */
- function show()
- {
- // check if the datagrid is already loaded
- if (!$this->loaded)
- {
- $this->onReload();
- }
- parent::show();
- }
- }
- ?>
Cara confere se o tipo de dados está compatível por exemplo o campo data tem que converter para o formato yyyy/mm/dd se for mysql veja se os outros campos não estão nesse criterio tipo texto em campo numero etc...
Boa tarde, Felipe.
No bd (MySQL) os campos são todos VARCHAR (o mesmo tipo dos que consigo gravar: nome, email, login etc.) e o tipo DATE para dt_aniversario.
Confere então nomes (tem que estar iguais) no banco = model = form da control
Confere senão existe alguma restrição no banco tipo campo maior que o permitido não é nada complicado rapidinho vc acostuma outra coisa da um var_dump abaixo da linha $object = $this->form->getData('Usuarios');
var_dump( $object); de uma checada se os dados estão vindo direitinho como no form ok :)
Além disso, experimente ligar os logs no onSave() para ver os comandos que estão indo para o banco de dados:
www.adianti.com.br/doc-framework-Persistence-Objects-RegisterLog
Att,
Pablo
Além disso Anderson, me permita dar mais uma dica: Uma classe não deve estar no plural, veja por que:
www.adianti.com.br/framework-naming
Att,
Pablo