Lançado Adianti Framework 7.6!
Clique aqui para saber mais
Erro: TDataGrid' does not have a method 'validate' Fala pessoal. Incluí alguns campos na tabela System_User, para que ficasse centralizado o que preciso na aplicação. Ajustei a classe SystemUserForm também de forma realizar uma consulta em um webservice pra preenchimento de alguns campos. Até ai tudo certo. O problema, é na validação do CNPJ, onde preciso caso o usuário informe um CNPJ inválido, que não consiga salvar. Até que o v...
F
Erro: TDataGrid' does not have a method 'validate'  
Fala pessoal.
Incluí alguns campos na tabela System_User, para que ficasse centralizado o que preciso na aplicação. Ajustei a classe SystemUserForm também de forma realizar uma consulta em um webservice pra preenchimento de alguns campos. Até ai tudo certo.
O problema, é na validação do CNPJ, onde preciso caso o usuário informe um CNPJ inválido, que não consiga salvar. Até que o validador está funcionando ao adicionar a linha
$this->form->validate();
porém na pagina aparece o seguinte erro.

Warning: call_user_func_array() expects parameter 1 to be a valid callback, class 'AdiantiWidgetDatagridTDataGrid' does not have a method 'validate' in /srv/http/landini/lib/adianti/wrapper/BootstrapDatagridWrapper.php on line 43

Conforme imagem anexo.
Alguém já passou por isso.
Como solucionar o problema.
Conto com o apoio e antecipadamente agradeço.


Curso completo Meu Negócio Pronto
Use para si, ou transforme em um negócio: Inclui aulas e códigos-fontes
Gestor de conteúdo (SITE) + Loja Virtual (E-Commerce) + Emissor de Notas para infoprodutos


Meu negócio pronto Quero me inscrever agora!

Comentários (7)


MG

Olá, poderia compartilhar o código para que possamos ajudá-lo?
F

Olá Marcelo Gomes!
Claro, vou informar os blocos na classe que foi alterado da padrão.

  1. <?php
  2. #campos do formulário
  3.         $id            = new TEntry('id');
  4.         $name          = new TEntry('name');
  5.         $n_fantasia    = new TEntry('n_fantasia ');
  6.         $numins        = new TEntry('numins');
  7.         $login         = new TEntry('login');
  8.         $password      = new TPassword('password');
  9.         $repassword    = new TPassword('repassword');
  10.         $contato       = new TEntry('contato');
  11.         $email         = new TEntry('email');
  12.         $telefone      = new TEntry('telefone');
  13.         $unit_id       = new TDBCombo('system_unit_id','permission','SystemUnit','id','name');
  14.         $groups        = new TDBCheckGroup('groups','permission','SystemGroup','id','name');
  15.         $frontpage_id  = new TDBUniqueSearch('frontpage_id''permission''SystemProgram''id''name''name');
  16.         $units         = new TDBCheckGroup('units','permission','SystemUnit','id','name');
  17. ?>


  1. <?php
  2. #Definição de mascaras
  3.         $telefone->setMask('99-999-999-999');
  4.         $numins->setMask('99.999.999/9999-99');
  5. ?>


Outras alterações nos campos
  1. <?php
  2.  // outros
  3.         $id->setEditable(false);
  4.         $name->setEditable(false);
  5.         $n_fantasia->setEditable(false);
  6.         $email->setEditable(false);
  7.         $telefone->setEditable(false);
  8. ?>


Validações:
  1. <?php
  2. // validations
  3.         $name->addValidation(_t('Name'), new TRequiredValidator);
  4.         $numins->addValidation('<b>Numero Inscrição</b>', new TRequiredValidator);
  5.         $numins->addValidation('Numero Inscrição', new TCNPJValidator);
  6.         $login->addValidation('Login', new TRequiredValidator);
  7.         $email->addValidation('Email', new TEmailValidator);
  8. ?>


Na classe padrão no construtor as alterações foram as informadas acima.

No metodo
onSave</conde> só adicionei a linha
  1. <?php $this->form->validate();?>
