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

 
  1. <?php
  2. /**
  3. * Pessoa Active Record
  4. * @author <your-name-here>
  5. */
  6. class Pessoa extends TRecord
  7. {
  8. const TABLENAME = 'tb_pessoa';
  9. const PRIMARYKEY = 'id';
  10. const IDPOLICY = 'max'; // {max, serial}
  11. const CREATEDAT = 'hr_created_at';
  12. const UPDATEDAT = 'hr_updated_at';
  13. /**
  14. * Constructor method
  15. */
  16. public function __construct($id = NULL, $callObjectLoad = TRUE)
  17. {
  18. parent::__construct($id, $callObjectLoad);
  19. parent::addAttribute('no_nome');
  20. parent::addAttribute('no_nome_fantasia');
  21. parent::addAttribute('st_tipo');
  22. parent::addAttribute('nu_codigo_nacional');
  23. parent::addAttribute('nu_codigo_estadual');
  24. parent::addAttribute('nu_codigo_municipal');
  25. parent::addAttribute('nu_fone');
  26. parent::addAttribute('no_email');
  27. parent::addAttribute('ds_observacao');
  28. parent::addAttribute('nu_cep');
  29. parent::addAttribute('no_logradouro');
  30. parent::addAttribute('nu_numero');
  31. parent::addAttribute('no_complemento');
  32. parent::addAttribute('no_bairro');
  33. parent::addAttribute('municipio_id');
  34. parent::addAttribute('hr_created_at');
  35. parent::addAttribute('hr_updated_at');
  36. parent::addAttribute('grupo_id');
  37. }
  38. public function get_cidade()
  39. {
  40. return Cidade::find($this->municipio_id);
  41. }
  42. public function get_grupo()
  43. {
  44. return Grupo::find($this->grupo_id);
  45. }
  46. public function delete($id = null)
  47. {
  48. $id = isset($id) ? $id : $this->id;
  49. PessoaPapel::where('pessoa_id', '=', $this->id)->delete();
  50. parent::delete($id);
  51. }
  52. }
  53. /* Pessoa Form
 
  1. <?php
  2. /**
  3. * PessoaForm
  4. *
  5. * @version 1.0
  6. * @license http://www.adianti.com.br/framework-license
  7. */
  8. class PessoaForm extends TWindow
  9. {
  10. protected $form; // form
  11. /**
  12. * Form constructor
  13. * @param $param Request
  14. */
  15. public function __construct( $param )
  16. {
  17. parent::__construct();
  18. parent::setSize(0.8, null);
  19. parent::removePadding();
  20. parent::removeTitleBar();
  21. //parent::disableEscape();
  22. // creates the form
  23. $this->form = new BootstrapFormBuilder('form_Pessoa');
  24. $this->form->setFormTitle('Pessoa');
  25. $this->form->setProperty('style', 'margin:0;border:0');
  26. $this->form->setClientValidation(true);
  27. // create the form fields
  28. $id = new TEntry('id');
  29. $nome = new TEntry('nome');
  30. $nome_fantasia = new TEntry('nome_fantasia');
  31. $tipo = new TCombo('tipo');
  32. $codigo_nacional = new TEntry('codigo_nacional');
  33. $codigo_estadual = new TEntry('codigo_estadual');
  34. $codigo_municipal = new TEntry('codigo_municipal');
  35. $fone = new TEntry('fone');
  36. $email = new TEntry('email');
  37. $observacao = new TText('observacao');
  38. $cep = new TEntry('cep');
  39. $logradouro = new TEntry('logradouro');
  40. $numero = new TEntry('numero');
  41. $complemento = new TEntry('complemento');
  42. $bairro = new TEntry('bairro');
  43. $filter = new TCriteria;
  44. $filter->add(new TFilter('id', '<', '0'));
  45. $cidade_id = new TDBCombo('municipio_id', 'sys_db', 'Cidade', 'id', 'no_nome', 'no_nome', $filter);
  46. $grupo_id = new TDBUniqueSearch('grupo_id', 'sys_db', 'Grupo', 'id', 'no_nome');
  47. $papeis_id = new TDBMultiSearch('papeis_id', 'sys_db', 'Papel', 'id', 'no_nome');
  48. $estado_id = new TDBCombo('estado_id', 'sys_db', 'Estado', 'id', '{no_nome} ({sg_uf})');
  49. $estado_id->setChangeAction( new TAction( [$this, 'onChangeEstado'] ) );
  50. $cep->setExitAction( new TAction([ $this, 'onExitCEP']) );
  51. $codigo_nacional->setExitAction( new TAction( [$this, 'onExitCNPJ'] ) );
  52. $cidade_id->enableSearch();
  53. $estado_id->enableSearch();
  54. $grupo_id->setMinLength(0);
  55. $papeis_id->setMinLength(0);
  56. $papeis_id->setSize('100%', 60);
  57. $observacao->setSize('100%', 60);
  58. $tipo->addItems( ['F' => 'Física', 'J' => 'Jurídica' ] );
  59. // add the fields
  60. $this->form->addFields( [ new TLabel('Id') ], [ $id ] );
  61. $this->form->addFields( [ new TLabel('Tipo') ], [ $tipo ], [ new TLabel('CPF/CNPJ') ], [ $codigo_nacional ] );
  62. $this->form->addFields( [ new TLabel('Nome') ], [ $nome ] );
  63. $this->form->addFields( [ new TLabel('Nome Fantasia') ], [ $nome_fantasia ] );
  64. $this->form->addFields( [ new TLabel('Papéis')], [ $papeis_id ], [ new TLabel('Grupo') ], [ $grupo_id ] );
  65. $this->form->addFields( [ new TLabel('I.E.') ], [ $codigo_estadual ], [ new TLabel('I.M.') ], [ $codigo_municipal ] );
  66. $this->form->addFields( [ new TLabel('Fone') ], [ $fone ], [ new TLabel('Email') ], [ $email ] );
  67. $this->form->addFields( [ new TLabel('Observacao') ], [ $observacao ] );
  68. $this->form->addContent( [new TFormSeparator('Endereço')]);
  69. $this->form->addFields( [ new TLabel('Cep') ], [ $cep ] )->layout = ['col-sm-2 control-label', 'col-sm-4'];
  70. $this->form->addFields( [ new TLabel('Logradouro') ], [ $logradouro ], [ new TLabel('Numero') ], [ $numero ] );
  71. $this->form->addFields( [ new TLabel('Complemento') ], [ $complemento ], [ new TLabel('Bairro') ], [ $bairro ] );
  72. $this->form->addFields( [ new TLabel('Estado') ], [$estado_id], [ new TLabel('Cidade') ], [ $cidade_id ] );
  73. // adiciona as validações
  74. $codigo_nacional->addValidation('Tipo', new TNumericValidator);
  75. // set sizes
  76. $id->setSize('100%');
  77. $nome->setSize('100%');
  78. $nome_fantasia->setSize('100%');
  79. $tipo->setSize('100%');
  80. $codigo_nacional->setSize('100%');
  81. $codigo_estadual->setSize('100%');
  82. $codigo_municipal->setSize('100%');
  83. $fone->setSize('100%');
  84. $email->setSize('100%');
  85. $observacao->setSize('100%');
  86. $cep->setSize('100%');
  87. $logradouro->setSize('100%');
  88. $numero->setSize('100%');
  89. $complemento->setSize('100%');
  90. $bairro->setSize('100%');
  91. $cidade_id->setSize('100%');
  92. $grupo_id->setSize('100%');
  93. $cep->setMask('99.999-999');
  94. $id->setEditable(FALSE);
  95. $nome->addValidation('Nome', new TRequiredValidator);
  96. $nome_fantasia->addValidation('Nome Fantasia', new TRequiredValidator);
  97. $tipo->addValidation('Tipo', new TRequiredValidator);
  98. $codigo_nacional->addValidation('CPF/CNPJ', new TRequiredValidator);
  99. $grupo_id->addValidation('Grupo', new TRequiredValidator);
  100. $fone->addValidation('Fone', new TRequiredValidator);
  101. $email->addValidation('Email', new TRequiredValidator);
  102. $email->addValidation('Email', new TEmailValidator);
  103. $cidade_id->addValidation('Cidade', new TRequiredValidator);
  104. $cep->addValidation('CEP', new TRequiredValidator);
  105. $logradouro->addValidation('Logradouro', new TRequiredValidator);
  106. $numero->addValidation('Número', new TRequiredValidator);
  107. // create the form actions
  108. $this->form->addHeaderActionLink( _t('Close'), new TAction([__CLASS__, 'onClose'], ['static'=>'1']), 'fa:times red');
  109. $btn = $this->form->addAction(_t('Save'), new TAction([$this, 'onSave']), 'fa:save');
  110. $btn->class = 'btn btn-sm btn-primary';
  111. $this->form->addActionLink(_t('New'), new TAction([$this, 'onEdit']), 'fa:eraser red');
  112. // vertical box container
  113. $container = new TVBox;
  114. $container->style = 'width: 100%';
  115. // $container->add(new TXMLBreadCrumb('menu.xml', __CLASS__));
  116. $container->add($this->form);
  117. parent::add($container);
  118. }
  119. /**
  120. * Save form data
  121. * @param $param Request
  122. */
  123. public function onSave( $param )
  124. {
  125. try
  126. {
  127. TTransaction::open('sys_db'); // open a transaction
  128. $this->form->validate(); // validate form data
  129. $data = $this->form->getData(); // get form data as array
  130. $object = new Pessoa; // create an empty object
  131. $object->fromArray( (array) $data); // load the object with data
  132. $object->store(); // save the object
  133. var_dump($object);
  134. PessoaPapel::where('pessoa_id', '=', $object->id)->delete();
  135. if ($data->papeis_id)
  136. {
  137. foreach ($data->papeis_id as $papel_id)
  138. {
  139. $pp = new PessoaPapel;
  140. $pp->pessoa_id = $object->id;
  141. $pp->papel_id = $papel_id;
  142. $pp->store();
  143. }
  144. }
  145. // get the generated id
  146. $data->id = $object->id;
  147. $this->form->setData($data); // fill form data
  148. TTransaction::close(); // close the transaction
  149. new TMessage('info', AdiantiCoreTranslator::translate('Record saved'));
  150. }
  151. catch (Exception $e) // in case of exception
  152. {
  153. new TMessage('error', $e->getMessage()); // shows the exception error message
  154. $this->form->setData( $this->form->getData() ); // keep form data
  155. TTransaction::rollback(); // undo all pending operations
  156. }
  157. }
  158. /**
  159. * Clear form data
  160. * @param $param Request
  161. */
  162. public function onClear( $param )
  163. {
  164. $this->form->clear(TRUE);
  165. }
  166. /**
  167. * Load object to form data
  168. * @param $param Request
  169. */
  170. public function onEdit( $param )
  171. {
  172. try
  173. {
  174. if (isset($param['key']))
  175. {
  176. $key = $param['key'];
  177. TTransaction::open('sys_db');
  178. $object = new Pessoa($key);
  179. $object->papeis_id = PessoaPapel::where('pessoa_id', '=', $object->id)->getIndexedArray('papel_id');
  180. $this->form->setData($object);
  181. // force fire events
  182. $data = new stdClass;
  183. $data->estado_id = $object->cidade->estado->id;
  184. $data->municipio_id = $object->municipio_id;
  185. TForm::sendData('form_Pessoa', $data);
  186. TTransaction::close();
  187. }
  188. else
  189. {
  190. $this->form->clear(TRUE);
  191. }
  192. }
  193. catch (Exception $e) // in case of exception
  194. {
  195. new TMessage('error', $e->getMessage()); // shows the exception error message
  196. TTransaction::rollback(); // undo all pending operations
  197. }
  198. }
  199. /**
  200. * Action to be executed when the user changes the state
  201. * @param $param Action parameters
  202. */
  203. public static function onChangeEstado($param)
  204. {
  205. try
  206. {
  207. TTransaction::open('sys_db');
  208. if (!empty($param['estado_id']))
  209. {
  210. $criteria = TCriteria::create( ['estado_id' => $param['estado_id'] ] );
  211. // formname, field, database, model, key, value, ordercolumn = NULL, criteria = NULL, startEmpty = FALSE
  212. TDBCombo::reloadFromModel('form_Pessoa', 'municipio_id', 'sys_db', 'Cidade', 'id', '{no_nome} ({id})', 'no_nome', $criteria, TRUE);
  213. }
  214. else
  215. {
  216. TCombo::clearField('form_Pessoa', 'municipio_id');
  217. }
  218. TTransaction::close();
  219. }
  220. catch (Exception $e)
  221. {
  222. new TMessage('error', $e->getMessage());
  223. }
  224. }
  225. /**
  226. * Autocompleta outros campos a partir do CNPJ
  227. */
  228. public static function onExitCNPJ($param)
  229. {
  230. session_write_close();
  231. try
  232. {
  233. $cnpj = preg_replace('/[^0-9]/', '', $param['codigo_nacional']);
  234. $url = 'http://receitaws.com.br/v1/cnpj/'.$cnpj;
  235. $content = @file_get_contents($url);
  236. if ($content !== false)
  237. {
  238. $cnpj_data = json_decode($content);
  239. $data = new stdClass;
  240. if (is_object($cnpj_data) && $cnpj_data->status !== 'ERROR')
  241. {
  242. $data->tipo = 'J';
  243. $data->nome = $cnpj_data->nome;
  244. $data->nome_fantasia = !empty($cnpj_data->fantasia) ? $cnpj_data->fantasia : $cnpj_data->nome;
  245. if (empty($param['cep']))
  246. {
  247. $data->cep = $cnpj_data->cep;
  248. $data->numero = $cnpj_data->numero;
  249. }
  250. if (empty($param['fone']))
  251. {
  252. $data->fone = $cnpj_data->telefone;
  253. }
  254. if (empty($param['email']))
  255. {
  256. $data->email = $cnpj_data->email;
  257. }
  258. TForm::sendData('form_Pessoa', $data, false, true);
  259. }
  260. else
  261. {
  262. $data->nome = '';
  263. $data->nome_fantasia = '';
  264. $data->cep = '';
  265. $data->numero = '';
  266. $data->telefone = '';
  267. $data->email = '';
  268. TForm::sendData('form_Pessoa', $data, false, true);
  269. }
  270. }
  271. }
  272. catch (Exception $e)
  273. {
  274. new TMessage('error', $e->getMessage());
  275. }
  276. }
  277. /**
  278. * Autocompleta outros campos a partir do CEP
  279. */
  280. public static function onExitCEP($param)
  281. {
  282. session_write_close();
  283. try
  284. {
  285. $cep = preg_replace('/[^0-9]/', '', $param['cep']);
  286. $url = 'https://viacep.com.br/ws/'.$cep.'/json/unicode/';
  287. $content = @file_get_contents($url);
  288. if ($content !== false)
  289. {
  290. $cep_data = json_decode($content);
  291. $data = new stdClass;
  292. if (is_object($cep_data) && empty($cep_data->erro))
  293. {
  294. TTransaction::open('sys_db');
  295. $estado = Estado::where('sg_uf', '=', $cep_data->uf)->first();
  296. $cidade = Cidade::where('id', '=', $cep_data->ibge)->first();
  297. TTransaction::close();
  298. $data->logradouro = $cep_data->logradouro;
  299. $data->complemento = $cep_data->complemento;
  300. $data->bairro = $cep_data->bairro;
  301. $data->estado_id = $estado->id ?? '';
  302. $data->municipio_id = $cidade->id ?? '';
  303. TForm::sendData('form_Pessoa', $data, false, true);
  304. }
  305. else
  306. {
  307. $data->logradouro = '';
  308. $data->complemento = '';
  309. $data->bairro = '';
  310. $data->estado_id = '';
  311. $data->municipio_id = '';
  312. TForm::sendData('form_Pessoa', $data, false, true);
  313. }
  314. }
  315. }
  316. catch (Exception $e)
  317. {
  318. new TMessage('error', $e->getMessage());
  319. }
  320. }
  321. /**
  322. * Closes window
  323. */
  324. public static function onClose()
  325. {
  326. parent::closeWindow();
  327. }
  328. }
  329. /* PessoaList */
 
  1. <?php
  2. /**
  3. * PessoaList
  4. *
  5. * @version 1.0
  6. * @license http://www.adianti.com.br/framework-license
  7. */
  8. class PessoaList extends TPage
  9. {
  10. protected $form; // registration form
  11. protected $datagrid; // listing
  12. protected $pageNavigation;
  13. protected $formgrid;
  14. protected $deleteButton;
  15. use Adianti\base\AdiantiStandardListTrait;
  16. /**
  17. * Page constructor
  18. */
  19. public function __construct()
  20. {
  21. parent::__construct();
  22. $this->setDatabase('sys_db'); // defines the database
  23. $this->setActiveRecord('Pessoa'); // defines the active record
  24. $this->setDefaultOrder('id', 'asc'); // defines the default order
  25. $this->setLimit(10);
  26. // $this->setCriteria($criteria) // define a standard filter
  27. $this->addFilterField('id', '=', 'id'); // filterField, operator, formField
  28. $this->addFilterField('no_nome_fantasia', 'like', 'nome_fantasia'); // filterField, operator, formField
  29. $this->addFilterField('nu_fone', 'like', 'fone'); // filterField, operator, formField
  30. $this->addFilterField('no_email', 'like', 'email'); // filterField, operator, formField
  31. $this->addFilterField('grupo_id', '=', 'grupo_id'); // filterField, operator, formField
  32. // creates the form
  33. $this->form = new BootstrapFormBuilder('form_search_Pessoa');
  34. $this->form->setFormTitle('Pessoa');
  35. // create the form fields
  36. $id = new TEntry('id');
  37. $nome_fantasia = new TEntry('nome_fantasia');
  38. $fone = new TEntry('fone');
  39. $email = new TEntry('email');
  40. $grupo_id = new TDBUniqueSearch('grupo_id', 'sys_db', 'Grupo', 'id', 'no_nome');
  41. $grupo_id->setMinLength(0);
  42. // add the fields
  43. $this->form->addFields( [ new TLabel('Id') ], [ $id ] );
  44. $this->form->addFields( [ new TLabel('Nome Fantasia') ], [ $nome_fantasia ] );
  45. $this->form->addFields( [ new TLabel('Fone') ], [ $fone ] );
  46. $this->form->addFields( [ new TLabel('Email') ], [ $email ] );
  47. $this->form->addFields( [ new TLabel('Grupo') ], [ $grupo_id ] );
  48. // set sizes
  49. $id->setSize('100%');
  50. $nome_fantasia->setSize('100%');
  51. $fone->setSize('100%');
  52. $email->setSize('100%');
  53. $grupo_id->setSize('100%');
  54. // keep the form filled during navigation with session data
  55. $this->form->setData( TSession::getValue(__CLASS__.'_filter_data') );
  56. // add the search form actions
  57. $btn = $this->form->addAction(_t('Find'), new TAction([$this, 'onSearch']), 'fa:search');
  58. $btn->class = 'btn btn-sm btn-primary';
  59. $this->form->addActionLink(_t('New'), new TAction(['PessoaForm', 'onEdit']), 'fa:plus green');
  60. // creates a Datagrid
  61. $this->datagrid = new BootstrapDatagridWrapper(new TDataGrid);
  62. $this->datagrid->style = 'width: 100%';
  63. //$this->datagrid->datatable = 'true';
  64. // $this->datagrid->enablePopover('Popover', 'Hi <b> {name} </b>');
  65. // creates the datagrid columns
  66. $column_id = new TDataGridColumn('id', 'Id', 'left');
  67. $column_nome_fantasia = new TDataGridColumn('no_nome_fantasia', 'Nome Fantasia', 'left');
  68. $column_fone = new TDataGridColumn('nu_fone', 'Fone', 'left');
  69. $column_email = new TDataGridColumn('no_email', 'Email', 'left');
  70. $column_grupo_id = new TDataGridColumn('grupo->no_nome', 'Grupo', 'left');
  71. $column_fone->enableAutoHide(500);
  72. $column_email->enableAutoHide(500);
  73. $column_grupo_id->enableAutoHide(500);
  74. // add the columns to the DataGrid
  75. $this->datagrid->addColumn($column_id);
  76. $this->datagrid->addColumn($column_nome_fantasia);
  77. $this->datagrid->addColumn($column_fone);
  78. $this->datagrid->addColumn($column_email);
  79. $this->datagrid->addColumn($column_grupo_id);
  80. $column_id->setAction(new TAction([$this, 'onReload']), ['order' => 'id']);
  81. $column_nome_fantasia->setAction(new TAction([$this, 'onReload']), ['order' => 'no_nome_fantasia']);
  82. $action1 = new TDataGridAction(['PessoaFormView', 'onEdit'], ['id'=>'{id}', 'register_state' => 'false']);
  83. $action2 = new TDataGridAction(['PessoaForm', 'onEdit'], ['id'=>'{id}']);
  84. $action3 = new TDataGridAction([$this, 'onDelete'], ['id'=>'{id}', 'register_state' => 'false']);
  85. $this->datagrid->addAction($action1, _t('View'), 'fa:search gray');
  86. $this->datagrid->addAction($action2, _t('Edit'), 'far:edit blue');
  87. $this->datagrid->addAction($action3 ,_t('Delete'), 'far:trash-alt red');
  88. // create the datagrid model
  89. $this->datagrid->createModel();
  90. // creates the page navigation
  91. $this->pageNavigation = new TPageNavigation;
  92. $this->pageNavigation->setAction(new TAction([$this, 'onReload']));
  93. $panel = new TPanelGroup('', 'white');
  94. $panel->add($this->datagrid);
  95. $panel->addFooter($this->pageNavigation);
  96. // header actions
  97. $dropdown = new TDropDown(_t('Export'), 'fa:list');
  98. $dropdown->setPullSide('right');
  99. $dropdown->setButtonClass('btn btn-primary waves-effect dropdown-toggle');
  100. $dropdown->addAction( _t('Save as CSV'), new TAction([$this, 'onExportCSV'], ['register_state' => 'false', 'static'=>'1']), 'fa:table blue' );
  101. $dropdown->addAction( _t('Save as PDF'), new TAction([$this, 'onExportPDF'], ['register_state' => 'false', 'static'=>'1']), 'far:file-pdf red' );
  102. $panel->addHeaderWidget( $dropdown );
  103. // vertical box container
  104. $container = new TVBox;
  105. $container->style = 'width: 100%';
  106. // $container->add(new TXMLBreadCrumb('menu.xml', __CLASS__));
  107. $container->add($this->form);
  108. $container->add($panel);
  109. parent::add($container);
  110. }
  111. }

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


HL

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