PA
Problema com datagrid
Boa tarde, prezados,
Estou desenvolvendo um formulário onde possui os campos, em seguida um mapa com a api do google maps e em baixo do mapa um datagrid que quero colocar os pontos do mapa, porém ao preencher o campos e clicar no botão para adicionar o ponto na datagrid, a página carrega e não é preenchido o campo, se alguém puder ajudar serei muito grato.
Segue abaixo o código:
Estou desenvolvendo um formulário onde possui os campos, em seguida um mapa com a api do google maps e em baixo do mapa um datagrid que quero colocar os pontos do mapa, porém ao preencher o campos e clicar no botão para adicionar o ponto na datagrid, a página carrega e não é preenchido o campo, se alguém puder ajudar serei muito grato.
Segue abaixo o código:
- <?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 CadastrarPonto 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('PontosRonda'); // defines the active record
- // creates the form
- $this->form = new BootstrapFormBuilder('form_PontosRonda');
- $this->form->setFormTitle('Teste123');
- // create the form fields
- $id = new TEntry('id');
- $nome_unidade = new TEntry('nome_unidade');
- $id_unidade = new THidden('id_unidade');
- $nome = new TEntry('nome');
- $codigo_pin = new TEntry('codigo_pin');
- $estado = new TCombo('estado');
- $cidade = new TEntry('cidade');
- $bairro = new TEntry('bairro');
- $logradouro = new TEntry('logradouro');
- $cep = new TEntry('cep');
- $latitude = new TEntry('latitude');
- $longitude = new TEntry('longitude');
- $buscar = TButton::create('buscar', array($this, 'onSearchAddress'), 'Localizar', 'fa:search blue');
- $adicionar = TButton::create('adicionar', array($this, 'onAddPoint'), 'Adicionar ponto', 'fa:plus green');
- $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');
- $mapaDenuncia = new TElement('div');
- $mapaDenuncia->id = 'mapaDenuncia';
- $mapaDenuncia->style = 'width:100%; height:400px; min-height:200px; border:1px solid gray; padding:4px; margin: auto auto 30px auto; text-align: center;';
- $id->setEditable(FALSE);
- $latitude->setEditable(false);
- $longitude->setEditable(false);
- $id->setSize('12%');
- $nome_unidade->setSize('70%');
- $nome->setSize('70%');
- $codigo_pin->setSize('70%');
- $estado->setSize('70%');
- $cidade->setSize('70%');
- $bairro->setSize('70%');
- $logradouro->setSize('70%');
- $cep->setSize('27.8%');
- $latitude->setSize('70%');
- $longitude->setSize('73.5%');
- //criar botão
- $add_unidade = TButton::create('add_unidade', array($this,'onAddUnidade'), _t('Add'), 'fa:plus green');
- //criar datagrid
- $this->listagem_pontos = new BootstrapDatagridWrapper(new TQuickGrid);
- $this->listagem_pontos->setHeight(200);
- $this->listagem_pontos->makeScrollable();
- $this->listagem_pontos->style='width: 100%';
- $this->listagem_pontos->id = 'lista_unidade';
- $this->listagem_pontos->disableDefaultClick();
- $this->listagem_pontos->addQuickColumn('', 'edit', 'center', '5%');
- $this->listagem_pontos->addQuickColumn('', 'delete', 'center', '5%');
- $this->listagem_pontos->addQuickColumn('Pontos', 'unidade', 'center', '90%');
- $this->listagem_pontos->createModel();
- //formulário da localização
- $this->form->addFields( [new TLabel('Id')], [$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] );
- $label2 = new TLabel('', '#000000', 12, 'bi');
- $label2->style='text-align: center; border-bottom: 1px solid #c0c0c0; width: 100%';
- $this->form->addContent( [$label2] );
- //formulário dos pontos
- $this->form->addFields( [new TLabel('Nome')], [$nome], [new TLabel('PIN')], [$codigo_pin] );
- $this->form->addFields( [new TLabel('Latitude')], [$latitude], [new TLabel('Longitude')], [$longitude, $adicionar] );
- //mapa
- $this->form->addContent( [$mapaDenuncia] );
- //datagrid dos pontos
- $this->form->addFields( [new TLabel('Nome')], [$nome_unidade, $add_unidade] );
- $this->form->addContent( [$this->listagem_pontos] );
- // create the form actions
- $btn = $this->form->addAction(_t('Save'), new TAction(array($this, 'onSave')), 'fa:floppy-o');
- $btn->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', 'CadastroRonda'));
- $container->add($this->form );
- parent::add($container);
- TScript::create("
- var pontos = [];
- function removePoint(id){
- pontos[id].setMap(null);
- }
- function addPonto(){
- Adianti.waitMessage = 'Carregando';
- __adianti_post_data('form_PontosRonda', 'class=GoogleMaps&method=onAddPoint&static=1');
- return false;
- }
- var mapOptions = {
- zoom: 13,
- center: {lat: -12.984588, lng: -38.485411},
- 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});
- google.maps.event.addListener(map, 'click', function (e) {
- var point0 = new google.maps.Marker({
- position: e.latLng,
- draggable: false,
- map: map,
- title: 'Perímetro'
- });
- pontos[pontos.length] = point0;
- var lat = e.latLng.lat();
- var lng = e.latLng.lng();
- $('input[name=\"latitude\"]').val(lat);
- $('input[name=\"longitude\"]').val(lng);
- /*addPonto();*/
- });
- 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) {}
- ");
- }
- //função para filtrar com funções php
- public static function test_input($data) {
- $data = trim($data);
- $data = stripslashes($data);
- $data = htmlspecialchars($data);
- return $data;
- }
- 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(17);
- ");
- } else {
- new TMessage('error', 'Local não encontrado!');
- }
- }
- }
- }
- public static function onAddPoint($param)
- {
- if(isset($param['nome']) && strlen(trim($param['nome'])) > 0 && isset($param['latitude']) && strlen(trim($param['latitude'])) > 0 && isset($param['longitude']) && strlen(trim($param['longitude'])) > 0){
- $pontos = TSession::getValue('lista_pontos');
- $novoPonto = new PontosRonda;
- $novoPonto->nome = $param['nome'];
- $novoPonto->latitude = $param['latitude'];
- $novoPonto->longitude = $param['longitude'];
- $novoPonto->codigo_pin = $param['codigo_pin'];
- $pontos[] = $novoPonto;
- TSession::setValue('lista_pontos', $pontos);
- $data = new stdClass;
- $data->nome = '';
- $data->latitude = '';
- $data->longitude = '';
- $data->codigo_pin = '';
- TForm::sendData('form_PontosRonda', $data);
- } else {
- new TMessage('error', 'Informe o nome e as coordenadas do ponto');
- }
- }
- public static function onRemovePoint($param){
- $pontos = TSession::getValue('lista_pontos');
- unset($ponto[$param['id']]);
- TSession::setValue('lista_pontos', $pontos);
- TScript::create("removePoint(" . $param['key'] . ");");
- }
- public static function updateUnidadeDatagrid($listagem_pontos){
- TScript::create('$(\'table[id="listagem_pontos"] tbody\').empty();');
- foreach ($listagem_pontos as $key => $value) {
- $i = new TElement('i');
- $i->{'class'} = 'fa fa-pencil-square-o blue';
- $btn1 = new TElement('a');
- $btn1->{'onclick'} = "__adianti_ajax_exec(\'class=TESTE123&method=editUnidade&id=$key\');";
- $btn1->{'class'} = 'btn btn-default btn-sm';
- $btn1->add($i);
- $i = new TElement('i');
- $i->{'class'} = 'fa fa-trash red';
- $btn2 = new TElement('a');
- $btn2->{'onclick'} = "__adianti_ajax_exec(\'class=TESTE123&method=confirmDeleteUnidade&id=$key\');";
- $btn2->{'class'} = 'btn btn-default btn-sm';
- $btn2->add($i);
- $tr = new TTableRow;
- $tr->{'class'} = 'tdatagrid_row_odd';
- $tr->{'style'} = 'width: 100%;display: inline-table;';
- $cell = $tr->addCell( $btn1 );
- $cell->{'style'}='text-align:center';
- $cell->{'class'}='tdatagrid_cell';
- $cell->{'width'} = '5%';
- $cell = $tr->addCell( $btn2 );
- $cell->{'style'}='text-align:center';
- $cell->{'class'}='tdatagrid_cell';
- $cell->{'width'} = '5%';
- $cell = $tr->addCell( $value );
- $cell->{'style'}='text-align:center';
- $cell->{'class'}='tdatagrid_cell';
- $cell->{'width'} = '5%';
- TScript::create("tdatagrid_add_serialized_row('listagem_pontos', '$tr');");
- }
- }
- public static function confirmDeleteUnidade($param)
- {
- // define the delete action
- $action = new TAction(array('TESTE123', 'deleteUnidade'));
- $action->setParameters($param); // pass the key parameter ahead
- // shows a dialog to the user
- new TQuestion(AdiantiCoreTranslator::translate('Do you really want to delete ?'), $action);
- }
- public static function deleteUnidade($param)
- {
- $listagem_pontos = TSession::getValue('listagem_pontos');
- unset($listagem_pontos[ $param['id'] ]);
- TSession::setValue('listagem_pontos', $listagem_pontos);
- CadastrarPonto::updateUnidadeDatagrid($listagem_pontos);
- }
- public static function editUnidade($param)
- {
- $listagem_pontos = TSession::getValue('listagem_pontos');
- $data = new stdClass;
- $data->id_unidade = $param['id'];
- $data->nome_unidade = $listagem_pontos[ $param['id'] ];
- TForm::sendData('form_PontosRonda', $data);
- }
- public static function onAddUnidade($param)
- {
- if(isset($param['nome_unidade']) && strlen(trim($param['nome_unidade'])) > 0){
- $id = date('Y_m_d_H_i_s') . '_' . rand(0, 9999);
- if(isset($param['id_unidade']) && strlen(trim($param['id_unidade'])) > 0){
- $id = $param['id_unidade'];
- }
- $listagem_pontos = TSession::getValue('listagem_pontos');
- $listagem_pontos[$id] = trim($param['nome_unidade']);
- TSession::setValue('listagem_pontos', $listagem_pontos);
- CadastrarPonto::updateUnidadeDatagrid($listagem_pontos);
- $data = new stdClass;
- $data->id_unidade = '';
- $data->nome_unidade = '';
- TForm::sendData('form_PontosRonda', $data);
- }
- }
- function onEdit($param)
- {
- try
- {
- TSession::setValue('listagem_pontos', []);
- 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('fk_id_ponto_ronda', '=', $key));
- $unidades = PontosRonda::getObjects($criterio);
- $script = "
- var point0 = new google.maps.Marker({
- position: {lat: {$object->latitude}, lng: {$object->longitude}},
- draggable: false,
- map: map,
- title: 'Perímetro'
- });
- pontos[0] = point0;
- ";
- $lista_pontos = array();
- $lista_pontos[0] = $object;
- $indice = 1;
- foreach ($pontos as $ponto)
- {
- //$id = date('Y_m_d_H_i_s') . '_' . rand(0, 9999);
- $id = $ponto->id;
- $lista_pontos[$id] = $ponto;
- $script .= "
- var point{$indice} = new google.maps.Marker({
- position: {lat: {$ponto->latitude}, lng: {$ponto->longitude}},
- draggable: false,
- map: map,
- title: 'Perímetro'
- });
- pontos[$indice] = point{$indice};
- ";
- $item = new stdClass;
- $item->id = $id;
- $item->ponto = $ponto->nome;
- $indice++;
- }
- $listagem_pontos = array();
- foreach ($unidades as $unidade)
- {
- //$id = date('Y_m_d_H_i_s') . '_' . rand(0, 9999);
- $id = $unidade->id;
- $listagem_pontos[$id] = $unidade->nome;
- $item = new stdClass;
- $item->id = $id;
- $item->unidade = $unidade->nome;
- $i = new TElement('i');
- $i->{'class'} = 'fa fa-pencil-square-o blue';
- $btn1 = new TElement('a');
- $btn1->{'onclick'} = "__adianti_ajax_exec('class=TESTE123&method=editUnidade&id={$id}');";
- $btn1->{'class'} = 'btn btn-default btn-sm';
- $btn1->add( $i );
- $i = new TElement('i');
- $i->{'class'} = 'fa fa-trash red';
- $btn2 = new TElement('a');
- $btn2->{'onclick'} = "__adianti_ajax_exec('class=TESTE123&method=confirmDeleteUnidade&id={$id}');";
- $btn2->{'class'} = 'btn btn-default btn-sm';
- $btn2->add( $i );
- $item->edit = $btn1;
- $item->delete = $btn2;
- $tr = $this->listagem_pontos->addItem($item);
- $tr->{'style'} = 'width: 100%;display: inline-table;';
- }
- TSession::setValue('listagem_pontos', $listagem_pontos);
- TSession::setValue('lista_pontos', $lista_pontos);
- $data = new stdClass;
- TForm::sendData('form_PontosRonda', $data);
- TScript::create("
- {$script}
- map.setCenter(new google.maps.LatLng({$object->latitude}, {$object->longitude}));
- map.setZoom(15);
- ");
- // 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 onEdit2($param)
- {
- try
- {
- TSession::setValue('listagem_pontos', []);
- if (isset($param['key']))
- {
- // get the parameter $key
- $key=$param['key'];
- // open a transaction with database 'permission'
- TTransaction::open('permission');
- // instantiates object
- $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);
- $listagem_pontos = array();
- foreach ($unidades as $unidade)
- {
- //$id = date('Y_m_d_H_i_s') . '_' . rand(0, 9999);
- $id = $unidade->id;
- $listagem_pontos[$id] = $unidade->nome;
- $item = new stdClass;
- $item->id = $id;
- $item->unidade = $unidade->nome;
- }
- TSession::setValue('listagem_pontos', $listagem_pontos);
- $data = new stdClass;
- TForm::sendData('form_PontosRonda', $data);
- TScript::create("
- selectedPoint = new google.maps.Marker({
- position: {lat: {$object->latitude}, lng: {$object->longitude}},
- draggable: false,
- map: map,
- title: 'Perímetro'
- });
- map.setCenter(new google.maps.LatLng({$object->latitude}, {$object->longitude}));
- map.setZoom(15);
- ");
- // 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();
- $listagem_pontos = TSession::getValue('listagem_pontos');
- $lista = TSession::getValue('lista_pontos');
- PontosRonda::updateUnidadeDatagrid($listagem_pontos);
- $this->form->validate();
- $object = new PontosRonda;
- $object->fromArray( (array) $data );
- $object->store();
- $unitsToMaintain = [];
- foreach ($listagem_pontos as $key => $value) {
- if(strpos($key, '_') !== false){
- $elemento = new PontosRonda;
- } else {
- $elemento = new PontosRonda($key);
- }
- $elemento->id = $object->id;
- $elemento->nome = $value;
- $elemento->store();
- $unitsToMaintain[] = $elemento->id;
- }
- if(sizeof($unitsToMaintain) > 0){
- PontosRonda::where('id', '=', $object->id)->where('id', 'NOT IN', $unitsToMaintain)->delete();
- } else {
- PontosRonda::where('id', '=', $object->id)->delete();
- }
- if(sizeof($lista) > 0){
- // open a transaction with database 'permission'
- TTransaction::open('permission');
- if($data->id){
- PontosRonda::where('fk_id_ponto_ronda', '=', $data->id)->delete();
- $ponto = new PontosRonda($data->id);
- $ponto->delete();
- }
- $fk = null;
- foreach ($lista as $ponto) {
- $ponto->id = null;
- $ponto->nome = TESTE123::test_input($ponto->nome);
- $ponto->fk_id_ponto_ronda = $fk;
- $ponto->store();
- if($fk == null){
- $fk = $ponto->id;
- }
- }
- TTransaction::close(); // close the transaction
- TApplication::loadPage('CadastroRonda', 'showMessage');
- } else {
- new TMessage('error', 'Informe pelo menos um ponto da ronda!');
- }
- 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();
- }
- }
- }