Lançado Adianti Framework 7.6!
Clique aqui para saber mais
Problema com onEdit Prezados, boa noite, Estou enfrentando um problema com o edit do meu sistema, ao clicar para editar, vai pro formulário preenchido, porém, quando se alterar os dados, em vez de editar é salvo um novo dados. Abaixo segue o código para análise: ...
PA
Problema com onEdit  
Prezados, boa noite,
Estou enfrentando um problema com o edit do meu sistema, ao clicar para editar, vai pro formulário preenchido, porém, quando se alterar os dados, em vez de editar é salvo um novo dados.

Abaixo segue o código para análise:

  1. <?php
  2. /**
  3.  * SystemUnitForm
  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 GoogleMaps extends TStandardForm
  13. {
  14.     protected $form// form
  15.     
  16.     /**
  17.      * Class constructor
  18.      * Creates the page and the registration form
  19.      */
  20.     function __construct()
  21.     {
  22.         parent::__construct();
  23.         
  24.         $this->setDatabase('permission');              // defines the database
  25.         $this->setActiveRecord('SystemUnit');     // defines the active record
  26.         
  27.         // creates the form
  28.         $this->form = new BootstrapFormBuilder('form_SystemUnit');
  29.         $this->form->setFormTitle('Cadastrar pontos de ronda');
  30.         
  31.         // create the form fields
  32.         $nome = new TEntry('nome');
  33.         //$unit_id = new TDBCombo('fk_id_system_unit','permission','SystemUnit','id','name');
  34.         
  35.         $estado = new TCombo('estado');
  36.         $cidade = new TEntry('cidade');
  37.         $bairro = new TEntry('bairro');
  38.         $logradouro = new TEntry('logradouro');
  39.         $cep = new TEntry('cep');
  40.         $buscar TButton::create('buscar',  array($this'onSearchAddress'), 'Localizar''fa:search blue');
  41.         
  42.         $estado->addItems(array('AC' => 'ACRE''AL' => 'ALAGOAS''AM' => 'AMAZONAS''AP' => 'AMAPÁ''BA' => 'BAHIA''CE' => 'CEARÁ''DF' => 'DISTRITO FEDERAL''ES' => 'ESPÍRITO SANTO''GO' => 'GOIÁS''MA' => 'MARANHÃO''MG' => 'MINAS GERAIS''MS' => 'MATO GROSSO DO SUL''MT' => 'MATO GROSSO''PA' => 'PARÁ''PB' => 'PARAÍBA''PE' => 'PERNAMBUCO''PI' => 'PIAUÍ''PR' => 'PARANÁ''RJ' => 'RIO DE JANEIRO''RN' => 'RIO GRANDE DO NORTE''RO' => 'RONDÔNIA''RR' => 'RORAIMA''RS' => 'RIO GRANDE DO SUL''SC' => 'SANTA CATARINA''SE' => 'SERGIPE''SP' => 'SÃO PAULO''TO' => 'TOCANTINS'));
  43.         $cep->setMask('99.999-999');
  44.         $latitude = new TEntry('latitude');
  45.         $longitude = new TEntry('longitude');
  46.         $mapaDenuncia = new TElement('div');
  47.         $mapaDenuncia->id 'mapaDenuncia';
  48.         $mapaDenuncia->style 'width:100%; height:500px; min-height:200px; border:1px solid gray; padding:4px; margin: auto; text-align: center;';
  49.         
  50.         //não permirtir edição
  51.         $latitude->setEditable(false);
  52.         $longitude->setEditable(false);
  53.         //definir um tamanho
  54.         $nome->setSize('89%');
  55.         //$unit_id->setSize('89%');
  56.         $latitude->setSize('70%');
  57.         $longitude->setSize('70%');
  58.         $estado->setSize('70%');
  59.         $cidade->setSize('70%');
  60.         $bairro->setSize('70%');
  61.         $logradouro->setSize('70%');
  62.         $cep->setSize('28%');
  63.         
  64.         $nome->addValidation( ('Nome'), new TRequiredValidator );
  65.         // add the fields
  66.         $this->form->addFields( [new TLabel('Nome')], [$nome] );
  67.         //$this->form->addFields( [new TLabel('Unidade Matriz')], [$unit_id] );
  68.         $this->form->addFields( [new TLabel('Estado')], [$estado], [new TLabel('Cidade')], [$cidade] );
  69.         $this->form->addFields( [new TLabel('Bairro')], [$bairro], [new TLabel('Logradouro')], [$logradouro] );
  70.         $this->form->addFields( [new TLabel('CEP')], [$cep$buscar] );
  71.         $this->form->addFields( [new TLabel('Latitude')], [$latitude], [new TLabel('Longitude')], [$longitude] );
  72.         
  73.         $this->form->addContent( [$mapaDenuncia] );
  74.         // create the form actions
  75.         $this->form->addAction(_t('Save'), new TAction(array($this'onSave')), 'fa:floppy-o')->class 'btn btn-sm btn-primary';;
  76.         $this->form->addAction(_t('Clear'),  new TAction(array($this'onEdit')), 'fa:eraser red');
  77.         $this->form->addAction(_t('Back'),new TAction(array('CadastroRonda','onReload')),'fa:arrow-circle-o-left blue');
  78.         
  79.         // vertical box container
  80.         $container = new TVBox;
  81.         $container->style 'width: 100%';
  82.         $container->add(new TXMLBreadCrumb('menu.xml''SystemUnitList'));
  83.         $container->add($this->form);
  84.         
  85.         parent::add($container);
  86.         TScript::create("
  87.             var selectedShape;
  88.             var selectedPoint;
  89.             var selectedMarker;
  90.             function clearMap() {
  91.                 if (selectedShape) {
  92.                     selectedShape.setMap(null);
  93.                     selectedShape = null;
  94.                 }
  95.                 if(selectedMarker){
  96.                     selectedMarker.setMap(null);
  97.                 }
  98.             }
  99.             function setSelectedOverlay(shape, marker) {
  100.                 clearMap();
  101.                 selectedShape = shape;
  102.                 selectedMarker = marker;
  103.                 shape.setEditable(true);
  104.             }
  105.             function setSelectedPoint(point) {
  106.                 if(selectedPoint){
  107.                     selectedPoint.setMap(null);
  108.                     selectedPoint = null;
  109.                 }
  110.                 selectedPoint = point;
  111.             }
  112.             var teste = 1;
  113.             var mapOptions = {
  114.                 zoom: 12,
  115.                 center: {lat: -12.942304, lng: -38.421180},
  116.                 styles: [
  117.                     { 'featureType': 'administrative', 'elementType': 'labels.text.fill', 'stylers': [ { 'color': '#444444' } ] },
  118.                     { 'featureType': 'landscape', 'elementType': 'all', 'stylers': [ { 'color': '#f2f2f2' } ] },
  119.                     { 'featureType': 'poi', 'elementType': 'all', 'stylers': [ { 'visibility': 'off' } ] },
  120.                     { 'featureType': 'road', 'elementType': 'all', 'stylers': [ { 'saturation': -100 }, { 'lightness': 45 } ] },
  121.                     { 'featureType': 'road.highway', 'elementType': 'all', 'stylers': [ { 'visibility': 'simplified' } ] },
  122.                     { 'featureType': 'road.arterial', 'elementType': 'labels.icon', 'stylers': [ { 'visibility': 'off' } ] },
  123.                     { 'featureType': 'transit', 'elementType': 'all', 'stylers': [ { 'visibility': 'off' } ] },
  124.                     { 'featureType': 'water', 'elementType': 'all', 'stylers': [ { 'color': '#46bcec' }, { 'visibility': 'on' } ] }
  125.                 ]
  126.             };
  127.             /* Instantiate a directions service. */
  128.             var directionsService = new google.maps.DirectionsService;
  129.             /* Create a map */
  130.             var map = new google.maps.Map(document.getElementById('mapaDenuncia'), mapOptions);
  131.             /* Create a renderer for directions and bind it to the map. */
  132.             var directionsDisplay = new google.maps.DirectionsRenderer({map: map, suppressMarkers: true});
  133.             var drawingManager = new google.maps.drawing.DrawingManager({
  134.                 drawingMode: google.maps.drawing.OverlayType.MARKER,
  135.                 drawingControl: true,
  136.                 drawingControlOptions: {
  137.                     position: google.maps.ControlPosition.TOP_CENTER,
  138.                     drawingModes: [ 
  139.                         google.maps.drawing.OverlayType.MARKER
  140.                     ]
  141.                 }
  142.             });
  143.             drawingManager.setMap(map);
  144.             map.addListener('mousemove', function() {
  145.                 if(teste == 1){
  146.                     teste = 2;
  147.                     var center = map.getCenter();
  148.                     google.maps.event.trigger(map, \"resize\");
  149.                     map.setCenter(center);
  150.                 }
  151.             });
  152.             google.maps.event.addListener(drawingManager, 'overlaycomplete', function (e) {
  153.                 var overlay = e.overlay;
  154.                 if (e.type == google.maps.drawing.OverlayType.MARKER) {
  155.                     var lat = overlay.getPosition().lat();
  156.                     var lng = overlay.getPosition().lng();
  157.                     
  158.                     setSelectedPoint(overlay);
  159.                     $('input[name=\"latitude\"]').val(lat);
  160.                     $('input[name=\"longitude\"]').val(lng);
  161.                     var infowindow = new google.maps.InfoWindow({
  162.                         content: 'Seu estabelecimento.'
  163.                     });
  164.                     overlay.addListener('click', function() {
  165.                         infowindow.open(map, overlay);
  166.                     });
  167.                 }
  168.             });
  169.             var infoWindow = new google.maps.InfoWindow({
  170.                 content: 'Seu perímetro.'
  171.             });
  172.             if (navigator.geolocation) {
  173.                 navigator.geolocation.getCurrentPosition(function(position) {
  174.                     var pos = {lat: position.coords.latitude, lng: position.coords.longitude};
  175.                     map.setCenter(pos);
  176.                 }, function() {
  177.                     handleLocationError(true, infoWindow, map.getCenter());
  178.                 });
  179.             } else {
  180.                 /* Browser doesn't support Geolocation*/
  181.                 handleLocationError(false, infoWindow, map.getCenter());
  182.             }
  183.             function handleLocationError(browserHasGeolocation, infoWindow, pos) {}
  184.         ");
  185.     }
  186.     public static function onSearchAddress($param)
  187.     {
  188.         if((isset($param['estado']) && strlen(trim($param['estado'])) > 0) || (isset($param['cep']) && strlen(trim($param['cep'])) > 0)){
  189.             $estado $param['estado'];
  190.             $cidade trim($param['cidade']);
  191.             $bairro trim($param['bairro']);
  192.             $logradouro trim($param['logradouro']);
  193.             $cep str_replace(array('-''.'), array(''''), trim($param['cep']));
  194.             $coordenadas WebService::getCoordinates$estado$cidade$bairro$logradouro$cep);
  195.             if(sizeof($coordenadas) > 0){
  196.                 if(strlen($coordenadas['lat']) > 0){
  197.                     TScript::create("
  198.                         map.setCenter({lat: {$coordenadas['lat']}, lng: {$coordenadas['lon']}});
  199.                         map.setZoom(20);
  200.                     ");
  201.                 } else {
  202.                     new TMessage('error''Local não encontrado!');
  203.                 }
  204.             }
  205.         }
  206.     }
  207.     function onEdit($param)
  208.     {
  209.         try
  210.         {
  211.             TSession::setValue('lista_unidade', []);
  212.             if (isset($param['key']))
  213.             {
  214.                 // get the parameter $key
  215.                 $key=$param['key'];
  216.                 
  217.                 // open a transaction with database 'permission'
  218.                 TTransaction::open('permission');
  219.                 
  220.                 // instantiates object System_group
  221.                 $object = new PontosRonda($key);
  222.                 
  223.                 // fill the form with the active record data
  224.                 $this->form->setData($object);
  225.                 $criterio = new TCriteria;
  226.                 $criterio->add(new TFilter('id''='$key));
  227.                 $unidades PontosRonda::getObjects($criterio);
  228.                 $lista_unidade = array();
  229.                 foreach ($unidades as $unidade)
  230.                 {
  231.                     //$id = date('Y_m_d_H_i_s') . '_' . rand(0, 9999);
  232.                     $id $unidade->id;
  233.                     
  234.                     $lista_unidade[$id] = $unidade->nome;
  235.                     
  236.                     $item = new stdClass;
  237.                     $item->id $id;
  238.                     $item->unidade $unidade->nome;
  239.                 }
  240.                 TSession::setValue('lista_unidade'$lista_unidade);
  241.                 $data = new stdClass;
  242.                 TForm::sendData('form_SystemUnit'$data);
  243.                 
  244.                 // close the transaction
  245.                 TTransaction::close();
  246.             } else {
  247.                 $this->form->clear();
  248.             }
  249.         } catch (Exception $e) {
  250.             // shows the exception error message
  251.             new TMessage('error'$e->getMessage());
  252.             
  253.             // undo all pending operations
  254.             TTransaction::rollback();
  255.         }
  256.     }
  257.     function onSave()
  258.     {
  259.         try
  260.         {
  261.             // open a transaction with database 'permission'
  262.             TTransaction::open('permission');
  263.             
  264.             // get the form data into an active record System_group
  265.             $data $this->form->getData();
  266.             $this->form->validate();
  267.             $object = new PontosRonda;
  268.             $object->fromArray( (array) $data );
  269.             $object->store();
  270.             
  271.             $data = new stdClass;
  272.             $data->id $object->id;
  273.             TForm::sendData('form_SystemUnit'$data);
  274.             
  275.             TTransaction::close(); // close the transaction
  276.             TApplication::loadPage('CadastroRonda''showMessage');
  277.         }
  278.         catch (Exception $e// in case of exception
  279.         {
  280.             // shows the exception error message
  281.             new TMessage('error'$e->getMessage());
  282.             
  283.             // undo all pending operations
  284.             TTransaction::rollback();
  285.         }
  286.     }
  287.     public static function generateSerial() {
  288.         $chars = array(0,1,2,3,4,5,6,7,8,9,'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z');
  289.         $sn '';
  290.         $max count($chars) - 1;
  291.         
  292.         for($i 0$i 9$i++){
  293.             $sn .= (!($i 3) && $i'' '') . $chars[rand(0$max)];
  294.         }
  295.         return $sn;
  296.     }
  297.     public static function checkSerial($serial){
  298.         $licencas = [];
  299.         try{
  300.             // open a transaction with database 'permission'
  301.             TTransaction::open('permission');
  302.             $criterio = new TCriteria;
  303.             $criterio->add(new TFilter('serial''like'"{$serial}"));
  304.             $licencas SerialCaixa::countObjects($criterio);
  305.             TTransaction::close(); // close the transaction
  306.         } catch (Exception $e) {
  307.             // undo all pending operations
  308.             TTransaction::rollback();
  309.         }
  310.         return ($licencas >= 1);
  311.     }
  312.     public static function getSerial(){
  313.         $serial SystemUnitForm::generateSerial();
  314.         while(SystemUnitForm::checkSerial($serial)){
  315.             $serial SystemUnitForm::generateSerial();
  316.         }
  317.         return $serial;
  318.     }
  319.     public static function getTipos(){
  320.         return array(=> 'Portão'=> 'Lâmpada');
  321.     }
  322. }

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


LC

No onSave tem que vir um ID da tabela, e, nesse caso não deve ta vindo.
Dai sem o ID o sistema vai criar um novo registro na tabela.
PA

Muito obrigado Leandro, esse realmente foi o problema. =D
PA

Muito obrigado Leandro, esse realmente foi o problema. =D