Gravar na tabela a Unidade do Usuário Boa tarde Amigos, Alguém sabe informar como faço para gravar na tabela o nome do usuário logado no sistema e a unidade em que o usuário está cadastrado quando este gravar um novo registro? ...
ST
Gravar na tabela a Unidade do Usuário  
Boa tarde Amigos,
Alguém sabe informar como faço para gravar na tabela o nome do usuário logado no sistema e a unidade em que o usuário está cadastrado quando este
gravar um novo registro?


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


MG

No controller "LoginForm" ao se logar o sistema grava na variável de sessão o userid, recupere assim $userId = TSession::getValue('userid').
Se observar o modelo "SystemUser" poderá ver que há um relacionamento com "SystemUnit", uma vez recuperado um objeto "SystemUser", vc poderá obter a unit.
Exemplo:

$user = new SystemUser(TSession::getValue('userid'));
$unitId = $user->unit->id;

e assim por diante
ST

Marcelo,
Certo. Mas como gravar no banco de dados, ao clicar em salvar?
MG

No seu model e banco de dados vc deve ter os campos: system_user_id e system_unit_id.

Antes de salvar ($obj->store()), vc associa, por exemplo:

<?phppublic funciton onSave( $param ){     ....     $obj->system_user_id = TSession::getvalue('userid');     $user = new SystemUser(TSession::getValue('userod'));     $obj->system_unit_id = $user->system_unit_id;     $obj->store();     ...}?>
ST

Marcelo,
Certo. Mas como gravar no banco de dados, ao clicar em salvar?
ST

Marcelo,
Onde eu coloco esse código OnSave?
MG

Sebastião

Acredito que você tenha um form, certo?

Neste form você tem os componentes de entrada de dados e num dado momento você deve ter adicionado um TAction, certo?

Isto é o básico do framework....

Veja um exemplo:

