HL
Form de cadastro Não vincula passagem de alguns dados com DB
Estou tentado cadastra pessoas mas, só estar sendo vinculado com base de dados (id,cidade, dt_criação e grupo_id).O resto não esta sendo cadastrado tipo nome, telefone,email...O que poder esta dando de errado ao vincular dados do form com DB?
- <?php
- /**
- * Pessoa Active Record
- * @author <your-name-here>
- */
- class Pessoa extends TRecord
- {
- const TABLENAME = 'tb_pessoa';
- const PRIMARYKEY = 'id';
- const IDPOLICY = 'max'; // {max, serial}
- const CREATEDAT = 'hr_created_at';
- const UPDATEDAT = 'hr_updated_at';
- /**
- * Constructor method
- */
- public function __construct($id = NULL, $callObjectLoad = TRUE)
- {
- parent::__construct($id, $callObjectLoad);
- parent::addAttribute('no_nome');
- parent::addAttribute('no_nome_fantasia');
- parent::addAttribute('st_tipo');
- parent::addAttribute('nu_codigo_nacional');
- parent::addAttribute('nu_codigo_estadual');
- parent::addAttribute('nu_codigo_municipal');
- parent::addAttribute('nu_fone');
- parent::addAttribute('no_email');
- parent::addAttribute('ds_observacao');
- parent::addAttribute('nu_cep');
- parent::addAttribute('no_logradouro');
- parent::addAttribute('nu_numero');
- parent::addAttribute('no_complemento');
- parent::addAttribute('no_bairro');
- parent::addAttribute('municipio_id');
- parent::addAttribute('hr_created_at');
- parent::addAttribute('hr_updated_at');
- parent::addAttribute('grupo_id');
- }
- public function get_cidade()
- {
- return Cidade::find($this->municipio_id);
- }
- public function get_grupo()
- {
- return Grupo::find($this->grupo_id);
- }
- public function delete($id = null)
- {
- $id = isset($id) ? $id : $this->id;
- PessoaPapel::where('pessoa_id', '=', $this->id)->delete();
- parent::delete($id);
- }
- }
- /* Pessoa Form
- <?php
- /**
- * PessoaForm
- *
- * @version 1.0
- * @license http://www.adianti.com.br/framework-license
- */
- class PessoaForm extends TWindow
- {
- protected $form; // form
- /**
- * Form constructor
- * @param $param Request
- */
- public function __construct( $param )
- {
- parent::__construct();
- parent::setSize(0.8, null);
- parent::removePadding();
- parent::removeTitleBar();
- //parent::disableEscape();
- // creates the form
- $this->form = new BootstrapFormBuilder('form_Pessoa');
- $this->form->setFormTitle('Pessoa');
- $this->form->setProperty('style', 'margin:0;border:0');
- $this->form->setClientValidation(true);
- // create the form fields
- $id = new TEntry('id');
- $nome = new TEntry('nome');
- $nome_fantasia = new TEntry('nome_fantasia');
- $tipo = new TCombo('tipo');
- $codigo_nacional = new TEntry('codigo_nacional');
- $codigo_estadual = new TEntry('codigo_estadual');
- $codigo_municipal = new TEntry('codigo_municipal');
- $fone = new TEntry('fone');
- $email = new TEntry('email');
- $observacao = new TText('observacao');
- $cep = new TEntry('cep');
- $logradouro = new TEntry('logradouro');
- $numero = new TEntry('numero');
- $complemento = new TEntry('complemento');
- $bairro = new TEntry('bairro');
- $filter = new TCriteria;
- $filter->add(new TFilter('id', '<', '0'));
- $cidade_id = new TDBCombo('municipio_id', 'sys_db', 'Cidade', 'id', 'no_nome', 'no_nome', $filter);
- $grupo_id = new TDBUniqueSearch('grupo_id', 'sys_db', 'Grupo', 'id', 'no_nome');
- $papeis_id = new TDBMultiSearch('papeis_id', 'sys_db', 'Papel', 'id', 'no_nome');
- $estado_id = new TDBCombo('estado_id', 'sys_db', 'Estado', 'id', '{no_nome} ({sg_uf})');
- $estado_id->setChangeAction( new TAction( [$this, 'onChangeEstado'] ) );
- $cep->setExitAction( new TAction([ $this, 'onExitCEP']) );
- $codigo_nacional->setExitAction( new TAction( [$this, 'onExitCNPJ'] ) );
- $cidade_id->enableSearch();
- $estado_id->enableSearch();
- $grupo_id->setMinLength(0);
- $papeis_id->setMinLength(0);
- $papeis_id->setSize('100%', 60);
- $observacao->setSize('100%', 60);
- $tipo->addItems( ['F' => 'Física', 'J' => 'Jurídica' ] );
- // add the fields
- $this->form->addFields( [ new TLabel('Id') ], [ $id ] );
- $this->form->addFields( [ new TLabel('Tipo') ], [ $tipo ], [ new TLabel('CPF/CNPJ') ], [ $codigo_nacional ] );
- $this->form->addFields( [ new TLabel('Nome') ], [ $nome ] );
- $this->form->addFields( [ new TLabel('Nome Fantasia') ], [ $nome_fantasia ] );
- $this->form->addFields( [ new TLabel('Papéis')], [ $papeis_id ], [ new TLabel('Grupo') ], [ $grupo_id ] );
- $this->form->addFields( [ new TLabel('I.E.') ], [ $codigo_estadual ], [ new TLabel('I.M.') ], [ $codigo_municipal ] );
- $this->form->addFields( [ new TLabel('Fone') ], [ $fone ], [ new TLabel('Email') ], [ $email ] );
- $this->form->addFields( [ new TLabel('Observacao') ], [ $observacao ] );
- $this->form->addContent( [new TFormSeparator('Endereço')]);
- $this->form->addFields( [ new TLabel('Cep') ], [ $cep ] )->layout = ['col-sm-2 control-label', 'col-sm-4'];
- $this->form->addFields( [ new TLabel('Logradouro') ], [ $logradouro ], [ new TLabel('Numero') ], [ $numero ] );
- $this->form->addFields( [ new TLabel('Complemento') ], [ $complemento ], [ new TLabel('Bairro') ], [ $bairro ] );
- $this->form->addFields( [ new TLabel('Estado') ], [$estado_id], [ new TLabel('Cidade') ], [ $cidade_id ] );
- // adiciona as validações
- $codigo_nacional->addValidation('Tipo', new TNumericValidator);
- // set sizes
- $id->setSize('100%');
- $nome->setSize('100%');
- $nome_fantasia->setSize('100%');
- $tipo->setSize('100%');
- $codigo_nacional->setSize('100%');
- $codigo_estadual->setSize('100%');
- $codigo_municipal->setSize('100%');
- $fone->setSize('100%');
- $email->setSize('100%');
- $observacao->setSize('100%');
- $cep->setSize('100%');
- $logradouro->setSize('100%');
- $numero->setSize('100%');
- $complemento->setSize('100%');
- $bairro->setSize('100%');
- $cidade_id->setSize('100%');
- $grupo_id->setSize('100%');
- $cep->setMask('99.999-999');
- $id->setEditable(FALSE);
- $nome->addValidation('Nome', new TRequiredValidator);
- $nome_fantasia->addValidation('Nome Fantasia', new TRequiredValidator);
- $tipo->addValidation('Tipo', new TRequiredValidator);
- $codigo_nacional->addValidation('CPF/CNPJ', new TRequiredValidator);
- $grupo_id->addValidation('Grupo', new TRequiredValidator);
- $fone->addValidation('Fone', new TRequiredValidator);
- $email->addValidation('Email', new TRequiredValidator);
- $email->addValidation('Email', new TEmailValidator);
- $cidade_id->addValidation('Cidade', new TRequiredValidator);
- $cep->addValidation('CEP', new TRequiredValidator);
- $logradouro->addValidation('Logradouro', new TRequiredValidator);
- $numero->addValidation('Número', new TRequiredValidator);
- // create the form actions
- $this->form->addHeaderActionLink( _t('Close'), new TAction([__CLASS__, 'onClose'], ['static'=>'1']), 'fa:times red');
- $btn = $this->form->addAction(_t('Save'), new TAction([$this, 'onSave']), 'fa:save');
- $btn->class = 'btn btn-sm btn-primary';
- $this->form->addActionLink(_t('New'), new TAction([$this, 'onEdit']), 'fa:eraser red');
- // vertical box container
- $container = new TVBox;
- $container->style = 'width: 100%';
- // $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('sys_db'); // open a transaction
- $this->form->validate(); // validate form data
- $data = $this->form->getData(); // get form data as array
- $object = new Pessoa; // create an empty object
- $object->fromArray( (array) $data); // load the object with data
- $object->store(); // save the object
- var_dump($object);
- PessoaPapel::where('pessoa_id', '=', $object->id)->delete();
- if ($data->papeis_id)
- {
- foreach ($data->papeis_id as $papel_id)
- {
- $pp = new PessoaPapel;
- $pp->pessoa_id = $object->id;
- $pp->papel_id = $papel_id;
- $pp->store();
- }
- }
- // get the generated id
- $data->id = $object->id;
- $this->form->setData($data); // fill form data
- TTransaction::close(); // close the transaction
- new TMessage('info', AdiantiCoreTranslator::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
- }
- }
- /**
- * 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'];
- TTransaction::open('sys_db');
- $object = new Pessoa($key);
- $object->papeis_id = PessoaPapel::where('pessoa_id', '=', $object->id)->getIndexedArray('papel_id');
- $this->form->setData($object);
- // force fire events
- $data = new stdClass;
- $data->estado_id = $object->cidade->estado->id;
- $data->municipio_id = $object->municipio_id;
- TForm::sendData('form_Pessoa', $data);
- TTransaction::close();
- }
- 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
- }
- }
- /**
- * Action to be executed when the user changes the state
- * @param $param Action parameters
- */
- public static function onChangeEstado($param)
- {
- try
- {
- TTransaction::open('sys_db');
- if (!empty($param['estado_id']))
- {
- $criteria = TCriteria::create( ['estado_id' => $param['estado_id'] ] );
- // formname, field, database, model, key, value, ordercolumn = NULL, criteria = NULL, startEmpty = FALSE
- TDBCombo::reloadFromModel('form_Pessoa', 'municipio_id', 'sys_db', 'Cidade', 'id', '{no_nome} ({id})', 'no_nome', $criteria, TRUE);
- }
- else
- {
- TCombo::clearField('form_Pessoa', 'municipio_id');
- }
- TTransaction::close();
- }
- catch (Exception $e)
- {
- new TMessage('error', $e->getMessage());
- }
- }
- /**
- * Autocompleta outros campos a partir do CNPJ
- */
- public static function onExitCNPJ($param)
- {
- session_write_close();
- try
- {
- $cnpj = preg_replace('/[^0-9]/', '', $param['codigo_nacional']);
- $url = 'http://receitaws.com.br/v1/cnpj/'.$cnpj;
- $content = @file_get_contents($url);
- if ($content !== false)
- {
- $cnpj_data = json_decode($content);
- $data = new stdClass;
- if (is_object($cnpj_data) && $cnpj_data->status !== 'ERROR')
- {
- $data->tipo = 'J';
- $data->nome = $cnpj_data->nome;
- $data->nome_fantasia = !empty($cnpj_data->fantasia) ? $cnpj_data->fantasia : $cnpj_data->nome;
- if (empty($param['cep']))
- {
- $data->cep = $cnpj_data->cep;
- $data->numero = $cnpj_data->numero;
- }
- if (empty($param['fone']))
- {
- $data->fone = $cnpj_data->telefone;
- }
- if (empty($param['email']))
- {
- $data->email = $cnpj_data->email;
- }
- TForm::sendData('form_Pessoa', $data, false, true);
- }
- else
- {
- $data->nome = '';
- $data->nome_fantasia = '';
- $data->cep = '';
- $data->numero = '';
- $data->telefone = '';
- $data->email = '';
- TForm::sendData('form_Pessoa', $data, false, true);
- }
- }
- }
- catch (Exception $e)
- {
- new TMessage('error', $e->getMessage());
- }
- }
- /**
- * Autocompleta outros campos a partir do CEP
- */
- public static function onExitCEP($param)
- {
- session_write_close();
- try
- {
- $cep = preg_replace('/[^0-9]/', '', $param['cep']);
- $url = 'https://viacep.com.br/ws/'.$cep.'/json/unicode/';
- $content = @file_get_contents($url);
- if ($content !== false)
- {
- $cep_data = json_decode($content);
- $data = new stdClass;
- if (is_object($cep_data) && empty($cep_data->erro))
- {
- TTransaction::open('sys_db');
- $estado = Estado::where('sg_uf', '=', $cep_data->uf)->first();
- $cidade = Cidade::where('id', '=', $cep_data->ibge)->first();
- TTransaction::close();
- $data->logradouro = $cep_data->logradouro;
- $data->complemento = $cep_data->complemento;
- $data->bairro = $cep_data->bairro;
- $data->estado_id = $estado->id ?? '';
- $data->municipio_id = $cidade->id ?? '';
- TForm::sendData('form_Pessoa', $data, false, true);
- }
- else
- {
- $data->logradouro = '';
- $data->complemento = '';
- $data->bairro = '';
- $data->estado_id = '';
- $data->municipio_id = '';
- TForm::sendData('form_Pessoa', $data, false, true);
- }
- }
- }
- catch (Exception $e)
- {
- new TMessage('error', $e->getMessage());
- }
- }
- /**
- * Closes window
- */
- public static function onClose()
- {
- parent::closeWindow();
- }
- }
- /* PessoaList */
- <?php
- /**
- * PessoaList
- *
- * @version 1.0
- * @license http://www.adianti.com.br/framework-license
- */
- class PessoaList extends TPage
- {
- protected $form; // registration form
- protected $datagrid; // listing
- protected $pageNavigation;
- protected $formgrid;
- protected $deleteButton;
- use Adianti\base\AdiantiStandardListTrait;
- /**
- * Page constructor
- */
- public function __construct()
- {
- parent::__construct();
- $this->setDatabase('sys_db'); // defines the database
- $this->setActiveRecord('Pessoa'); // defines the active record
- $this->setDefaultOrder('id', 'asc'); // defines the default order
- $this->setLimit(10);
- // $this->setCriteria($criteria) // define a standard filter
- $this->addFilterField('id', '=', 'id'); // filterField, operator, formField
- $this->addFilterField('no_nome_fantasia', 'like', 'nome_fantasia'); // filterField, operator, formField
- $this->addFilterField('nu_fone', 'like', 'fone'); // filterField, operator, formField
- $this->addFilterField('no_email', 'like', 'email'); // filterField, operator, formField
- $this->addFilterField('grupo_id', '=', 'grupo_id'); // filterField, operator, formField
- // creates the form
- $this->form = new BootstrapFormBuilder('form_search_Pessoa');
- $this->form->setFormTitle('Pessoa');
- // create the form fields
- $id = new TEntry('id');
- $nome_fantasia = new TEntry('nome_fantasia');
- $fone = new TEntry('fone');
- $email = new TEntry('email');
- $grupo_id = new TDBUniqueSearch('grupo_id', 'sys_db', 'Grupo', 'id', 'no_nome');
- $grupo_id->setMinLength(0);
- // add the fields
- $this->form->addFields( [ new TLabel('Id') ], [ $id ] );
- $this->form->addFields( [ new TLabel('Nome Fantasia') ], [ $nome_fantasia ] );
- $this->form->addFields( [ new TLabel('Fone') ], [ $fone ] );
- $this->form->addFields( [ new TLabel('Email') ], [ $email ] );
- $this->form->addFields( [ new TLabel('Grupo') ], [ $grupo_id ] );
- // set sizes
- $id->setSize('100%');
- $nome_fantasia->setSize('100%');
- $fone->setSize('100%');
- $email->setSize('100%');
- $grupo_id->setSize('100%');
- // keep the form filled during navigation with session data
- $this->form->setData( TSession::getValue(__CLASS__.'_filter_data') );
- // add the search form actions
- $btn = $this->form->addAction(_t('Find'), new TAction([$this, 'onSearch']), 'fa:search');
- $btn->class = 'btn btn-sm btn-primary';
- $this->form->addActionLink(_t('New'), new TAction(['PessoaForm', 'onEdit']), 'fa:plus green');
- // creates a Datagrid
- $this->datagrid = new BootstrapDatagridWrapper(new TDataGrid);
- $this->datagrid->style = 'width: 100%';
- //$this->datagrid->datatable = 'true';
- // $this->datagrid->enablePopover('Popover', 'Hi <b> {name} </b>');
- // creates the datagrid columns
- $column_id = new TDataGridColumn('id', 'Id', 'left');
- $column_nome_fantasia = new TDataGridColumn('no_nome_fantasia', 'Nome Fantasia', 'left');
- $column_fone = new TDataGridColumn('nu_fone', 'Fone', 'left');
- $column_email = new TDataGridColumn('no_email', 'Email', 'left');
- $column_grupo_id = new TDataGridColumn('grupo->no_nome', 'Grupo', 'left');
- $column_fone->enableAutoHide(500);
- $column_email->enableAutoHide(500);
- $column_grupo_id->enableAutoHide(500);
- // add the columns to the DataGrid
- $this->datagrid->addColumn($column_id);
- $this->datagrid->addColumn($column_nome_fantasia);
- $this->datagrid->addColumn($column_fone);
- $this->datagrid->addColumn($column_email);
- $this->datagrid->addColumn($column_grupo_id);
- $column_id->setAction(new TAction([$this, 'onReload']), ['order' => 'id']);
- $column_nome_fantasia->setAction(new TAction([$this, 'onReload']), ['order' => 'no_nome_fantasia']);
- $action1 = new TDataGridAction(['PessoaFormView', 'onEdit'], ['id'=>'{id}', 'register_state' => 'false']);
- $action2 = new TDataGridAction(['PessoaForm', 'onEdit'], ['id'=>'{id}']);
- $action3 = new TDataGridAction([$this, 'onDelete'], ['id'=>'{id}', 'register_state' => 'false']);
- $this->datagrid->addAction($action1, _t('View'), 'fa:search gray');
- $this->datagrid->addAction($action2, _t('Edit'), 'far:edit blue');
- $this->datagrid->addAction($action3 ,_t('Delete'), 'far:trash-alt red');
- // create the datagrid model
- $this->datagrid->createModel();
- // creates the page navigation
- $this->pageNavigation = new TPageNavigation;
- $this->pageNavigation->setAction(new TAction([$this, 'onReload']));
- $panel = new TPanelGroup('', 'white');
- $panel->add($this->datagrid);
- $panel->addFooter($this->pageNavigation);
- // header actions
- $dropdown = new TDropDown(_t('Export'), 'fa:list');
- $dropdown->setPullSide('right');
- $dropdown->setButtonClass('btn btn-primary waves-effect dropdown-toggle');
- $dropdown->addAction( _t('Save as CSV'), new TAction([$this, 'onExportCSV'], ['register_state' => 'false', 'static'=>'1']), 'fa:table blue' );
- $dropdown->addAction( _t('Save as PDF'), new TAction([$this, 'onExportPDF'], ['register_state' => 'false', 'static'=>'1']), 'far:file-pdf red' );
- $panel->addHeaderWidget( $dropdown );
- // vertical box container
- $container = new TVBox;
- $container->style = 'width: 100%';
- // $container->add(new TXMLBreadCrumb('menu.xml', __CLASS__));
- $container->add($this->form);
- $container->add($panel);
- parent::add($container);
- }
- }
Desconsidera a mensagem, já resolvir o erro era isso $url = 'receitaws.com.br/v1/cnpj/'.$cnpj minha modelagem do DB estava diferente da integração