, deixo abaixo o codigo do metodo. Se achar necessário, posso informar o código completo da classe, mas são quase 360 linhas.

  1. <?php
  2. /**
  3.      * Save user data
  4.      */
  5.     public function onSave($param)
  6.     {
  7.         try
  8.         {
  9.             // open a transaction with database 'permission'
  10.             TTransaction::open('permission');
  11.            
  12.             $data $this->form->getData();
  13.             $this->form->validate();
  14.             $this->form->setData($data);
  15.             
  16.             
  17.             $object = new SystemUser;
  18.             $object->fromArray( (array) $data );
  19.             
  20.             $senha $object->password;
  21.             
  22.           
  23.             
  24.             if( empty($object->login) )
  25.             {
  26.                 throw new Exception(TAdiantiCoreTranslator::translate('The field ^1 is required'_t('Login')));
  27.             }
  28.             
  29.             if( empty($object->id) )
  30.             {
  31.                 if (SystemUser::newFromLogin($object->login) instanceof SystemUser)
  32.                 {
  33.                     throw new Exception(_t('An user with this login is already registered'));
  34.                 }
  35.                 
  36.                 if (SystemUser::newFromNumins($object->numins) instanceof SystemUser)
  37.                 {
  38.                     throw new Exception(_t('An user with this registration number is already registered'));
  39.                 }
  40.                 
  41.                 if ( empty($object->password) )
  42.                 {
  43.                     throw new Exception(TAdiantiCoreTranslator::translate('The field ^1 is required'_t('Password')));
  44.                 }
  45.                 
  46.                 $object->active 'Y';
  47.             }
  48.             
  49.             if( $object->password )
  50.             {
  51.                 if( $object->password !== $param['repassword'] )
  52.                     throw new Exception(_t('The passwords do not match'));
  53.                 
  54.                 $object->password md5($object->password);
  55.             }
  56.             else
  57.             {
  58.                 unset($object->password);
  59.             }
  60.             
  61.             $object->store();
  62.             $object->clearParts();
  63.             
  64.             if( !empty($data->groups) )
  65.             {
  66.                 foreach( $data->groups as $group_id )
  67.                 {
  68.                     $object->addSystemUserGroup( new SystemGroup($group_id) );
  69.                 }
  70.             }
  71.             
  72.             if( !empty($data->units) )
  73.             {
  74.                 foreach( $param['units'] as $unit_id )
  75.                 {
  76.                     $object->addSystemUserUnit( new SystemUnit($unit_id) );
  77.                 }
  78.             }
  79.             
  80.             if (!empty($data->program_list))
  81.             {
  82.                 foreach ($data->program_list as $program_id)
  83.                 {
  84.                     $object->addSystemUserProgram( new SystemProgram$program_id ) );
  85.                 }
  86.             }
  87.             
  88.             $data = new stdClass;
  89.             $data->id $object->id;
  90.             
  91.             TForm::sendData('form_System_user'$data);
  92.             
  93.             // close the transaction
  94.             TTransaction::close();
  95.             
  96.             // shows the success message
  97.             new TMessage('info'TAdiantiCoreTranslator::translate('Record saved'));
  98.         }
  99.         catch (Exception $e// in case of exception
  100.         {
  101.             new TMessage('error'$e->getMessage());
  102.             TTransaction::rollback();
  103.         }
  104.     }
  105.     
  106. ?>


Pensei que talvez fosse necessário carregar uma classe que possua o metodo validate nativo.. mas não sei se é isso.

Agradeço o apoio e fico no aguardo.
F