<?php
<?php/** * TipoPercursosFormList Form List * @author  <your name here> */class TipoPercursosFormList extends TPage{    protected $form; // form    protected $datagrid; // datagrid    protected $pageNavigation;    protected $loaded;        /**     * Form constructor     * @param $param Request     */    public function __construct( $param )    {        parent::__construct();                // creates the form        $this->form = new TQuickForm('form_TipoPercursos');        $this->form->class = 'tform'; // change CSS class        $this->form = new BootstrapFormWrapper($this->form);        $this->form->style = 'display: table;width:100%'; // change style        $this->form->setFormTitle('TipoPercursos');        $this->form->setFieldsByRow(2);                // create the form fields        $id = new TEntry('id');        $descricao = new TEntry('descricao');        $valor_pagar = new TEntry('valor_pagar');        $valor_percurso = new TEntry('valor_percurso');        $status = new TCombo('status');                $id->setEditable(FALSE);        $valor_pagar->setNumericMask(2,',','.',TRUE);        $valor_percurso->setNumericMask(2,',','.',TRUE);        // config        $stt = array(            '1' => 'Ativo',            '0' => 'Inativo'        );        $status->addItems($stt);        $status->setValue(1);        // add the fields        $this->form->addQuickField('Id', $id,  100 );        $this->form->addQuickField('Descrição', $descricao,  200 , new TRequiredValidator);        $this->form->addQuickField('Valor Percurso', $valor_percurso,  200 , new TRequiredValidator);        $this->form->addQuickField('Valor Pagar', $valor_pagar,  200 , new TRequiredValidator);        $this->form->addQuickField('Status', $status,  100 , new TRequiredValidator);        /** samples         $this->form->addQuickFields('Date', array($date1, new TLabel('to'), $date2)); // side by side fields         $fieldX->addValidation( 'Field X', new TRequiredValidator ); // add validation         $fieldX->setSize( 100, 40 ); // set size         **/                 // create the form actions        $this->form->addQuickAction(_t('Save'), new TAction(array($this, 'onSave')), 'fa:floppy-o');        $this->form->addQuickAction(_t('New'),  new TAction(array($this, 'onClear')), 'bs:plus-sign green');                // creates a Datagrid        $this->datagrid = new TDataGrid;        ##LIST_DECORATOR##        $this->datagrid->style = 'width: 100%';        $this->datagrid->setHeight(320);        // $this->datagrid->datatable = 'true';        // $this->datagrid->enablePopover('Popover', 'Hi <b> {name} </b>');                // creates the datagrid columns        $column_id = new TDataGridColumn('id', 'Id', 'left');        $column_descrucai = new TDataGridColumn('descricao', 'Descrição', 'left');        $column_valor_pagar = new TDataGridColumn('valor_pagar', 'Valor Pagar', 'right');        $column_valor_percurso = new TDataGridColumn('valor_percurso', 'Valor Percurso', 'right');        $column_status = new TDataGridColumn('status', 'Status', 'center');        $column_user = new TDataGridColumn('system_user->name','Por','center');        $column_update = new TDataGridColumn('update_at','Em','center');        // add the columns to the DataGrid        $this->datagrid->addColumn($column_id);        $this->datagrid->addColumn($column_descrucai);        $this->datagrid->addColumn($column_valor_pagar);        $this->datagrid->addColumn($column_valor_percurso);        $this->datagrid->addColumn($column_status);        $this->datagrid->addColumn($column_user);        $this->datagrid->addColumn($column_update);                // transformers        $column_status->setTransformer(function($value, $object, $row){            $lbl = new TLabel('');                        switch ($value) {                case 1 :                    $lbl->setValue('Ativo');                    $lbl->class = 'label label-success';                    break;                case 0 :                    $lbl->setValue('Inativo');                    $lbl->class = 'label label-danger';                    break;            }                        return $lbl;        });                $column_update->setTransformer(function($value, $object, $row){            $data = new DateTime($value);            return $data->format('d/m/Y H:m:s');        });                        // creates two datagrid actions        $action1 = new TDataGridAction(array($this, 'onEdit'));        $action1->setUseButton(TRUE);        $action1->setButtonClass('btn btn-default');        $action1->setLabel(_t('Edit'));        $action1->setImage('fa:pencil-square-o blue fa-lg');        $action1->setField('id');                $action2 = new TDataGridAction(array($this, 'onDelete'));        $action2->setUseButton(TRUE);        $action2->setButtonClass('btn btn-default');        $action2->setLabel(_t('Delete'));        $action2->setImage('fa:trash-o red fa-lg');        $action2->setField('id');                // add the actions to the datagrid        $this->datagrid->addAction($action1);        $this->datagrid->addAction($action2);                // 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());                // vertical box container        $container = new TVBox;        $container->style = 'width: 90%';        $container->add(new TXMLBreadCrumb('menu.xml', __CLASS__));        $container->add(TPanelGroup::pack('Cadastro de Valores e Percursos', $this->form));        $container->add($this->datagrid);        $container->add($this->pageNavigation);                parent::add($container);    }    /**     * Load the datagrid with data     */    public function onReload($param = NULL)    {        try        {            // open a transaction with database 'moto'            TTransaction::open('moto');                        // creates a repository for TipoPercursos            $repository = new TRepository('TipoPercursos');            $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('TipoPercursos_filter'))            {                // add the filter stored in the session to the criteria                $criteria->add(TSession::getValue('TipoPercursos_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        {            // shows the exception error message            new TMessage('error', '<b>Error</b> ' . $e->getMessage());                        // undo all pending operations            TTransaction::rollback();        }    }        /**     * Ask before deletion     */    public 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);    }        /**     * Delete a record     */    public function Delete($param)    {        try        {            $key=$param['key']; // get the parameter $key            TTransaction::open('moto'); // open a transaction with database            $object = new TipoPercursos($key, FALSE); // instantiates the Active Record            $object->delete(); // deletes the object from the database            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', '<b>Error</b> ' . $e->getMessage()); // shows the exception error message            TTransaction::rollback(); // undo all pending operations        }    }        /**     * Save form data     * @param $param Request     */    public function onSave( $param )    {        try        {            TTransaction::open('moto'); // open a transaction                        /**            // Enable Debug logger for SQL operations inside the transaction            TTransaction::setLogger(new TLoggerSTD); // standard output            TTransaction::setLogger(new TLoggerTXT('log.txt')); // file            **/                        $this->form->validate(); // validate form data                        $object = new TipoPercursos;  // create an empty object            $data = $this->form->getData(); // get form data as array            $object->fromArray( (array) $data); // load the object with data            $object->system_user_id = TSession::getValue('userid');                        if (empty($object->id)) {                $object->create_at = date('Y-m-d H:m:s');            }            $object->updade_at = date('Y-m-d H:m:s');                        $object->store(); // save the object                        // get the generated id            $data->id = $object->id;                        $this->form->setData($data); // fill form 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', $e->getMessage()); // shows the exception error message            $this->form->setData( $this->form->getData() ); // keep form data            TTransaction::rollback(); // undo all pending operations        }    }        /**     * Clear form data     * @param $param Request     */    public function onClear( $param )    {        $this->form->clear(TRUE);    }        /**     * Load object to form data     * @param $param Request     */    public function onEdit( $param )    {        try        {            if (isset($param['key']))            {                $key = $param['key'];  // get the parameter $key                TTransaction::open('moto'); // open a transaction                $object = new TipoPercursos($key); // instantiates the Active Record                $this->form->setData($object); // fill the form                TTransaction::close(); // close the transaction            }            else            {                $this->form->clear(TRUE);            }        }        catch (Exception $e) // in case of exception        {            new TMessage('error', $e->getMessage()); // shows the exception error message            TTransaction::rollback(); // undo all pending operations        }    }        /**     * method show()     * Shows 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();    }}?>

</your>
ST

Marcelo,
Obrigado por sua ajuda.
Saiba que estou na fase inicial da Ferramenta Adianti Framework.
Este é o meu primeiro projeto, por isso estou com dúvidas de como implementar o código.
MG

Tranquilo
Estamos aqui para ajudar.
Você conseguiu entender a lógica?
Isso é o mais importante!
ST

Marcelo,

Não consigo nem gravar a unidade do usuário e nem o usuário no banco de dados.
Sinceramente estou completamente perdido.
Se puder me ajudar a identificar onde estou errando, te agradeceria muito.

Segue o modelo:

<?php/** * Perdcomp Active Record * @author  <your-name-here> */class Perdcomp extends TRecord{    const TABLENAME = 'perdcomp';    const PRIMARYKEY= 'perdcomp_id';    const IDPOLICY =  'max'; // {max, serial}            private $origem_documento;    private $tipo_credito;    private $tipo_documento;    private $tipo_imposto;    private $unit;     /**     * Constructor method     */    public function __construct($id = NULL, $callObjectLoad = TRUE)    {        parent::__construct($id, $callObjectLoad);        parent::addAttribute('DataCriacao');        parent::addAttribute('DataTransmissao');        parent::addAttribute('Sequencial');        parent::addAttribute('Nr_Perdcomp');        parent::addAttribute('TipoDocumento_id');        parent::addAttribute('OrigemDocumento_id');        parent::addAttribute('TipoCredito_id');        parent::addAttribute('SaldoDeclarado');        parent::addAttribute('Exercicio');        parent::addAttribute('TipoImposto_id');        parent::addAttribute('ValorCompensado');        parent::addAttribute('Competencia');        parent::addAttribute('PerdcompOriginal');        parent::addAttribute('Situacao');        parent::addAttribute('Cancelamento');        parent::addAttribute('CreditoOriginalInicial');        parent::addAttribute('CreditoOriginalUtilizadoCompensacoes');        parent::addAttribute('CreditoOriginalDisponivel');        parent::addAttribute('CreditoOriginalTransmissao');        parent::addAttribute('SelicAcumulada');        parent::addAttribute('CreditoAtualizado');        parent::addAttribute('DebitosDocumento');        parent::addAttribute('CreditoOriginalUtilizadoDocumento');        parent::addAttribute('SaldoCreditoOriginal');        parent::addAttribute('system_unit_id');        parent::addAttribute('system_user_id');        parent::addAttribute('Ged');    }            public function get_tipo_credito()    {        if (empty($this->tipo_credito))            $this->tipo_credito = new TipoCredito($this->TipoCredito_id);            return $this->tipo_credito->TipoCreditoDescricao;            }            public function get_tipo_documento()    {        if (empty($this->tipo_documento))            $this->tipo_documento = new TipoDocumento($this->TipoDocumento_id);        return $this->tipo_documento->TipoDocumentoDescricao;    }           public function get_origem_documento()    {        if (empty($this->origem_documento))            $this->origem_documento = new OrigemDocumento($this->OrigemDocumento_id);            return $this->origem_documento->OrigemDocumentoDescricao;            }            public function get_tipo_imposto()    {        if (empty($this->tipo_imposto))            $this->tipo_imposto = new TipoImposto($this->TipoImposto_id);            return $this->tipo_imposto->TipoImpostoDescricao;    }        public function get_unit()    {        // loads the associated object        if (empty($this->unit))            $this->unit = new SystemUnit($this->system_unit_id);            // returns the associated object        return $this->unit;    }}        Formulário:
<?php/** * PerdcompForm Registration * @author  <your name here> */class PerdcompForm extends TPage{    protected $form; // form        use Adianti\Base\AdiantiStandardFormTrait; // Standard form methods        /**     * Class constructor     * Creates the page and the registration form     */    function __construct()    {        parent::__construct();                $this->setDatabase('perdcomp');              // defines the database        $this->setActiveRecord('Perdcomp');     // defines the active record                // creates the form        $this->form = new TQuickForm('form_Perdcomp');        $this->form->class = 'tform'; // change CSS class                $this->form->style = 'display: table;width:100%'; // change style                // define the form title        $this->form->setFormTitle('Perdcomp');                       // create the form fields        $perdcomp_id = new TEntry('perdcomp_id');        $DataCriacao = new TDate('DataCriacao');        $DataTransmissao = new TDate('DataTransmissao');        $Sequencial = new TEntry('Sequencial');        $Nr_Perdcomp = new TEntry('Nr_Perdcomp');        $TipoDocumento_id           = new 
">TDBSeekButton('TipoDocumento_id', 'perdcomp',$this->form->getName(),'TipoDocumento', 'TipoDocumentoDescricao','TipoDocumento_id','tipo_documento');        $TipoDocumentoDescricao   = new TEntry('tipo_documento');        $OrigemDocumento_id       = new 
">TDBSeekButton('OrigemDocumento_id', 'perdcomp', $this->form->getName(), 'OrigemDocumento', 'OrigemDocumentoDescricao', 'OrigemDocumento_id', 'origem_documento');        $OrigemDocumentoDescricao = new TEntry('origem_documento');        $TipoCredito_id       = new 
">TDBSeekButton('TipoCredito_id', 'perdcomp', $this->form->getName(), 'TipoCredito', 'TipoCreditoDescricao', 'TipoCredito_id', 'tipo_credito');        $TipoCreditoDescricao = new TEntry('tipo_credito');        $SaldoDeclarado = new TEntry('SaldoDeclarado');        $Exercicio = new TEntry('Exercicio');        $TipoImposto_id       = new 
">TDBSeekButton('TipoImposto_id', 'perdcomp', $this->form->getName(), 'TipoImposto', 'TipoImpostoDescricao', 'TipoImposto_id', 'tipo_imposto');        $TipoImpostoDescricao = new TEntry('tipo_imposto');        $ValorCompensado = new TEntry('ValorCompensado');        $Competencia = new TDate('Competencia');        $PerdcompOriginal = new TEntry('PerdcompOriginal');        $Situacao = new TEntry('Situacao');        $Cancelamento = new TEntry('Cancelamento');        $CreditoOriginalInicial = new TEntry('CreditoOriginalInicial');        $CreditoOriginalUtilizadoCompensacoes = new TEntry('CreditoOriginalUtilizadoCompensacoes');        $CreditoOriginalDisponivel = new TEntry('CreditoOriginalDisponivel');        $CreditoOriginalTransmissao = new TEntry('CreditoOriginalTransmissao');        $SelicAcumulada = new TEntry('SelicAcumulada');        $CreditoAtualizado = new TEntry('CreditoAtualizado');        $DebitosDocumento = new TEntry('DebitosDocumento');        $CreditoOriginalUtilizadoDocumento = new TEntry('CreditoOriginalUtilizadoDocumento');        $SaldoCreditoOriginal = new TEntry('SaldoCreditoOriginal');      //     $system_unit_id   = new  TDBSeekButton('system_unit_id', 'permission', $this->form->getName(),'SystemUnit', 'name', 'system_unit_id', 'unit'); //       $system_unit = new TEntry('unit');    //$system_unit_id             = new TDBCombo('system_unit_id','permission','SystemUnit','id','name');        $Ged = new TFile('Ged');                // complete upload action                          $TipoDocumentoDescricao->setEditable(FALSE);        $TipoDocumento_id->setSize('40');        $TipoDocumentoDescricao->setSize('500');        $OrigemDocumentoDescricao->setEditable(FALSE);        $OrigemDocumento_id->setSize('40');        $OrigemDocumentoDescricao->setSize('500');        $TipoCreditoDescricao->setEditable(FALSE);        $TipoCredito_id->setSize('40');        $TipoCreditoDescricao->setSize('500');        $TipoImpostoDescricao->setEditable(FALSE);        $TipoImposto_id->setSize('40');        $TipoImpostoDescricao->setSize('500');   //     $system_unit->setEditable(FALSE);     //   $system_unit_id->setSize('40');      //  $system_unit->setSize('500');                    $SaldoDeclarado->setNumericMask(2, ',', '.', TRUE);        $ValorCompensado->setNumericMask(2, ',', '.', TRUE);        $CreditoOriginalInicial->setNumericMask(2, ',', '.', TRUE);        $CreditoOriginalUtilizadoCompensacoes->setNumericMask(2, ',', '.', TRUE);        $CreditoOriginalDisponivel->setNumericMask(2, ',', '.', TRUE);        $CreditoOriginalTransmissao->setNumericMask(2, ',', '.', TRUE);        $SelicAcumulada->setNumericMask(2, ',', '.', TRUE);        $CreditoAtualizado->setNumericMask(2, ',', '.', TRUE);        $DebitosDocumento->setNumericMask(2, ',', '.', TRUE);        $CreditoOriginalUtilizadoDocumento->setNumericMask(2, ',', '.', TRUE);        $SaldoCreditoOriginal->setNumericMask(2, ',', '.', TRUE);        $Nr_Perdcomp->setMask('99999.99999.999999.9.9.99-9999');        $PerdcompOriginal->setMask('99999.99999.999999.9.9.99-9999');        $DataCriacao->setMask('dd/mm/yyyy');        $DataTransmissao->setMask('dd/mm/yyyy');        $Competencia->setMask('dd/mm/yyyy');               // add the fields        $this->form->addQuickField('Código:', $perdcomp_id,  100 );        $this->form->addQuickField('Data Criação:', $DataCriacao,  100 );        $this->form->addQuickField('Data Transmissão:', $DataTransmissao,  100 );        $this->form->addQuickField('Sequencial:', $Sequencial,  200 );        $this->form->addQuickField('Nº Perdcomp:', $Nr_Perdcomp,  200 );        $this->form->addQuickFields('Tipo Documento:', [$TipoDocumento_id,$TipoDocumentoDescricao] );             $this->form->addQuickFields('Origem Documento:', [ $OrigemDocumento_id, $OrigemDocumentoDescricao ] );             $this->form->addQuickFields('Tipo Crédito:', [ $TipoCredito_id, $TipoCreditoDescricao] );             $this->form->addQuickField('Saldo Declarado:', $SaldoDeclarado,  100 );        $this->form->addQuickField('Exercicio:', $Exercicio,  100 );        $this->form->addQuickFields('Tipo Imposto:', [ $TipoImposto_id, $TipoImpostoDescricao] );             $this->form->addQuickField('Valor Compensado:', $ValorCompensado,  100 );        $this->form->addQuickField('Competência:', $Competencia,  100 );        $this->form->addQuickField('Perdcomp Original:', $PerdcompOriginal,  200 );        $this->form->addQuickField('Situação:', $Situacao,  200 );        $this->form->addQuickField('Cancelamento:', $Cancelamento,  200 );        $this->form->addQuickField('Crédito Original Inicial:', $CreditoOriginalInicial,  100 );        $this->form->addQuickField('Crédito Original Utilizado Compensações:', $CreditoOriginalUtilizadoCompensacoes,  100 );        $this->form->addQuickField('Crédito Original Disponível:', $CreditoOriginalDisponivel,  100 );        $this->form->addQuickField('Crédito Original Transmissão:', $CreditoOriginalTransmissao,  100 );        $this->form->addQuickField('Selic Acumulada:', $SelicAcumulada,  100 );        $this->form->addQuickField('Crédito Atualizado:', $CreditoAtualizado,  100 );        $this->form->addQuickField('Débitos Documento:', $DebitosDocumento,  100 );        $this->form->addQuickField('Crédito Original Utilizado Documento:', $CreditoOriginalUtilizadoDocumento,  100 );        $this->form->addQuickField('Saldo Crédito Original:', $SaldoCreditoOriginal,  100);      //  $this->form->addQuickFields('Empresa:', [$system_unit_id,$system_unit], new TRequiredValidator);             $this->form->addQuickField('Ged:', $Ged,  500 );                        if (!empty($perdcomp_id))        {            $perdcomp_id->setEditable(FALSE);        }                        /** samples         $this->form->addQuickFields('Date', array($date1, new TLabel('to'), $date2)); // side by side fields         $fieldX->addValidation( 'Field X', new TRequiredValidator ); // add validation         $fieldX->setSize( 100, 40 ); // set size         **/                 // create the form actions        $this->form->addQuickAction(_t('Save'), new TAction(array($this, 'onSave')), 'fa:floppy-o');        $this->form->addQuickAction(_t('New'),  new TAction(array($this, 'onEdit')), 'bs:plus-sign green');        $this->form->addQuickAction(_t('Back to the listing'), new TAction(array('PerdcompList', 'onReload')), 'fa:table blue');                  // vertical box container        $container = new TVBox;        $container->style = 'width: 90%';        // $container->add(new TXMLBreadCrumb('menu.xml', __CLASS__));        $container->add($this->form);                parent::add($container);                               }        /**     * Save form data     * @param $param Request     */    public function onSave( $param )    {        try        {            TTransaction::open('perdcomp'); // open a transaction                       /**            // Enable Debug logger for SQL operations inside the transaction            TTransaction::setLogger(new TLoggerSTD); // standard output            TTransaction::setLogger(new TLoggerTXT('log.txt')); // file            **/                       $this->form->validate(); // validate form data                       $object = new Perdcomp;  // create an empty object            $data = $this->form->getData(); // get form data as array            $object->fromArray( (array) $data); // load the object with data            $object->DataCriacao = DateTime::createFromFormat('d/m/Y', $object->DataCriacao)->format( 'Y-m-d' );        if (!empty($object->DataTransmissao)) {           $object->DataTransmissao = DateTime::createFromFormat('d/m/Y', $object->DataTransmissao)->format( 'Y-m-d' );       }     if (!empty($object->Competencia)) {                      $object->Competencia = DateTime::createFromFormat('d/m/Y', $object->Competencia)->format( 'Y-m-d' );       }                        $object->system_user_id = TSession::getvalue('userid');            $user = new SystemUser(TSession::getValue('userod'));            $object->system_unit_id = $user->system_unit_id;                        $object->store(); // save the object                       // get the generated id            $data->id = $object->id;                       $this->form->setData($data); // fill form data            TTransaction::close(); // close the transaction                       new TMessage('info', TAdiantiCoreTranslator::translate('Record saved'));        }        catch (Exception $e) // in case of exception        {            new TMessage('error', $e->getMessage()); // shows the exception error message            $this->form->setData( $this->form->getData() ); // keep form data            TTransaction::rollback(); // undo all pending operations        }                       if ($object instanceof Perdcomp)        {            $source_file   = 'tmp/1/'.$object->Ged;            $target_file   = 'images/' . $object->Ged;            $finfo         = new finfo(FILEINFO_MIME_TYPE);                        // if the user uploaded a source file            if (file_exists($source_file) AND ($finfo->file($source_file) == 'image/pdf'))            {                // move to the target directory                rename($source_file, $target_file);                try                {                    TTransaction::open($this->database);                    // update the Ged                    $object->Ged = 'images/'.$object->Ged;                    $object->store();                                        TTransaction::close();                }                catch (Exception $e) // in case of exception                {                    new TMessage('error', $e->getMessage());                    TTransaction::rollback();                }            }        }    }       /**     * Clear form data     * @param $param Request     */         public function onClear( $param )    {        $this->form->clear();    }       /**     * Load object to form data     * @param $param Request     */    public function onEdit( $param )    {        try        {            if (isset($param['key']))            {                $key = $param['key'];  // get the parameter $key                TTransaction::open('perdcomp'); // open a transaction                $object = new Perdcomp($key); // instantiates the Active Record                $object->DataCriacao = DateTime::createFromFormat('Y-m-d', $object->DataCriacao)->format( 'd/m/Y' );        if (!empty($object->DataTransmissao)) {              $object->DataTransmissao = DateTime::createFromFormat('Y-m-d', $object->DataTransmissao)->format( 'd/m/Y' );            }        if (!empty($object->Competencia)) {              $object->Competencia = DateTime::createFromFormat('Y-m-d', $object->Competencia)->format( 'd/m/Y' );              }                              $this->form->setData($object); // fill the form                TTransaction::close(); // close the transaction            }            else            {                $this->form->clear();            }        }        catch (Exception $e) // in case of exception        {            new TMessage('error', $e->getMessage()); // shows the exception error message            TTransaction::rollback(); // undo all pending operations        }    }      }Datagrid:
<?php/** * PerdcompList Listing * @author  <your name here> */class PerdcompList extends TStandardList{    protected $form;     // registration form    protected $datagrid; // listing    protected $pageNavigation;    protected $formgrid;    protected $deleteButton;    protected $transformCallback;        /**     * Page constructor     */    public function __construct()    {        parent::__construct();                parent::setDatabase('perdcomp');            // defines the database        parent::setActiveRecord('Perdcomp');   // defines the active record        parent::setDefaultOrder('perdcomp_id', 'asc');         // defines the default order        // parent::setCriteria($criteria) // define a standard filter        parent::addFilterField('perdcomp_id', '=', 'perdcomp_id'); // filterField, operator, formField        parent::addFilterField('DataCriacao', 'like', 'DataCriacao'); // filterField, operator, formField        parent::addFilterField('DataTransmissao', 'like', 'DataTransmissao'); // filterField, operator, formField        parent::addFilterField('Sequencial', 'like', 'Sequencial'); // filterField, operator, formField        parent::addFilterField('Nr_Perdcomp', 'like', 'Nr_Perdcomp'); // filterField, operator, formField        parent::addFilterField('TipoDocumento_id', 'like', 'TipoDocumento_id'); // filterField, operator, formField        parent::addFilterField('OrigemDocumento_id', 'like', 'OrigemDocumento_id'); // filterField, operator, formField        parent::addFilterField('TipoCredito_id', 'like', 'TipoCredito_id'); // filterField, operator, formField        parent::addFilterField('SaldoDeclarado', 'like', 'SaldoDeclarado'); // filterField, operator, formField        parent::addFilterField('Exercicio', 'like', 'Exercicio'); // filterField, operator, formField        parent::addFilterField('TipoImposto_id', 'like', 'TipoImposto_id'); // filterField, operator, formField                // creates the form        $this->form = new TQuickForm('form_search_Perdcomp');        $this->form->class = 'tform'; // change CSS class                $this->form->style = 'display: table;width:100%'; // change style        $this->form->setFormTitle('Filtro Perdcomp');                // create the form fields        $perdcomp_id = new TEntry('perdcomp_id');        $DataCriacao = new TDate('DataCriacao');        $DataTransmissao = new TDate('DataTransmissao');        $Nr_Perdcomp = new TEntry('Nr_Perdcomp');        $TipoDocumento_id       = new 
">TDBSeekButton('TipoDocumento_id', 'perdcomp', $this->form->getName(), 'TipoDocumento', 'TipoDocumentoDescricao', 'TipoDocumento_id', 'tipo_documento');        $TipoDocumentoDescricao = new TEntry('tipo_documento');        $TipoCredito_id       = new 
">TDBSeekButton('TipoCredito_id', 'perdcomp', $this->form->getName(), 'TipoCredito', 'TipoCreditoDescricao', 'TipoCredito_id', 'tipo_credito');        $TipoCreditoDescricao = new TEntry('tipo_credito');        $OrigemDocumento_id       = new 
">TDBSeekButton('OrigemDocumento_id', 'perdcomp', $this->form->getName(), 'OrigemDocumento', 'OrigemDocumentoDescricao', 'OrigemDocumento_id', 'origem_documento');        $OrigemDocumentoDescricao = new TEntry('origem_documento');        $TipoImposto_id       = new 
">TDBSeekButton('TipoImposto_id', 'perdcomp', $this->form->getName(), 'TipoImposto', 'TipoImpostoDescricao', 'TipoImposto_id', 'tipo_imposto');        $TipoImpostoDescricao = new TEntry('tipo_imposto');        $Exercicio = new TEntry('Exercicio');               $TipoDocumentoDescricao->setEditable(FALSE);        $TipoDocumento_id->setSize('40');        $TipoDocumentoDescricao->setSize('500');                $TipoCreditoDescricao->setEditable(FALSE);        $TipoCredito_id->setSize('40');        $TipoCreditoDescricao->setSize('500');                $OrigemDocumentoDescricao->setEditable(FALSE);        $OrigemDocumento_id->setSize('40');        $OrigemDocumentoDescricao->setSize('500');             $TipoImpostoDescricao->setEditable(FALSE);        $TipoImposto_id->setSize('40');        $TipoImpostoDescricao->setSize('500');        // add the fields        $this->form->addQuickField('Código:', $perdcomp_id,  80 );        $this->form->addQuickField('Data Criação', $DataCriacao,  80 );        $this->form->addQuickField('Data Transmissão:', $DataTransmissao,  80 );        $this->form->addQuickField('Nº Perdcomp:', $Nr_Perdcomp,  500 );        $this->form->addQuickFields('Tipo Documento:', [ $TipoDocumento_id, $TipoDocumentoDescricao ] );             $this->form->addQuickFields('Tipo Crédito:', [ $TipoCredito_id, $TipoCreditoDescricao] );             $this->form->addQuickFields('Origem Documento:', [ $OrigemDocumento_id, $OrigemDocumentoDescricao ] );             $this->form->addQuickFields('Tipo Imposto:', [ $TipoImposto_id, $TipoImpostoDescricao] );             $this->form->addQuickField('Exercício', $Exercicio,  100 );                    // keep the form filled during navigation with session data        $this->form->setData( TSession::getValue('Perdcomp_filter_data') );                        // add the search form actions        $this->form->addQuickAction(_t('Find'), new TAction(array($this, 'onSearch')), 'fa:search');        $this->form->addQuickAction(_t('New'),  new TAction(array('PerdcompForm', 'onEdit')), 'bs:plus-sign green');                // creates a DataGrid        $this->datagrid = new TDataGrid;          // $this->datagrid->enablePopover('Image', "<img src='{photo_path}'>");                $this->datagrid->style = 'width: 100%';        $this->datagrid->datatable = 'true';       // $this->datagrid->enablePopover('Popover', 'Hi <b> {name} </b>');                // creates the datagrid columns        $column_check = new TDataGridColumn('check', '', 'center');        $column_perdcomp_id = new TDataGridColumn('perdcomp_id', 'Código', 'right');        $column_DataCriacao = new TDataGridColumn('DataCriacao', 'Data Criação', 'left');        $column_DataTransmissao = new TDataGridColumn('DataTransmissao', 'Data Transmissão', 'left');        $column_Nr_Perdcomp = new TDataGridColumn('Nr_Perdcomp', 'Nº Perdcomp', 'left');        $column_TipoDocumento_id = new TDataGridColumn('tipo_documento', 'Tipo Documento', 'left');        $column_TipoCredito_id = new TDataGridColumn('tipo_credito', 'Tipo Crédito', 'left');        $column_TipoImposto_id = new TDataGridColumn('tipo_imposto', 'Tipo Imposto', 'left');        $column_OrigemDocumento_id = new TDataGridColumn('origem_documento', 'Origem Documento', 'left');        $column_SaldoDeclarado = new TDataGridColumn('SaldoDeclarado', 'Saldo Declarado', 'right');        $column_Exercicio = new TDataGridColumn('Exercicio', 'Exercício', 'right');        $column_ValorCompensado = new TDataGridColumn('ValorCompensado', 'Valor Compensado', 'right');        $column_Sequencial = new TDataGridColumn('Sequencial', 'Sequencial', 'left');        $column_Competencia = new TDataGridColumn('Competencia', 'Competência', 'left');        $column_PerdcompOriginal = new TDataGridColumn('PerdcompOriginal', 'Perdcomp Original', 'left');        $column_Situacao = new TDataGridColumn('Situacao', 'Situação', 'left');        $column_Cancelamento = new TDataGridColumn('Cancelamento', 'Cancelamento', 'left');        $column_CreditoOriginalInicial = new TDataGridColumn('CreditoOriginalInicial', 'Crédito Original Inicial', 'right');        $column_CreditoOriginalUtilizadoCompensacoes = new TDataGridColumn('Credito Original Utilizado Compensações', 'Creditooriginalutilizadocompensacoes', 'right');        $column_CreditoOriginalDisponivel = new TDataGridColumn('Crédito Original Disponível', 'Crédito Original Disponível', 'right');        $column_CreditoOriginalTransmissao = new TDataGridColumn('Credito Original Transmissão', 'Crédito Original Transmissão', 'right');        $column_SelicAcumulada = new TDataGridColumn('Selic Acumulada', 'Selic Acumulada', 'right');        $column_CreditoAtualizado = new TDataGridColumn('CreditoAtualizado', 'Crédito Atualizado', 'right');        $column_DebitosDocumento = new TDataGridColumn('DebitosDocumento', 'Débitos Documento', 'right');        $column_CreditoOriginalUtilizadoDocumento = new TDataGridColumn('CreditoOriginalUtilizadoDocumento', 'Crédito Original Utilizado Documento', 'right');        $column_SaldoCreditoOriginal = new TDataGridColumn('SaldoCreditoOriginal', 'Saldo Crédito Original', 'right');        $column_system_unit_id = new TDataGridColumn('system_unit_id', 'Empresa', 'right');        $column_Ged = new TDataGridColumn('Ged', 'Ged', 'left');              // add the columns to the DataGrid        $this->datagrid->addColumn($column_check);        $this->datagrid->addColumn($column_perdcomp_id);        $this->datagrid->addColumn($column_DataCriacao);        $this->datagrid->addColumn($column_DataTransmissao);        $this->datagrid->addColumn($column_Sequencial);        $this->datagrid->addColumn($column_Nr_Perdcomp);        $this->datagrid->addColumn($column_TipoDocumento_id);        $this->datagrid->addColumn($column_OrigemDocumento_id);        $this->datagrid->addColumn($column_TipoCredito_id);        $this->datagrid->addColumn($column_TipoImposto_id);        $this->datagrid->addColumn($column_SaldoDeclarado);        $this->datagrid->addColumn($column_ValorCompensado);        $this->datagrid->addColumn($column_Exercicio);        $this->datagrid->addColumn($column_Competencia);        $this->datagrid->addColumn($column_PerdcompOriginal);        $this->datagrid->addColumn($column_Situacao);        $this->datagrid->addColumn($column_Cancelamento);        $this->datagrid->addColumn($column_CreditoOriginalInicial);        $this->datagrid->addColumn($column_CreditoOriginalUtilizadoCompensacoes);        $this->datagrid->addColumn($column_CreditoOriginalDisponivel);        $this->datagrid->addColumn($column_CreditoOriginalTransmissao);        $this->datagrid->addColumn($column_SelicAcumulada);        $this->datagrid->addColumn($column_CreditoAtualizado);        $this->datagrid->addColumn($column_DebitosDocumento);        $this->datagrid->addColumn($column_CreditoOriginalUtilizadoDocumento);        $this->datagrid->addColumn($column_SaldoCreditoOriginal);        $this->datagrid->addColumn($column_Ged);        $this->datagrid->addColumn($column_system_unit_id);                        $order_perdcomp_id = new TAction(array($this, 'onReload'));        $order_perdcomp_id->setParameter('order', 'perdcomp_id');        $column_perdcomp_id->setAction($order_perdcomp_id);                $order_DataCriacao = new TAction(array($this, 'onReload'));        $order_DataCriacao->setParameter('order', 'DataCriacao');        $column_DataCriacao->setAction($order_DataCriacao);                $order_DataTransmissao = new TAction(array($this, 'onReload'));        $order_DataTransmissao->setParameter('order', 'DataTransmissao');        $column_DataTransmissao->setAction($order_DataTransmissao);              // define the transformer method over image                            $column_Ged->setTransformer(function($value, $object, $row){          $link = new THyperLink($value,'tmp/1/' . $value, 'blue', 12, 'biu');           return $link;    });           $column_Competencia->setTransformer( function($value, $object, $row) {            $date = new DateTime($value);            return $date->format('d/m/Y');        });          // define the transformer method over image        $column_DataCriacao->setTransformer( function($value, $object, $row) {            $date = new DateTime($value);            return $date->format('d/m/Y');        });        // define the transformer method over image        $column_DataTransmissao->setTransformer( function($value, $object, $row) {            $date = new DateTime($value);            return $date->format('d/m/Y');        });                          // define the transformer method over image        $column_SaldoDeclarado->setTransformer( function($value, $object, $row) {            return 'R$ ' . number_format($value, 2, ',', '.');        });        // define the transformer method over image        $column_ValorCompensado->setTransformer( function($value, $object, $row) {            return 'R$ ' . number_format($value, 2, ',', '.');        });        // define the transformer method over image        $column_CreditoOriginalInicial->setTransformer( function($value, $object, $row) {            return 'R$ ' . number_format($value, 2, ',', '.');        });        // define the transformer method over image        $column_CreditoOriginalUtilizadoCompensacoes->setTransformer( function($value, $object, $row) {            return 'R$ ' . number_format($value, 2, ',', '.');        });        // define the transformer method over image        $column_CreditoOriginalDisponivel->setTransformer( function($value, $object, $row) {            return 'R$ ' . number_format($value, 2, ',', '.');        });        // define the transformer method over image        $column_CreditoOriginalTransmissao->setTransformer( function($value, $object, $row) {            return 'R$ ' . number_format($value, 2, ',', '.');        });        // define the transformer method over image        $column_CreditoAtualizado->setTransformer( function($value, $object, $row) {            return 'R$ ' . number_format($value, 2, ',', '.');        });        // define the transformer method over image        $column_DebitosDocumento->setTransformer( function($value, $object, $row) {            return 'R$ ' . number_format($value, 2, ',', '.');        });        // define the transformer method over image        $column_CreditoOriginalUtilizadoDocumento->setTransformer( function($value, $object, $row) {            return 'R$ ' . number_format($value, 2, ',', '.');        });        // define the transformer method over image        $column_SaldoCreditoOriginal->setTransformer( function($value, $object, $row) {            return 'R$ ' . number_format($value, 2, ',', '.');        });                // create EDIT action        $action_edit = new TDataGridAction(array('PerdcompForm', 'onEdit'));        $action_edit->setButtonClass('btn btn-default');        $action_edit->setLabel(_t('Edit'));        $action_edit->setImage('fa:pencil-square-o blue fa-lg');        $action_edit->setField('perdcomp_id');        $this->datagrid->addAction($action_edit);                          // create DELETE action        $action_del = new TDataGridAction(array($this, 'onDelete'));        $action_del->setButtonClass('btn btn-default');        $action_del->setLabel(_t('Delete'));        $action_del->setImage('fa:trash-o red fa-lg');        $action_del->setField('perdcomp_id');        $this->datagrid->addAction($action_del);                    // create the datagrid model        $this->datagrid->createModel();                // create the page navigation        $this->pageNavigation = new TPageNavigation;        $this->pageNavigation->setAction(new TAction(array($this, 'onReload')));        $this->pageNavigation->setWidth($this->datagrid->getWidth());                 $this->datagrid->disableDefaultClick();                // put datagrid inside a form        $this->formgrid = new TForm;        $this->formgrid->add($this->datagrid);                // creates the delete collection button        $this->deleteButton = new TButton('delete_collection');        $this->deleteButton->setAction(new TAction(array($this, 'onDeleteCollection')), AdiantiCoreTranslator::translate('Delete selected'));        $this->deleteButton->setImage('fa:remove red');        $this->formgrid->addField($this->deleteButton);                $gridpack = new TVBox;        $gridpack->style = 'width: 100%';        $gridpack->add($this->formgrid);        $gridpack->add($this->deleteButton)->style = 'background:whiteSmoke;border:1px solid #cccccc; padding: 3px;padding: 5px;';                $this->transformCallback = array($this, 'onBeforeLoad');        // vertical box container        $container = new TVBox;        $container->style = 'width: 90%';        // $container->add(new TXMLBreadCrumb('menu.xml', __CLASS__));        $container->add($this->form);       // $container->add($this->datagrid);        $container->add($gridpack);        $container->add($this->pageNavigation);                parent::add($container);    }        public function onBeforeLoad($objects, $param)    {        // update the action parameters to pass the current page to action        // without this, the action will only work for the first page        $deleteAction = $this->deleteButton->getAction();        $deleteAction->setParameters($param); // important!                $gridfields = array( $this->deleteButton );                foreach ($objects as $object)        {            $object->check = new TCheckButton('check' . $object->perdcomp_id);            $object->check->setIndexValue('on');            $gridfields[] = $object->check; // important        }                $this->formgrid->setFields($gridfields);    }}   </your></your>
ST

Marcelo,

O usuário está gravando no banco de dados, apenas a unidade não está gravando.
MG

Bom dia.

Dá uma olhada no seu código.

O "userid" está errado quando tentar buscar os dados, veja parte do seu código abaixo, você usou "userod".

<?php        $object->system_user_id = TSession::getvalue('userid');        $user = new SystemUser(TSession::getValue('userod')); // <==== correto é "userid"        $object->system_unit_id = $user->system_unit_id;?>
ST

Marcelo,

Problema resolvido. Muitíssimo obrigado.

Gostaria de filtrar os dados do datagrid pela unidade, como faço isto?
MG

Você usa TCriteria no método onReload.

Quando você cria um TDataGrid pelo Adianti Studio ele cria um método onReload.

Neste método existe alguns filtros que podem vir da tela de pesquisa básica que ele criar.

Modifique este método e adicione os critérios desejados.
ST

Marcelo,
Este é o meu primeiro projeto.
Não sei ainda como utilizar o Tcriteria.
Poderia, por favor, me passaram um exemplo.
MG

Sebastião, vai um trecho de código a respeito deste assunto.
Trata-se de um método onReload().

Neste caso seu model contém o campo "system_group_id", correto e tão vamos ao método e uso do TCriteria.

<?php    /**     * Load the datagrid with data     */    public function onReload($param = NULL)    {        try        {            // open a transaction with database 'moto'            TTransaction::open('moto');                        // creates a repository for TipoDespesas            $repository = new TRepository('TipoDespesas');            $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('TipoDespesas_filter'))            {                // add the filter stored in the session to the criteria                $criteria->add(TSession::getValue('TipoDespesas_filter'));            }                        // filtra por grupo            $criteria-add("system_group_id","=",$param['system_group_id']); // aqui vc adiciona o TCriteria que deve valer para todo o TDataGrid            // 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        {            // shows the exception error message            new TMessage('error', '<b>Error</b> ' . $e->getMessage());                        // undo all pending operations            TTransaction::rollback();        }    }?>
MG

Veja na linha 35.
Vc deve localizar seu método onReload e implementar o TCriteria.
ST

Marcelo,
No formulário do datagrid não tem o método on Reload.
Tem o método onBeforeLoad.
MG

Implemente nele.
Literalmente o método diz "Antes de Ler".
ST

Problema resolvido.
Obrigado Marcelo.