Title: [SOLVED] :) HELP-ME URGENTLY!!!! VO DATA
Post by: Vander on June 20, 2008, 09:29:09
Hello everyone.. im 12 hours trying to discover why i cant associate in one line expression... the proxy vo object to the view vo object!
since im using bindable for the public var on view... like this
[Bindable] public var usuarioVO:UsuarioVO;
then the text property of fields, are {usuarioVO.nome} etc.. correspondly.. ok
my first confusion starts on proxy.. with all those different approximations that i saw ive tried EVERYTHING hehe but when in the mediator i try to obtain the VO sure i can obtain it
but if i assign just one property it works... like usuarios.usuarioVO = new UsuarioVO; usuarios.usuarioVO.nome = note.getBody( ).nome;
yes.. the field called nome.. update ! cool
but when i try to associate the entire stuff NEVER WORKS.. im going mad
usuarios.usuarioVO = note.getBody( ) as UsuarioVO; never usuarios.usuarioVO = note.getBody( )[0] as UsuarioVO; never
ive played too with the confusion new UsuarioVO with and without () parenthesis (UsuarioVO () and just UsuarioVO);
thats also confusing since the VO dont have a constructor like on some examples dont have too.. and i remember that i maybe seen someone with parenthesis
ive tried too creating a setter on the proxy and associateing view vo directly = proxy vo hmmm i remember that worked when i wanted to clear the fields :) with new VO declaration on the proxy then association... i even got more and more lost... when i just cannot understand the getter... the constructor.. the data... the strange setdata instead sending event.result... and tried many things and im lost... so im writing this as a last resource.. and im so convinced that this is the one of the most (if not the most) problem on the learning curve experience of this total usefull framework that cliff developed..
thanks everyone
Title: Re: HELP-ME URGENTLY!!!! VO DATA
Post by: Tekool on June 21, 2008, 02:37:50
What is the code you use to send the notification in your proxy ?
Are you sure that you send something like : sendNotification( ApplicationFacade.TRYING_EVERYTHING, new UsuarioVO());
If you do not use a real *UsuarioVO* as transport object in your notification, trying to cast it with the *AS* keyword will not be sufficient to recreate the data binding. You must have a real *UsuarioVO* object all the way long. Note that adding or removing parenthesis when constructing an object that do not have constructor changes nothing in AS3 for now.
If you are using Flex or something equivalent, a good starting point to see what really happens is to use the "-keep" compiler parameter in compiler parameters. It will generate all the class used for data-binding in your project and will allow you to use the step by step debugger in it.
Title: Re: HELP-ME URGENTLY!!!! VO DATA
Post by: Vander on June 21, 2008, 03:20:01
ive tried many things
sendNotification( ApplicationFacade.USUARIOS_SUCESSO, event.result, "recolheDados" );
for example
and in the mediator ive already tried with and without creating a new vo before...
but anyway thanks for the reply, im sleeping, i MUST finish this work this weekend :S im hoping very much that i solve this last problem with the puremvc knowledge
Title: Re: HELP-ME URGENTLY!!!! VO DATA
Post by: Tekool on June 21, 2008, 06:46:40
The best you can do is to post a minimal example to illustrate your problem.
Title: Re: HELP-ME URGENTLY!!!! VO DATA
Post by: Vander on June 21, 2008, 09:10:48
ive already posted all the "picks", anyway all the "confusion" who wants a real explanation and example is ME! hehehe
however... much thanks tek... for your attention
take a look
usuarios.usuarioVO = new UsuarioVO( ); usuarios.usuarioVO.nome = note.getBody( ).nome;
this way i can update the "nome field" binding but i wanna all the fields at the same time!!!
usuarios.usuarioVO = note.getBody( ) as UsuarioVO *! just dont work !*
i can obviously, put one by one. field by field... but.. so whats the advantage of the bindable? and we dont want to spend much time of course, writing line by line...
thanks everyone
Title: Re: HELP-ME URGENTLY!!!! VO DATA
Post by: puremvc on June 21, 2008, 11:10:29
I assume 'usuarios' is the name you've given your view component.
So in your UsuariosMediator, place a breakpoint on the line:
usuarios.usuarioVO = note.getBody( ) as UsuarioVO ...and examine the note variable. Is it a UsuarioVO? if not then the proxy failed to send the VO, so move your attention on back into the UsuarioProxy and set a breakpoint on the line:
sendNotification( ApplicationFacade.USUARIOS_SUCESSO, event.result, "recolheDados" ); ...and examine the event variable. Is the result property a UsuarioVO? If not then the service failed to return a valid UsuarioVO.
So what does the service look like? What is the result format set to? Have you set a RemoteClass meta tag on the UsuarioVO in AS to ensure that it is translated to the proper typed object?
[RemoteClass(alias="com.me.myapp.UsuarioVO")]
-=Cliff>
Title: Re: HELP-ME URGENTLY!!!! VO DATA
Post by: Vander on June 21, 2008, 11:35:00
My VO:
package com.msm.AdmMapas.model.vo { /**************************************************** * AS3 CLASS CODE * * * * UsuarioVO.as * * * * transporta dados no objeto Usuario * * * * VO relacionada ao UsuariosProxy * * * * by Vander F. Hiar - 2008 © (based on PureMVC) * ****************************************************/ // associa classe remota [RemoteClass(alias="com.msm.AdmMapas.model.vo.UsuarioVO")] /********** * classe * **********/ // classe bindable [Bindable] public class UsuarioVO { // declara variáveis transientes (que não são enviadas ao servidor) [Transient] public var data_ins:String; [Transient] public var data_upd:String; // declara variáveis da VO public var id_usuario:int; public var id_usuario2:int; public var usuario:String; public var senha:String; public var tipo:int; public var equipe:int; public var level:int; public var end:String; public var nome:String; public var rg:int; public var cpf:int; public var end_num:int; public var comp:String; public var bairro:String; public var cidade:String; public var estado:int; public var cep:int; public var email:String; public var teld:int; public var teln:int; public var celd:int; public var celn:int; public var obs:String; public var arquivo:int; public var id_ins:int; public var id_upd:int; public function UsuarioVO( ) { } } } my proxy:
package com.msm.AdmMapas.model { /**************************************************** * AS3 CLASS CODE * * * * UsuariosProxy.as * * * * proxy para os usuários: * * * * gerencia o modelo relacionado aos usuários * * * * by Vander F. Hiar - 2008 © (based on PureMVC) * ****************************************************/ /*********** * imports * ***********/ // importa interfaces puremvc import org.puremvc.as3.interfaces.*; // importa Proxy puremvc import org.puremvc.as3.patterns.proxy.Proxy; // importa RemoteObject e eventos result e fault import mx.rpc.remoting.mxml.RemoteObject; import mx.rpc.events.ResultEvent; import mx.rpc.events.FaultEvent; // importa fachada do aplicativo import com.msm.AdmMapas.*; // importa mediators do aplicativo import com.msm.AdmMapas.view.*; // importa VO import com.msm.AdmMapas.model.vo.UsuarioVO; import flash.system.System; /********** * classe * **********/ public class UsuariosProxy extends Proxy implements IProxy { // nome único para o proxy public static const NAME:String = "UsuariosProxy"; // declara constantes que sinalizam tipo e modo de usuários manipulados public static const USUARIOS:String = "Usuários"; public static const CLIENTES:String = "Clientes"; public static const ADICAO:String = "adição"; public static const EDICAO:String = "edição";
// declara instância do RemoteObject private var service:RemoteObject; // declara variável que armazena id do usuário logado private var _id_logado:int = 0; // declara variáveis que armazenam tipo e modo de usuários manipulados private var _modo:String; private var _tipo:String; // construtor public function UsuariosProxy( ) { super ( NAME, new UsuarioVO( ) ); service = new RemoteObject( ); service.endpoint = "http://localhost/AdmMapas/amfphp/gateway.php"; service.requestTimeout = 5; service.makeObjectsBindable = true; service.showBusyCursor = true; service.source = "Servicos"; service.destination = "GenericDestination"; service.addEventListener( FaultEvent.FAULT, falha ); service.addEventListener( ResultEvent.RESULT, sucesso ); } // obtém instância da VO public function get usuarioVO( ):UsuarioVO { return data as UsuarioVO; } // obtém id do usuário logado public function get usuarioLogado( ):int { return _id_logado; }
// obtém tipo de usuário manipulado public function get tipoUsuario( ):String { return _tipo; }
// obtém modo de usuário manipulado public function get modoUsuario( ):String { return _modo; } // seta tipo de usuário manipulado public function set tipoUsuario( tipo:String ):void { _tipo = tipo; } // seta modo de usuário manipulado public function set modoUsuario( modo:String ):void { _modo = modo; } /******************* * funcoes remotas * *******************/ public function tentarLogar( tentativa:UsuarioVO ):void { service.tentaLogar( tentativa ); } public function popularGrid( ):void { service.populaGrid( ); } public function inserirUsuario( tabela:String ):void { service.insereDados( usuarioVO, tabela ); } public function lerUsuario( id:int, tabela:String ):void { service.recolheDados( id, tabela ); } /****************** * funcoes locais * ******************/ public function sucesso( event:ResultEvent ):void { if( service.operations.tentaLogar ) { try { _id_logado = event.result[ 0 ].id_usuario; } catch( err:Error ){ } sendNotification( ApplicationFacade.USUARIOS_SUCESSO, event.result.length > 0, "tentaLogar" ); delete service.operations.tentaLogar; } if( service.operations.populaGrid ) { sendNotification( ApplicationFacade.USUARIOS_SUCESSO, event.result, "populaGrid" ); delete service.operations.populaGrid; } if( service.operations.recolheDados ) { sendNotification( ApplicationFacade.USUARIOS_SUCESSO, event.result[0], "recolheDados" ); delete service.operations.recolheDados; } } public function falha( event:FaultEvent ):void { sendNotification( ApplicationFacade.SERVICO_FALHA, event.fault ); } } } my mediator:
package com.msm.AdmMapas.view { /**************************************************** * AS3 CLASS CODE * * * * UsuariosMediator.as * * * * mediator pro Usuarios.mxml: * * * * gerencia o view * * * * by Vander F. Hiar - 2008 © (based on PureMVC) * ****************************************************/ /*********** * imports * ***********/ // importa interfaces puremvc import org.puremvc.as3.interfaces.*; // importa mediator puremvc import org.puremvc.as3.patterns.mediator.Mediator; // importa eventos flash import flash.events.Event; // importa CursorManager mx import mx.managers.CursorManager; // importa fachada do aplicativo import com.msm.AdmMapas.*; // importa proxies do aplicativo import com.msm.AdmMapas.model.*; // importa view components do aplicativo import com.msm.AdmMapas.view.components.*; // importa VO import com.msm.AdmMapas.model.vo.UsuarioVO; // importa utilitários import utils.view.*; import utils.view.components.*; import mx.controls.Button;
/********** * classe * **********/
public class UsuariosMediator extends Mediator implements IMediator { // nome único para o mediator public static const NAME:String = "UsuariosMediator"; // declara proxy público public var usuariosProxy:UsuariosProxy;
// declara instâncias de componentes utilitários ou // componentes opcionais de sistema private var janelaResultado:TWAlert;
// construtor public function UsuariosMediator( viewComponent:Object ) { super( NAME, viewComponent ); // adiciona os listeners emitidos pelo view // exemplo: umView.addEventListener( umView.UM_VIEW_EVENTO, umaFuncao ); usuarios.addEventListener( Usuarios.USUARIOS_ADICIONAR_CLICK, adicionarClick ); // inicializa proxy usuariosProxy = facade.retrieveProxy( UsuariosProxy.NAME ) as UsuariosProxy; // inicializa view se necessário sendNotification( ApplicationFacade.SERVICO_OCUPADO, true ); } // declara o view protected function get usuarios( ):Usuarios { return viewComponent as Usuarios; } // índice das notificações ouvidas override public function listNotificationInterests( ):Array { /* exemplo: return [ ApplicationFacade.UM_EVENTO ];*/ return [ ApplicationFacade.USUARIOS_SUCESSO ]; } // gerencia as notificações ouvidas override public function handleNotification( note:INotification ):void { /* exemplo: switch( note.getName( ) ) { /* case ApplicationFacade.SHOW_UM_VIEW: app.viewManager.selectedIndex = UM_VIEW; // registre o mediator caso não estiver registrado if ( facade.retrieveMediator( UmViewMediator.NAME ) == null ) facade.registerMediator( new UmViewMediator( app.umView ) ); break; } */ switch( note.getName( ) ) { // serviço executado com sucesso case ApplicationFacade.USUARIOS_SUCESSO: // qual serviço? switch( note.getType( ) ) { case "recolheDados": usuarios.usuarioVO = new UsuarioVO( ); usuarios.usuarioVO.nome = note.getBody( ).nome; //usuarios.usuarioVO = usuariosProxy.getData() as UsuarioVO; break; } break; } }
/****************** * funcoes locais * ******************/ // gerencia eventos ouvidos do view /* exemplo: private function umaFuncao( event:Event = null ):void { sendNotification( ApplicationFacade.UM_COMANDO, umView.umVO ); } */ // dispara notificação para inserir dados private function adicionarClick( event:Event = null ):void { //sendNotification( ApplicationFacade.SERVICO_OCUPADO, true ); with( usuariosProxy.usuarioVO ) { id_ins = usuariosProxy.usuarioLogado; nome = usuarios.nome.text; rg = parseInt( usuarios.rg.text ); cpf = parseInt( usuarios.cpf.text ); end = usuarios.end.text; end_num = parseInt( usuarios.end_num.text ); comp = usuarios.comp.text; bairro = usuarios.bairro.text; cidade = usuarios.cidade.text; estado = usuarios.estado.selectedIndex ; cep = parseInt( usuarios.cep.text ); teld = parseInt( usuarios.teld.text ); teln = parseInt( usuarios.teln.text ); celd = parseInt( usuarios.celd.text ); celn = parseInt( usuarios.celn.text ); email = usuarios.email.text; obs = usuarios.obs.text; } switch( usuariosProxy.tipoUsuario ) { case UsuariosProxy.USUARIOS: with( usuariosProxy.usuarioVO ) { usuario = usuarios.usuario.text; senha = usuarios.senha.text; tipo = usuarios.tipo.selectedItem.ordinal; equipe = usuarios.equipe.selectedItem.ordinal; level = usuarios.level.selectedItem.ordinal; } usuariosProxy.inserirUsuario( "usuario" ); break; case UsuariosProxy.CLIENTES: with( usuariosProxy.usuarioVO ) { usuario = ""; senha = ""; tipo = -1; equipe = -1; level = -1; } usuariosProxy.inserirUsuario( "usuario2" ); break; } } } } the script part of the component:
<mx:Script><![CDATA[ // importa VO import com.msm.AdmMapas.model.vo.UsuarioVO; // importa enums de combo import com.msm.AdmMapas.model.enum.*; // define constantes para os eventos do view // exemplo: public static const UM_VIEW_EVENTO:String = "umViewEvento"; public static const USUARIOS_ADICIONAR_CLICK:String = "usuariosAdicionarClick"; // instancia VO bindable [Bindable] public var usuarioVO:UsuarioVO; ]]></mx:Script> and obviously bindables on text..
my servicos.php
the meaning part:
function recolheDados ( $id, $tabela ) { $sql = "SELECT * FROM $tabela WHERE id_" . $tabela . " = $id"; return _query( $sql ); } and yes im including the php vo in the php service
and here is my php vo:
<?php /************************************************************ * PHP CLASS CODE * * * * UsuarioVO.php * * * * transporta dados no objeto Usuario no servidor: * * * * VO relacionada ao UsuariosProxy e Servicos.php * * * * by Vander F. Hiar - 2008 © (based on PureMVC) * ***********************************************************/ /********** * classe * **********/ class UsuarioVO { // associa classe remota public $_explicitType = "com.msm.AdmMapas.model.vo.UsuarioVO"; public $id_usuario; public $id_usuario2; public $nome; public $rg; public $cpf; public $usuario; public $senha; public $tipo; public $equipe; public $level; public $end; public $end_num; public $comp; public $bairro; public $cidade; public $estado; public $cep; public $email; public $teld; public $teln; public $celd; public $celn; public $obs; public $arquivo; public $data_ins; public $id_ins; public $data_upd; public $id_upd; } ?>
Title: Re: HELP-ME URGENTLY!!!! VO DATA
Post by: puremvc on June 21, 2008, 12:19:08
function recolheDados ( $id, $tabela ) { $sql = "SELECT * FROM $tabela WHERE id_" . $tabela . " = $id"; return _query( $sql ); }
Since PHP methods don't expose return type, I can't tell if this is returning a UsuarioVO. I assume _query is doing so, if not that may be your problem. When a service is involved, it's best to figure out on which side of the fence the problem lies before ripping apart either the client or server code. So before proceeding with my in-client debugging suggestions above, use a web debugging proxy such as Charles (www.xk72.com) or ServiceCapture (www.servicecapture.com) to examine the requests leaving the client and the results coming back from the service. Make sure the proper request is being sent and the proper response returned. -=Cliff>
Title: Re: HELP-ME URGENTLY!!!! VO DATA
Post by: Vander on June 21, 2008, 04:06:08
ok, so you mean that there´s no way to return VO from PHP?
Title: Re: HELP-ME URGENTLY!!!! VO DATA
Post by: puremvc on June 21, 2008, 08:18:21
No, that's not what I mean at all. I'm trying to give you pointers on troublshooting the problem. Figure out if its on the client or server and then debug accordingly. Reread the suggestions above.
-=Cliff>
Title: Re: HELP-ME URGENTLY!!!! VO DATA
Post by: Vander on June 21, 2008, 11:47:57
ok, but, im using flex 3, and amfphp
amfphp have the service browser..
the returned stuff that im getting is:
(mx.collections::ArrayCollection)#0 filterFunction = (null) length = 1 list = (mx.collections::ArrayList)#1 length = 1 source = (Array)#2 [0] (Object)#3 arquivo = 0 bairro = "" celd = 0 celn = 0 cep = 0 cidade = "" comp = "" cpf = 333111222 data_ins = "2008-06-06 13:57:55" data_upd = "0000-00-00 00:00:00" end = "" end_num = 0 equipe = 0 estado = "" id_ins = 0 id_upd = 0 id_usuario = 1 level = 0 nome = "Vander Ferreira Hiar" obs = "" rg = 0 senha = "teste" teld = 0 teln = 0 tipo = 0 usuario = "vander" uid = "DE32E9EE-167C-A123-2A43-AF06268BACB8" sort = (null) source = (Array)#2 and if i put on tree view i see
0: (object Object) #1 arquivo: 0 bairro: bla bla bla bla bla (the fields of the bd/vo) with the correct values this can help something?
thanks for attention
Title: Re: HELP-ME URGENTLY!!!! VO DATA
Post by: puremvc on June 22, 2008, 04:53:33
Yes. Your result is an ArrayCollection. When you receive the result at the client, you need to cast event.result to ArrayCollection, then take out the first object, which is your VO.
However it appears the VO inside the ArrayCollection may not have been converted to the right type; it appears to be type Object. All I can say there is look at the docs for AMFPHP and see what's gone wrong on that end. Where you see [object Object] you should be seeing [object UsuarioVO].
-=Cliff>
Title: Re: HELP-ME URGENTLY!!!! VO DATA
Post by: puremvc on June 22, 2008, 04:59:05
Also, double check your RemoteClass tag to be sure the AS3 VO is properly mapped to your PHP VO. And that your _query method is actually creating a UsuarioVO and not a plain object. I think you have to set $_explicitType in the PHP class.
-=Cliff>
Title: Re: HELP-ME URGENTLY!!!! VO DATA
Post by: Vander on June 22, 2008, 05:15:28
hmmm. sounds interesting
i would like to mention that, if you take a look on the posted codes... u can see the mappings, and the explicittype definition
_query method, just returns a mysql_query method :)
what u said about array its true
because for me access the properties i must use event.result[0]
and as i said previously, if i try to retrieve the properties one by one it works like event.result[0].nome etc but entirely i cant like usuario.usuarioVO = event.result[0] <- doesnt work usuario.usuarioVO.nome = event.result[0].nome <- works
its the last thing that i need to resolve.. to deliver my work too much delayed :) sorry some incovenience and much thanks cliff
Title: Re: HELP-ME URGENTLY!!!! VO DATA
Post by: puremvc on June 22, 2008, 09:38:14
Sorry my last response was from a phone, hard to review code.
Sounds like you just need to assemble a UsuarioVO on the PHP side and return that. Just returning a raw query value is just returning an ArrayCollection of plain Objects. You need to create a new UsuarioVO instance and populate it with the query results, the return that.
-=Cliff>
Title: Re: HELP-ME URGENTLY!!!! VO DATA
Post by: Vander on June 22, 2008, 09:45:30
Yes it have much sense! ive thinked this together with your last post...
if i create a new usuariovo on php, i can retrieve it but do you know how can i automatize using for... to populate automatically?
very thankx cliff
function recolheDados ( $id, $tabela ) { $sql = "SELECT * FROM $tabela WHERE id_" . $tabela . " = $id"; $teste = new UsuarioVO( ); $teste->nome="van"; return _query( $sql ); } this code is wrong.. because its returning the query... as object but im posting to show you.. because if i return $teste.. it cames as UsuarioVO :) but do you know how to create a routine that parses query and puts automagically, a iterated loop.. that puts all variables inside the object to return?
very thanks
Title: Re: HELP-ME URGENTLY!!!! VO DATA
Post by: Vander on June 22, 2008, 11:32:03
hey cliff got it
function recolheDados ( $id, $tabela ) { $sql = "SELECT * FROM $tabela WHERE id_" . $tabela . " = $id"; $objeto = new UsuarioVO(); $query = mysql_fetch_array(_query($sql)); foreach ($query as $key => $value) { $objeto->$key = $value; } return $objeto; }
just one last problem since ive created a dynamic function how can i tell it to instantiate the correct type of object, based on table that ive passed no argument?
$objeto = new UsuarioVO(); <- how to dynamically change UsuarioVO for another VO depending of the table passed? theres no way? i will must do a switch case?
thanks for all
Title: Re: HELP-ME URGENTLY!!!! VO DATA
Post by: Vander on June 22, 2008, 11:36:00
hmm another strange behaviour
the result are doubled
(Object)#0 0 = "1" 1 = "vander" 10 = "0" 11 = "" 12 = "" 13 = "" 14 = "" 15 = "0" 16 = "0" 17 = "0" 18 = "0" 19 = "0" 2 = "teste" 20 = "" 21 = "0" 22 = "2008-06-06 13:57:55" 23 = "0" 24 = "0000-00-00 00:00:00" 25 = "0" 3 = "0" 4 = "0" 5 = "Vander Ferreira Hiar" 6 = "0" 7 = "333111222" 8 = "0" 9 = "" arquivo = "0" bairro = "" celd = "0" celn = "0" cep = "0" cidade = "" comp = "" cpf = "333111222" data_ins = "2008-06-06 13:57:55" data_upd = "0000-00-00 00:00:00" email = (null) end = "" end_num = "0" equipe = "0" estado = "" id_ins = "0" id_upd = "0" id_usuario = "1" id_usuario2 = (null) level = "0" nome = "Vander Ferreira Hiar" obs = "" rg = "0" senha = "teste" teld = "0" teln = "0" tipo = "0" usuario = "vander" i cant figure out why .. since im returning only the $object why its filling with field name and index together?
i guess that im lacking of php knowledge a bit.
thanks for help.. and i have sure that it will help many ppl with the same problem!
Title: Re: HELP-ME URGENTLY!!!! VO DATA
Post by: puremvc on June 22, 2008, 11:39:52
Yep, that's where my knowledge starts to run a little thin as well. I'm not a PHP guy. I'll be picking it up soon, but for now, I'm at a loss to tell you what's going wrong there.
Again, you might want to look into WebORB. I believe it automates a lot of this for you.
-=Cliff>
Title: Re: HELP-ME URGENTLY!!!! VO DATA
Post by: Vander on June 22, 2008, 12:12:54
SOLVED!
instead of using mysql_fetch_array, i must use mysql_fetch_assoc
and i can use dynamic name :)
so the code is
// function for dynamic data read, with class mapping :) function recolheDados ( $id, $tabela, $voname ) { $sql = "SELECT * FROM $tabela WHERE id_" . $tabela . " = $id"; $objeto = new $voname(); $query = mysql_fetch_assoc(_query($sql)); foreach ($query as $key => $value) { $objeto->$key = $value; } return $objeto; }
|