Classe completa

  1. <?php
  2. /**
  3.  * SystemUserForm
  4.  *
  5.  * @version    1.0
  6.  * @package    control
  7.  * @subpackage admin
  8.  * @author     Pablo Dall'Oglio
  9.  * @copyright  Copyright (c) 2006 Adianti Solutions Ltd. (http://www.adianti.com.br)
  10.  * @license    http://www.adianti.com.br/framework-license
  11.  */
  12. class SystemUserForm extends TPage
  13. {
  14.     protected $form// form
  15.     protected $program_list;
  16.     
  17.     /**
  18.      * Class constructor
  19.      * Creates the page and the registration form
  20.      */
  21.     function __construct()
  22.     {
  23.         parent::__construct();
  24.         
  25.         // creates the form
  26.         $this->form = new BootstrapFormBuilder('form_System_user');
  27.         $this->form->setFormTitle_t('User') );
  28.         
  29.         // create the form fields
  30.         $id            = new TEntry('id');
  31.         $name          = new TEntry('name');
  32.         $n_fantasia    = new TEntry('n_fantasia ');
  33.         $numins        = new TEntry('numins');
  34.         $login         = new TEntry('login');
  35.         $password      = new TPassword('password');
  36.         $repassword    = new TPassword('repassword');
  37.         $contato       = new TEntry('contato');
  38.         $email         = new TEntry('email');
  39.         $telefone      = new TEntry('telefone');
  40.         $unit_id       = new TDBCombo('system_unit_id','permission','SystemUnit','id','name');
  41.         $groups        = new TDBCheckGroup('groups','permission','SystemGroup','id','name');
  42.         $frontpage_id  = new TDBUniqueSearch('frontpage_id''permission''SystemProgram''id''name''name');
  43.         $units         = new TDBCheckGroup('units','permission','SystemUnit','id','name');
  44.         
  45.         $units->setLayout('horizontal');
  46.         if ($units->getLabels())
  47.         {
  48.             foreach ($units->getLabels() as $label)
  49.             {
  50.                 $label->setSize(200);
  51.             }
  52.         }
  53.         
  54.         $groups->setLayout('horizontal');
  55.         if ($groups->getLabels())
  56.         {
  57.             foreach ($groups->getLabels() as $label)
  58.             {
  59.                 $label->setSize(200);
  60.             }
  61.         }
  62.         
  63.         $btn $this->form->addAction_t('Save'), new TAction(array($this'onSave')), 'far:save');
  64.         $btn->class 'btn btn-sm btn-primary';
  65.         $this->form->addActionLink_t('Clear'), new TAction(array($this'onEdit')), 'fa:eraser red');
  66.         $this->form->addActionLink_t('Back'), new TAction(array('SystemUserList','onReload')), 'far:arrow-alt-circle-left blue');
  67.         
  68.         // define the sizes
  69.         $id->setSize('50%');
  70.         $name->setSize('100%');
  71.         $login->setSize('100%');
  72.         $password->setSize('100%');
  73.         $repassword->setSize('100%');        
  74.         $email->setSize('100%');
  75.         $unit_id->setSize('100%');
  76.         $frontpage_id->setSize('100%');
  77.         $frontpage_id->setMinLength(1);
  78.         
  79.         #Definição de mascaras
  80.         $telefone->setMask('99-999-999-999');
  81.         $numins->setMask('99.999.999/9999-99');
  82.         
  83.         // outros
  84.         $id->setEditable(false);
  85.         $name->setEditable(false);
  86.         $n_fantasia->setEditable(false);
  87.         $email->setEditable(false);
  88.         $telefone->setEditable(false);
  89.         
  90.         // validations
  91.         $name->addValidation(_t('Name'), new TRequiredValidator);
  92.         $numins->addValidation('<b>Numero Inscrição</b>', new TRequiredValidator);
  93.         $numins->addValidation('Numero Inscrição', new TCNPJValidator);
  94.         $login->addValidation('Login', new TRequiredValidator);
  95.         $email->addValidation('Email', new TEmailValidator);
  96.         
  97.         $this->form->addFields( [new TLabel('ID')], [$id],  [new TLabel(_t('Name'))], [$name] );
  98.         $this->form->addFields( [new TLabel('Nome Fantasia')], [$n_fantasia],  [new TLabel('C.N.P.J')], [$numins] );
  99.         $this->form->addFields( [new TLabel(_t('Login'))], [$login],  [new TLabel('Contato')], [$contato] );
  100.         $this->form->addFields( [new TLabel(_t('Email'))], [$email],  [new TLabel('Telefone')], [$telefone] );
  101.         $this->form->addFields( [new TLabel(_t('Main unit'))], [$unit_id],  [new TLabel(_t('Front page'))], [$frontpage_id] );
  102.         $this->form->addFields( [new TLabel(_t('Password'))], [$password],  [new TLabel(_t('Password confirmation'))], [$repassword] );
  103.         $this->form->addFields( [new TFormSeparator(_t('Units'))] );
  104.         $this->form->addFields( [$units] );
  105.         $this->form->addFields( [new TFormSeparator(_t('Groups'))] );
  106.         $this->form->addFields( [$groups] );
  107.         
  108.         $search = new TEntry('search');
  109.         $search->placeholder _t('Search');
  110.         $search->style 'width:50%;margin-left: 4px; border-radius: 4px';
  111.         
  112.         $this->program_list = new TCheckList('program_list');
  113.         $this->program_list->setIdColumn('id');
  114.         $this->program_list->addColumn('id',    'ID',    'center',  '10%');
  115.         $this->program_list->addColumn('name'_t('Name') . $search->getContents(),    'left',   '50%');
  116.         $col_program $this->program_list->addColumn('controller'_t('Menu path'),    'left',   '40%');
  117.         $col_program->enableAutoHide(500);
  118.         $this->program_list->setHeight(150);
  119.         $this->program_list->makeScrollable();
  120.         
  121.         #Action para consulta de cadastro via webservice do Sapiens
  122.         $numins->setExitAction(new TAction(array($this'onSeniorCadClientes')));
  123.         
  124.         $col_program->setTransformer( function($value$object$row) {
  125.             $menuparser = new TMenuParser('menu.xml');
  126.             $paths $menuparser->getPath($value);
  127.             
  128.             if ($paths)
  129.             {
  130.                 return implode(' &raquo; '$paths);
  131.             }
  132.         });
  133.         
  134.         $this->program_list->enableSearch($search'name');
  135.         
  136.         $this->form->addFields( [new TFormSeparator(_t('Programs'))] );
  137.         $this->form->addFields( [$this->program_list] );
  138.         
  139.         TTransaction::open('permission');
  140.         $this->program_list->addItemsSystemProgram::get() );
  141.         TTransaction::close();
  142.         
  143.         $container = new TVBox;
  144.         $container->style 'width: 100%';
  145.         $container->add(new TXMLBreadCrumb('menu.xml''SystemUserList'));
  146.         $container->add($this->form);
  147.         // add the container to the page
  148.         parent::add($container);
  149.     }
  150.     
  151.     public static function onSeniorCadClientes($param null)
  152.     {
  153.         try 
  154.         {
  155.             $consutlarCNPJ SeniorCadCliente::ConsultarCadastro($param['numins']);
  156.             if( isset($consutlarCNPJ->erro) )
  157.             {
  158.                 throw new Exception($consutlarCNPJ->mensagem);
  159.             }
  160.             else
  161.             {                
  162.                 //prepara stdClass para preencher o formulario com o endereco retornado
  163.                 $object                     = new stdClass();
  164.                 $object->name               $consutlarCNPJ->nomCli;
  165.                 $object->n_fantasia         $consutlarCNPJ->apeCli;
  166.                 $object->telefone           $consutlarCNPJ->fonCli;
  167.                 $object->email              $consutlarCNPJ->intNet;
  168.                                 
  169.                 #envia os dados para o formulario
  170.                 #TForm::sendData(self::'form_Paciente',$object);
  171.                 TForm::sendData('form_System_user',$object);                            
  172.             }
  173.             
  174.         }
  175.         catch (Exception $e
  176.         {
  177.             new TMessage('error'$e->getMessage());    
  178.         }
  179.     }
  180.     
  181.      /**
  182.      * Save user data
  183.      */
  184.     public function onSave($param)
  185.     {
  186.         try
  187.         {
  188.             // open a transaction with database 'permission'
  189.             TTransaction::open('permission');
  190.            
  191.             $data $this->form->getData();
  192.             $this->form->validate();
  193.             $this->form->setData($data);
  194.             
  195.             
  196.             $object = new SystemUser;
  197.             $object->fromArray( (array) $data );
  198.             
  199.             $senha $object->password;
  200.             
  201.           
  202.             
  203.             if( empty($object->login) )
  204.             {
  205.                 throw new Exception(TAdiantiCoreTranslator::translate('The field ^1 is required'_t('Login')));
  206.             }
  207.             
  208.             if( empty($object->id) )
  209.             {
  210.                 if (SystemUser::newFromLogin($object->login) instanceof SystemUser)
  211.                 {
  212.                     throw new Exception(_t('An user with this login is already registered'));
  213.                 }
  214.                 
  215.                 if (SystemUser::newFromNumins($object->numins) instanceof SystemUser)
  216.                 {
  217.                     throw new Exception(_t('An user with this registration number is already registered'));
  218.                 }
  219.                 
  220.                 if ( empty($object->password) )
  221.                 {
  222.                     throw new Exception(TAdiantiCoreTranslator::translate('The field ^1 is required'_t('Password')));
  223.                 }
  224.                 
  225.                 $object->active 'Y';
  226.             }
  227.             
  228.             if( $object->password )
  229.             {
  230.                 if( $object->password !== $param['repassword'] )
  231.                     throw new Exception(_t('The passwords do not match'));
  232.                 
  233.                 $object->password md5($object->password);
  234.             }
  235.             else
  236.             {
  237.                 unset($object->password);
  238.             }
  239.             
  240.             $object->store();
  241.             $object->clearParts();
  242.             
  243.             if( !empty($data->groups) )
  244.             {
  245.                 foreach( $data->groups as $group_id )
  246.                 {
  247.                     $object->addSystemUserGroup( new SystemGroup($group_id) );
  248.                 }
  249.             }
  250.             
  251.             if( !empty($data->units) )
  252.             {
  253.                 foreach( $param['units'] as $unit_id )
  254.                 {
  255.                     $object->addSystemUserUnit( new SystemUnit($unit_id) );
  256.                 }
  257.             }
  258.             
  259.             if (!empty($data->program_list))
  260.             {
  261.                 foreach ($data->program_list as $program_id)
  262.                 {
  263.                     $object->addSystemUserProgram( new SystemProgram$program_id ) );
  264.                 }
  265.             }
  266.             
  267.             $data = new stdClass;
  268.             $data->id $object->id;
  269.             
  270.             TForm::sendData('form_System_user'$data);
  271.             
  272.             // close the transaction
  273.             TTransaction::close();
  274.             
  275.             // shows the success message
  276.             new TMessage('info'TAdiantiCoreTranslator::translate('Record saved'));
  277.         }
  278.         catch (Exception $e// in case of exception
  279.         {
  280.             new TMessage('error'$e->getMessage());
  281.             TTransaction::rollback();
  282.         }
  283.     }
  284.     
  285.     /**
  286.      * method onEdit()
  287.      * Executed whenever the user clicks at the edit button da datagrid
  288.      */
  289.     function onEdit($param)
  290.     {
  291.         try
  292.         {
  293.             if (isset($param['key']))
  294.             {
  295.                 // get the parameter $key
  296.                 $key=$param['key'];
  297.                 
  298.                 // open a transaction with database 'permission'
  299.                 TTransaction::open('permission');
  300.                 
  301.                 // instantiates object System_user
  302.                 $object = new SystemUser($key);
  303.                 
  304.                 unset($object->password);
  305.                 
  306.                 $groups = array();
  307.                 $units  = array();
  308.                 
  309.                 if( $groups_db $object->getSystemUserGroups() )
  310.                 {
  311.                     foreach( $groups_db as $group )
  312.                     {
  313.                         $groups[] = $group->id;
  314.                     }
  315.                 }
  316.                 
  317.                 if( $units_db $object->getSystemUserUnits() )
  318.                 {
  319.                     foreach( $units_db as $unit )
  320.                     {
  321.                         $units[] = $unit->id;
  322.                     }
  323.                 }
  324.                 
  325.                 $program_ids = array();
  326.                 foreach ($object->getSystemUserPrograms() as $program)
  327.                 {
  328.                     $program_ids[] = $program->id;
  329.                 }
  330.                 
  331.                 $object->program_list $program_ids;
  332.                 $object->groups $groups;
  333.                 $object->units  $units;
  334.                 
  335.                 // fill the form with the active record data
  336.                 $this->form->setData($object);
  337.                 
  338.                 // close the transaction
  339.                 TTransaction::close();
  340.             }
  341.             else
  342.             {
  343.                 $this->form->clear();
  344.             }
  345.         }
  346.         catch (Exception $e// in case of exception
  347.         {
  348.             new TMessage('error'$e->getMessage());
  349.             TTransaction::rollback();
  350.         }
  351.     }
  352. }
  353. ?>
MG

Boa tarde!
Como está implementado este método no Model SystemUser:

if (SystemUser::newFromNumins($object->numins) instanceof SystemUser)

Um dica:
Eu aconselho você criar outro Model ou Controles para SystemUsers......
Estas aplicações (programas) são alterados de acordo com as novas versões do FW!
F

Olá Marcelo!
Seu conselho não é só válido como será seguido, porém o projeto tem data de entrega e vou deixar que os ajustes na classe seja feito futuramente. Ou mesmo quando atualizar o FW, eu adicione ou remova somente o que foi alterado.

Quanto ao seu questionamento, esta linha no padrão é do campo email. Então eu apenas alterei para o campo numins ficando assim
  1. <?php
  2. static public function newFromNumins($numins)
  3.     {
  4.         return SystemUser::where('numins''='$numins)->first();
  5.     }
  6.  ?>

No grupo do Facebook, o Pablo disse que se trata de um erro de versão que será corrigido na versão 7.1 lançada ainda este mes.

Agradeço demais seu apoio... e pode ter certeza que tenho outros que gostaria e muito da sua expertise me apoiando.
Muito obrigado mesmo!
MG

Ok. pode ser mesmo. Você migou o projeto?
Eu reproduzi este código na versão 7 e funcionou de boa.
Vamos aguardar. Se puder ajudar, estou aqui.
Abraços
F

Sim, migrei meu projeto.
Vamos aguardar.
Obrigado mais uma vez parceiro!