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:
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:
- <?php
- /**
- * SystemUnitForm
- *
- * @version 1.0
- * @package control
- * @subpackage admin
- * @author Pablo Dall'Oglio
- * @copyright Copyright (c) 2006 Adianti Solutions Ltd. (http://www.adianti.com.br)
- * @license http://www.adianti.com.br/framework-license
- */
- class GoogleMaps extends TStandardForm
- {
- protected $form; // form
- /**
- * Class constructor
- * Creates the page and the registration form
- */
- function __construct()
- {
- parent::__construct();
- $this->setDatabase('permission'); // defines the database
- $this->setActiveRecord('SystemUnit'); // defines the active record
- // creates the form
- $this->form = new BootstrapFormBuilder('form_SystemUnit');
- $this->form->setFormTitle('Cadastrar pontos de ronda');
- // create the form fields
- $nome = new TEntry('nome');
- //$unit_id = new TDBCombo('fk_id_system_unit','permission','SystemUnit','id','name');
- $estado = new TCombo('estado');
- $cidade = new TEntry('cidade');
- $bairro = new TEntry('bairro');
- $logradouro = new TEntry('logradouro');
- $cep = new TEntry('cep');
- $buscar = TButton::create('buscar', array($this, 'onSearchAddress'), 'Localizar', 'fa:search blue');
- $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'));
- $cep->setMask('99.999-999');
- $latitude = new TEntry('latitude');
- $longitude = new TEntry('longitude');
- $mapaDenuncia = new TElement('div');
- $mapaDenuncia->id = 'mapaDenuncia';
- $mapaDenuncia->style = 'width:100%; height:500px; min-height:200px; border:1px solid gray; padding:4px; margin: auto; text-align: center;';
- //não permirtir edição
- $latitude->setEditable(false);
- $longitude->setEditable(false);
- //definir um tamanho
- $nome->setSize('89%');
- //$unit_id->setSize('89%');
- $latitude->setSize('70%');
- $longitude->setSize('70%');
- $estado->setSize('70%');
- $cidade->setSize('70%');
- $bairro->setSize('70%');
- $logradouro->setSize('70%');
- $cep->setSize('28%');
- $nome->addValidation( ('Nome'), new TRequiredValidator );
- // add the fields
- $this->form->addFields( [new TLabel('Nome')], [$nome] );
- //$this->form->addFields( [new TLabel('Unidade Matriz')], [$unit_id] );
- $this->form->addFields( [new TLabel('Estado')], [$estado], [new TLabel('Cidade')], [$cidade] );
- $this->form->addFields( [new TLabel('Bairro')], [$bairro], [new TLabel('Logradouro')], [$logradouro] );
- $this->form->addFields( [new TLabel('CEP')], [$cep, $buscar] );
- $this->form->addFields( [new TLabel('Latitude')], [$latitude], [new TLabel('Longitude')], [$longitude] );
- $this->form->addContent( [$mapaDenuncia] );
- // create the form actions
- $this->form->addAction(_t('Save'), new TAction(array($this, 'onSave')), 'fa:floppy-o')->class = 'btn btn-sm btn-primary';;
- $this->form->addAction(_t('Clear'), new TAction(array($this, 'onEdit')), 'fa:eraser red');
- $this->form->addAction(_t('Back'),new TAction(array('CadastroRonda','onReload')),'fa:arrow-circle-o-left blue');
- // vertical box container
- $container = new TVBox;
- $container->style = 'width: 100%';
- $container->add(new TXMLBreadCrumb('menu.xml', 'SystemUnitList'));
- $container->add($this->form);
- parent::add($container);
- TScript::create("
- var selectedShape;
- var selectedPoint;
- var selectedMarker;
- function clearMap() {
- if (selectedShape) {
- selectedShape.setMap(null);
- selectedShape = null;
- }
- if(selectedMarker){
- selectedMarker.setMap(null);
- }
- }
- function setSelectedOverlay(shape, marker) {
- clearMap();
- selectedShape = shape;
- selectedMarker = marker;
- shape.setEditable(true);
- }
- function setSelectedPoint(point) {
- if(selectedPoint){
- selectedPoint.setMap(null);
- selectedPoint = null;
- }
- selectedPoint = point;
- }
- var teste = 1;
- var mapOptions = {
- zoom: 12,
- center: {lat: -12.942304, lng: -38.421180},
- styles: [
- { 'featureType': 'administrative', 'elementType': 'labels.text.fill', 'stylers': [ { 'color': '#444444' } ] },
- { 'featureType': 'landscape', 'elementType': 'all', 'stylers': [ { 'color': '#f2f2f2' } ] },
- { 'featureType': 'poi', 'elementType': 'all', 'stylers': [ { 'visibility': 'off' } ] },
- { 'featureType': 'road', 'elementType': 'all', 'stylers': [ { 'saturation': -100 }, { 'lightness': 45 } ] },
- { 'featureType': 'road.highway', 'elementType': 'all', 'stylers': [ { 'visibility': 'simplified' } ] },
- { 'featureType': 'road.arterial', 'elementType': 'labels.icon', 'stylers': [ { 'visibility': 'off' } ] },
- { 'featureType': 'transit', 'elementType': 'all', 'stylers': [ { 'visibility': 'off' } ] },
- { 'featureType': 'water', 'elementType': 'all', 'stylers': [ { 'color': '#46bcec' }, { 'visibility': 'on' } ] }
- ]
- };
- /* Instantiate a directions service. */
- var directionsService = new google.maps.DirectionsService;
- /* Create a map */
- var map = new google.maps.Map(document.getElementById('mapaDenuncia'), mapOptions);
- /* Create a renderer for directions and bind it to the map. */
- var directionsDisplay = new google.maps.DirectionsRenderer({map: map, suppressMarkers: true});
- var drawingManager = new google.maps.drawing.DrawingManager({
- drawingMode: google.maps.drawing.OverlayType.MARKER,
- drawingControl: true,
- drawingControlOptions: {
- position: google.maps.ControlPosition.TOP_CENTER,
- drawingModes: [
- google.maps.drawing.OverlayType.MARKER
- ]
- }
- });
- drawingManager.setMap(map);
- map.addListener('mousemove', function() {
- if(teste == 1){
- teste = 2;
- var center = map.getCenter();
- google.maps.event.trigger(map, \"resize\");
- map.setCenter(center);
- }
- });
- google.maps.event.addListener(drawingManager, 'overlaycomplete', function (e) {
- var overlay = e.overlay;
- if (e.type == google.maps.drawing.OverlayType.MARKER) {
- var lat = overlay.getPosition().lat();
- var lng = overlay.getPosition().lng();
- setSelectedPoint(overlay);
- $('input[name=\"latitude\"]').val(lat);
- $('input[name=\"longitude\"]').val(lng);
- var infowindow = new google.maps.InfoWindow({
- content: 'Seu estabelecimento.'
- });
- overlay.addListener('click', function() {
- infowindow.open(map, overlay);
- });
- }
- });
- var infoWindow = new google.maps.InfoWindow({
- content: 'Seu perímetro.'
- });
- if (navigator.geolocation) {
- navigator.geolocation.getCurrentPosition(function(position) {
- var pos = {lat: position.coords.latitude, lng: position.coords.longitude};
- map.setCenter(pos);
- }, function() {
- handleLocationError(true, infoWindow, map.getCenter());
- });
- } else {
- /* Browser doesn't support Geolocation*/
- handleLocationError(false, infoWindow, map.getCenter());
- }
- function handleLocationError(browserHasGeolocation, infoWindow, pos) {}
- ");
- }
- public static function onSearchAddress($param)
- {
- if((isset($param['estado']) && strlen(trim($param['estado'])) > 0) || (isset($param['cep']) && strlen(trim($param['cep'])) > 0)){
- $estado = $param['estado'];
- $cidade = trim($param['cidade']);
- $bairro = trim($param['bairro']);
- $logradouro = trim($param['logradouro']);
- $cep = str_replace(array('-', '.'), array('', ''), trim($param['cep']));
- $coordenadas = WebService::getCoordinates( $estado, $cidade, $bairro, $logradouro, $cep);
- if(sizeof($coordenadas) > 0){
- if(strlen($coordenadas['lat']) > 0){
- TScript::create("
- map.setCenter({lat: {$coordenadas['lat']}, lng: {$coordenadas['lon']}});
- map.setZoom(20);
- ");
- } else {
- new TMessage('error', 'Local não encontrado!');
- }
- }
- }
- }
- function onEdit($param)
- {
- try
- {
- TSession::setValue('lista_unidade', []);
- if (isset($param['key']))
- {
- // get the parameter $key
- $key=$param['key'];
- // open a transaction with database 'permission'
- TTransaction::open('permission');
- // instantiates object System_group
- $object = new PontosRonda($key);
- // fill the form with the active record data
- $this->form->setData($object);
- $criterio = new TCriteria;
- $criterio->add(new TFilter('id', '=', $key));
- $unidades = PontosRonda::getObjects($criterio);
- $lista_unidade = array();
- foreach ($unidades as $unidade)
- {
- //$id = date('Y_m_d_H_i_s') . '_' . rand(0, 9999);
- $id = $unidade->id;
- $lista_unidade[$id] = $unidade->nome;
- $item = new stdClass;
- $item->id = $id;
- $item->unidade = $unidade->nome;
- }
- TSession::setValue('lista_unidade', $lista_unidade);
- $data = new stdClass;
- TForm::sendData('form_SystemUnit', $data);
- // close the transaction
- TTransaction::close();
- } else {
- $this->form->clear();
- }
- } catch (Exception $e) {
- // shows the exception error message
- new TMessage('error', $e->getMessage());
- // undo all pending operations
- TTransaction::rollback();
- }
- }
- function onSave()
- {
- try
- {
- // open a transaction with database 'permission'
- TTransaction::open('permission');
- // get the form data into an active record System_group
- $data = $this->form->getData();
- $this->form->validate();
- $object = new PontosRonda;
- $object->fromArray( (array) $data );
- $object->store();
- $data = new stdClass;
- $data->id = $object->id;
- TForm::sendData('form_SystemUnit', $data);
- TTransaction::close(); // close the transaction
- TApplication::loadPage('CadastroRonda', 'showMessage');
- }
- catch (Exception $e) // in case of exception
- {
- // shows the exception error message
- new TMessage('error', $e->getMessage());
- // undo all pending operations
- TTransaction::rollback();
- }
- }
- public static function generateSerial() {
- $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');
- $sn = '';
- $max = count($chars) - 1;
- for($i = 0; $i < 9; $i++){
- $sn .= (!($i % 3) && $i? '' : '') . $chars[rand(0, $max)];
- }
- return $sn;
- }
- public static function checkSerial($serial){
- $licencas = [];
- try{
- // open a transaction with database 'permission'
- TTransaction::open('permission');
- $criterio = new TCriteria;
- $criterio->add(new TFilter('serial', 'like', "{$serial}"));
- $licencas = SerialCaixa::countObjects($criterio);
- TTransaction::close(); // close the transaction
- } catch (Exception $e) {
- // undo all pending operations
- TTransaction::rollback();
- }
- return ($licencas >= 1);
- }
- public static function getSerial(){
- $serial = SystemUnitForm::generateSerial();
- while(SystemUnitForm::checkSerial($serial)){
- $serial = SystemUnitForm::generateSerial();
- }
- return $serial;
- }
- public static function getTipos(){
- return array(1 => 'Portão', 2 => 'Lâmpada');
- }
- }
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.
Muito obrigado Leandro, esse realmente foi o problema. =D
Muito obrigado Leandro, esse realmente foi o problema. =D