Flex Sistema Imobiliário - Detalhes do Código Flex System Property - Details of the Code


A pedido do José Carlos Fonseca, aqui ficam algumas explicações e detalhes de partes de código usadas no meu sistema imobiliário, assim ajudo-o e posso ajudar mais gente interessada. At the request of Jose Carlos Fonseca, here are some explanations and details of parts of my system code used in real estate, so help him and I can help more people interested.

P: 1.Na primeira página surge uma imagem “loading” com efeito como fazes? Q: 1.Na front page a picture emerges "loading" as indeed are you doing?

R: 1. A: 1. O efeito loading é conseguido atravéz da substituição do “loader” normal do flex por uma imagem, podes ver aqui http://www.onflex.org/ted/2006/07/flex-2-preloaders-swf-png-gif-examples.php onde encontras gif, png, swf e exemplos com código fonte. The loading effect is achieved through the replacement of "loader" normal flex by an image, you can see here http://www.onflex.org/ted/2006/07/flex-2-preloaders-swf-png-gif- examples.php where you can find gif, png, swf and examples with source code. Basta copiares para a pasta da tua aplicação e no <mx:Application …> colocares preloader=”preload.CustomPreloader”. Just copiares to the folder of your application and <mx:Application …> colocares preloader = "preload.CustomPreloader." Eu fiz umas pequenas implementações baseadas nesse exemplo, mas se se usar assim funciona na mesma. I made some small deployments based in this example, but if we use works well in it.

P:2.Pagina de login: efeito de erro, “checking login” ea barra azul Q: 2.Pagina the login: effect of error, "checking log" and the blue bar

R: 2.A barra azul é uma progressBar: A: 2.The blue bar is a progressBar:

1: < mx:ProgressBar visible =”false” x =”112″ y =”175″ 1: <mx: ProgressBar visible = "false" x = "112" and = "175"

2: labelPlacement =”left” label =” “ width =”187″ 2: labelPlacement = "left" label = "" width = "187"

3: indeterminate =”true” showEffect =”{Fade}” hideEffect =”{Fade}” 3: indeterminate = "true" showEffect = "Fade ()" hideEffect = "Fade ()"

4: id =”progressStatus” /> 4: id = "progressStatus" />

que é activada (progressStatus.visible=true;) quando inicias o pedido para verificar o login no remoteObject (send) e desactivada quando recebes a resposta do remoteObject (result). that is activated (progressStatus.visible = true;) when the initial request to check the log in remoteObject (send) and when you get off the response of remoteObject (result). (progressStatus.visible=false;) (progressStatus.visible = false;)

quando recebe o resultado (negativo, o user e pass não condizem) faz o seguinte: when receiving the result (not, the user and pass not match) is the following:

blurRed.target=panelLogin; blurRed.target = panelLogin;

blurRed.play(); blurRed.play ();

onde o panelLogin é o nosso panel de login eo blurRed é o seguinte efeito : panelLogin where is our panel of login and blurRed is the following effect:

1: < mx:Glow id =”blurRed” duration =”700″ 1: <mx: Glow id = "blurRed" duration = "700"

2: alphaFrom =”1.0″ alphaTo =”0.0″ 2: alphaFrom = "1.0" alphaTo = "0.0"

3: blurXFrom =”0.0″ blurXTo =”20.0″ 3: blurXFrom = "0.0" blurXTo = "20.0"

4: blurYFrom =”0.0″ blurYTo =”20.0″ 4: blurYFrom = "0.0" blurYTo = "20.0"

5: color =”0×990000″ /> 5: color = "0 × 990000" />

Quanto ao checking login é o mesmo sistema que em cima, activar ou desactivar a progressStatus já que o Flex ainda não implementa o remoteObject com um event progress. As for checking login is the same system as above, or off the progressStatus since the Flex has not yet implemented the event with a remoteObject progress.

P:3.Pagina principal: efeito nos botões no lado esquerdo Q: 3.Pagina home: effect on the buttons on the left side

R: Quanto aos botões do lado esquerdo, o efeito passa pelo mesmo do erro do painel login, os efeitos são: A: As for the buttons on the left side, the effect is the same panel of the error log, the effects are:

1: < mx:Glow id =”blurBlueIn” duration =”700″ 1: <mx: Glow id = "blurBlueIn" duration = "700"

2: alphaFrom =”1.0″ alphaTo =”0.0″ 2: alphaFrom = "1.0" alphaTo = "0.0"

3: blurXFrom =”0.0″ blurXTo =”20.0″ 3: blurXFrom = "0.0" blurXTo = "20.0"

4: blurYFrom =”0.0″ blurYTo =”20.0″ 4: blurYFrom = "0.0" blurYTo = "20.0"

5: color =”0×900aeef” /> 5: color = "0 × 900aeef" />

6: < mx:Glow id =”blurBlueOut” duration =”700″ 6: <mx: Glow id = "blurBlueOut" duration = "700"

7: alphaFrom =”0.0″ alphaTo =”1.0″ 7: alphaFrom = "0.0" alphaTo = "1.0"

8: blurXFrom =”20.0″ blurXTo =”0.0″ 8: blurXFrom = "20.0" blurXTo = "0.0"

9: blurYFrom =”20.0″ blurYTo =”0.0″ 9: blurYFrom = "20.0" blurYTo = "0.0"

10: color =”0×00aeef” /> 10: color = "0 × 00aeef" />

e no botão basta chama-los nos events mouseOver mouseOut: and the button just called them in mouseOver mouseOut events:

1: < mx:Button width =”85″ height =”73″ label =”button ADD” id =”add” 1: <mx: Button width = "85" height = "73" label = "button ADD" id = "add"

2: icon =”@Embed(source=’imgs/Home_add.png’)” x =”10″ y =”91″ 2: icon = "@ Embed (source = 'imgs / Home_add.png')" = x "10" and = "91"

3: fillColors =”[#000000,#000000]“ fillAlphas =”0″ borderColor =”#525151″ 3: fillColors = [# 000000, # 000000] "fillAlphas =" 0 "borderColor =" # 525151 "

4: color =”#FDFBFB” themeColor =”#535C75″ textRollOverColor =”#2667B0″ 4: color = "# FDFBFB" themeColor = "# 535C75" textRollOverColor = "# 2667B0"

5: useHandCursor =”true” mouseOver =”{buttonOver(add)}” 5: useHandCursor = "true" mouseOver = "(buttonOver (add))"

6: mouseOut =”{buttonOut(add)}” click =”{changeTo(’bsf1′)}” 6: mouseOut = "(buttonOut (add))" click = "(changeTo ( 'bsf1'))"

7: buttonMode =”true” /> 7: buttonMode = "true" />

onde tens: a função buttonOver(id_do_botão) e buttonOut(id_do_botão): where you have: the function buttonOver (id_do_botão) and buttonOut (id_do_botão):

1: private function buttonOver(a:Button): void { 1: private function buttonOver (a: Button): void (

2: blurBlueOut.target=a; 2: blurBlueOut.target = a;

3: blurBlueOut.play(); 3: blurBlueOut.play ();

4: } 4:)

5: private function buttonOut(a:Button): void { 5: private function buttonOut (a: Button): void (

6: blurBlueIn.target=a; 6: blurBlueIn.target = a;

7: blurBlueIn.play(); 7: blurBlueIn.play ();

8: } 8:)

e tens os teus efeitos feitos and you made your purposes

P:4.Como adicionas uma foto na BD? Q: 4.Como added a photo in BD?

R: A foto é adicionada através do php via amfphp, no Flex apenas são seleccionadas as fotos e enviadas via post para um script upload.php que trata do envio para o servidor, e devolve as localizações das fotos que ficam guardadas num array, quando termina de enviar todas as fotos, é chamada uma função do remoteObject que guarda os caminhos das fotos na base de dados (optei por usar caminhos relativos em vez de colocar a foto directamente na base de dados, ja que as fotos podem ser de grande tamanho o que ia encher a base de dados). A: The photo is inserted through the php via amfphp in Flex are only selected the photos and sent by post to a script upload.php dealing with the transmission to the server, and return the locations of the photos that are stored in an array, where ends to send all the pictures, is called a function of remoteObject that guard the paths of the photos in the database (I chose to use relative paths instead put the picture directly in the database, already the pictures can be of great size what would fill the database).

Quanto ao sistema de upload, podes ver aqui um sistema parecido com o que fiz (com código): As the system of uploading, you can see here a system similar to what I did (with code):

http://weblog.cahlan.com/files/file_uploads/FileUpload.html http://weblog.cahlan.com/files/file_uploads/FileUpload.html

onde o upload.php será algo parecido com: http://www.msdevstudio.com/mywork/upload.rar where the upload.php will be something like: http://www.msdevstudio.com/mywork/upload.rar

P:Agora fora da tua aplicação, eu tenho uma tabela com varios itens e quero que apareçam numa pagina cada um como botão, é possível?? Q: Now outside of your application, I have a table with several items and want to appear on one page each as a button, it is possible? E no caso de essa pagina ter um numero predefinido de botões como fazer paginação? And in the case of this page have a default number of buttons how to do paging?

R: Agora o monstro das respostas (nota que escrevi isto sem testar, terás que alterar muitos dos campos, mas o essencial está lá: ) A: Now the monster of responses (note I wrote this without testing, you must change many of the camps, but the essence is there:)

Parte I: Botões em cada elemento da “tabela” Part I: Buttons on each element of the "table"

Quanto aos botões, podes colocar em cada linha da datagrid ou qualquer elemento de listagem um qualquer outro componente, sendo o mais comum, checkbox, listbox, button ou radioButton, ve isto: As for the buttons, you can put in each line of datagrid or any element of a listing any other component, being the most common, checkbox, listbox, button or radioButton, ve this:

http://www.returnundefined.com/files/ItemRendererExample/ (codigo fonte) http://www.returnundefined.com/files/ItemRendererExample/ (source code)

http://www.adobe.com/devnet/flex/quickstart/using_item_renderers/ http://www.adobe.com/devnet/flex/quickstart/using_item_renderers/

mesmo parecido com o que deves querer: even similar to what should want:

http://axel.cfwebtools.com/…/UsingTheItemRendererWithADataGrid.html http://axel.cfwebtools.com/… / UsingTheItemRendererWithADataGrid.html

Estes links têm o view source activo. These links have the view source assets.

Parte II: E no caso de essa pagina ter um número predefinindo de botões como fazer paginação? Part II: And in the case of this page have a number of buttons predefinindo how paging?

Qaunto a fazer a paginação, isso depende muito do tipo de sistema que tens, se tens php mySql podes limitar (LIMIT) a listagem a apenas o que queres, basta criares uma variavel publica para guardares a iniciação da listagem e outra com o número de entradas por pagina: Qaunto to make the layout, it largely depends on the type of system you have, if you can limit php mySql (LIMIT) to the listing only what you want, just create a variable publishes guardares for the initiation of the listing and another with the number of entries per page:

1: public var inicio:Number = 0; 1: public var start: Number = 0;

2: public var porPagina:Number = 10; 2: public var porPagina: Number = 10;

3: //ao ser chamado o Remote objecto, tens que dizer ao php para contruir o pedido sql com as limitações. 3: / / to be called the Remote object, you have to say to php to build the request sql with the limitations.

4: //no flex por exemplo o botão seguinte eo anterior a chamarem a Função goPag(”seguinte”); ou goPag(”anterior”); (consoante o botão.) 4: / / flex for example in the button and following up the call to the staff goPag ( "following"), or goPag ( "up"), (depending on the button.)

5: private function goPag(onde:String): void { 5: private function goPag (where: String): void (

6: if (onde== “seguinte” ) { 6: if (where == "following") (

7: inicio=inicio 10; 7: start = start 10;

8: } 8:)

9: if (onde== “anterior” ) { 9: if (where == "up") (

10: inicio=inicio-10; 10: start = start-10;

11: if (inicio<=0) inicio=0; 11: if (beginning <= 0) beginning = 0;

12: } 12:)

13: remoteObjectBusca.funcaoBusca.arguments.inicial=inicio; //redefinimos os valores 13: remoteObjectBusca.funcaoBusca.arguments.inicial = start; / / reset the values

14: remoteObjectBusca.funcaoBusca.arguments.porPag=porPagina; //redefinimos os valores 14: remoteObjectBusca.funcaoBusca.arguments.porPag = porPagina; / / reset the values

15: remoteObjectBusca.funcaoBusca.send(); 15: remoteObjectBusca.funcaoBusca.send ();

16: } 16:)

onde o remoteObject será algo como (amfphp): where the remoteObject will be something like (amfphp):

1: < mx:RemoteObject id =”remoteObjectBusca” destination =”amfphp” source =”servico.class” > 1: <mx: RemoteObject id = "remoteObjectBusca" destination = "amfphp" source = "servico.class">

2: < mx:method name =”funcaoBusca” result =”{lidaDados(event)}” > 2: <mx: method name = "funcaoBusca" result = "(lidaDados (event))">

3: < mx:arguments > 3: <mx: arguments>

4: < inicial > 4: <initial>

5: {”0″} 5: ( "0")

6: </ inicial > 6: </ initial>

7: < porPag > 7: <porPag>

8: {”10″} 8: ( "10")

9: </ porPag > 9: </ porPag>

10: </ mx:arguments > 10: </ mx: arguments>

11: </ mx:method > 11: </ mx: method>

12: </ mx:RemoteObject > 12: </ mx: RemoteObject>

e onde a função do remote object em php receberá esses parametros e devolverá a matriz de dados (as Object): and where the function of the remote object in php receive these parameters and return the matrix of data (the Object):

1: function funcaoBusca($inicial, $porPag) { 1: function funcaoBusca ($ original, $ porPag) (

2: if (!inicial || $inicial==NULL) $inicial=0; 2: if (! Initial | | $ initial == NULL) $ original = 0;

3: if (!porPag || $porPag==NULL) $porPag=10; 3: if (! PorPag | | $ porPag == NULL) $ porPag = 10;

4: 4:

5: $con=mysql_connect( “host” , “user” , “pass” ); 5: $ con = mysql_connect ( "host", "user", "pass");

6: $sel=mysql_select_db( “Bdados” ); 6: $ sel = mysql_select_db ( "Bdados");

7: 7:

8: $sql= “SELECT * FROM `tabelaDados` LIMIT “ .$inicial. “, “ .$porPag; 8: $ sql = "SELECT * FROM` `tabelaDados LIMIT." $ Original. "." $ PorPag;

9: $res=mysql_query($sql); 9: $ res = mysql_query ($ sql);

10: 10:

11: if ($res) return mysql_fetch_array($res); 11: if ($ res) return mysql_fetch_array ($ res);

12: else return “Error” ; 12: else return "Error";

13: } 13:)

depois só temos que criar no flex a funçâo para ler os dados: only then we must create in the flex funçâo to read the data:

1: [Bindable] 1: [Bindable]

2: public var dadosBusca:Object; 2: public var dadosBusca: Object;

3: pivate function lidaDados( event :ResultEvent): void { 3: pivate function lidaDados (event: ResultEvent): void (

4: if ( event .result== “Error” ) { 4: if (event. == Result "Error") (

5: //erro ao buscar os dados 5: / / error search data

6: } 6:)

7: else dadosBusca= event .result as Object; 7: = else dadosBusca event. The result Object;

8: // a partir daqui tens os dados acessiveis na variavel dadosBusca 8: / / From Here you have the data available in variable dadosBusca

9: // para acederes a cada elemento usas dadosBusca[linha].campoDaBd; 9: / / for access to each element uses dadosBusca [line]. CampoDaBd;

10: } 10:)

Nota: Este código da ultima resposta foi elaborado sem ter sido testado, por isso não sei se contem alguns erros.. Note: This code of the last answer was drawn up without being tested, I do not know if contains some errors .. mas basta testares, não sei se seria bem isto que querias. but just test, I do not know if this would be it wanted.

Bom, acho que consegui explicar tudo.. Well, I think that could explain everything .. dá para perceber? you can understand?

Coloquei as respostas num novo post, já que era uma resposta enorme, e assim pode ajudar mais gente. Put the answers in a new post, since it was a huge response, and thus can help more people.

Abraço.

Deixe um comentário or Deixe um Trackback Leave a comment or Leave Trackback

44 Comentários 44 Comments

  1. José Carlos Fonseca Jose Carlos Fonseca
    Abril 17, 2008 às 7:32 pm | Permalink April 17, 2008 at 7:32 pm | Permalink

    Olá, Hello,

    Desculpa de só agora responder, mas estive fora por uns tempos em trabalho e só voltei ontém. Sorry, only now respond, but I was out for a while at work and only went back ontém.

    Muito obrigado, pela ajuda. Thank you for the help. E que rapidez na resposta. And that speed of response. Mais uma vez obrigado. Thanks again.

    Na resposta à pergunta 4 (Como adicionas uma foto na BD?), mencionas um link, já estive a analizar o código, mas dá-me sempre “IO ERROR”. In answer to question 4 (As an added picture in BD?), To mention a link, to have been analyzing the code, but it gives me always "IO ERROR." Não sei como usar o upload.php. I do not know how to use the upload.php.

    Ajudas-me?? Aid me?

    Um abraço. A hug.

    José Carlos Fonseca Jose Carlos Fonseca
    Fafe - Portugal Fafe - Portugal

  2. Abril 18, 2008 às 6:13 am | Permalink April 18, 2008 at 6:13 am | Permalink

    Em principio o upload.php que dei para download deve funcionar sem qualquer alteração, verifica se os links que fazem referencia ao upload.php estão bem: In principle the upload.php I gave to download should work without any change, there are the links that make reference to upload.php are well:

    private const _strUploadDomain:String = “http://codycodingcowboy.cahlan.com/”; private const _strUploadDomain: String = "http://codycodingcowboy.cahlan.com/";
    private const _strUploadScript:String = _strUploadDomain “files/upload.php”; private const _strUploadScript: String = _strUploadDomain "files / upload.php";

    e na directoria onde é executado o .php deves ter a directoria myFileDir já que no tal upload.php está: and the directory where the runs. php should have the directory myFileDir since in such upload.php is:

    $file_path = $_SERVER['DOCUMENT_ROOT'].”/myFileDir”; $ file_path = $ _SERVER [ 'DOCUMENT_ROOT']."/ myFileDir ";

    se depois destas verificações continuar a dar erro, me indica se fez algumas alterações ao código para poder “investigar” melhor. if after those findings continue to provide error, indicates whether I made some changes to the code to "investigate" better. :)

    cumps.

  3. José Carlos Fonseca Jose Carlos Fonseca
    Abril 21, 2008 às 8:37 pm | Permalink April 21, 2008 at 8:37 pm | Permalink

    Olá Mário, Hello John,

    De facto não tinha o upload.php no directorio certo e não tinha a directoria. In fact was not upload.php on the directory and was not sure the directory. Depois de resolver isto já não me dá erro. After resolve it no longer gives me error. Confirma o upload da imagem e envia para o local. This confirms the upload the image and sends it to the place. No entanto a verificação se a imagem já existe não faz. However the verification if the image is not already there. Vou tentar vêr onde está o problema. I will try to vêr where is the problem.

    Na bd guardas o caminho todo da imagem, certo? In bd guards the way the whole picture, right?

    Agora outra questão, (espero não ser chato!!!). Now another question, (hopefully not boring !!!).

    Como mostro 1 registo da bd directamente num textinput sem ser num datagrid? As the record show 1 bd textinput without being directly in a datagrid?

    Obrigadão pela ajuda. Obrigadão for help.

    Tens sido fantástico. You have been fantastic.

    Um abraço. A hug.

    José Carlos Fonseca Jose Carlos Fonseca
    Fafe - Portugal Fafe - Portugal

  4. Abril 22, 2008 às 5:53 pm | Permalink April 22, 2008 at 5:53 pm | Permalink

    Sim, na base de dados guardo o caminho da imagem já que são muitas imagens e iria sobrecarregar a base de dados. Yes, in the database guardo the path of the image as many images and would overburden the database.

    para mostrar um registo directamente na base de dados num campo de texto podes fazer o seguinte, imagina a função seguinte (que recebe dados do remoteObject): to show a record in the database directly in the text field can do the following, imagine the following function (which receives data from remoteObject):
    imagina que o teu remote object devolve (exemplo em php amfphp) imagine that your remote object returns (example in php amfphp)
    < ?php <? PHP

    function dev() { dev function () (
    //exemplo 1 / / example 1
    return "Ola"; Return "Hello";

    //exemplo 2 / / example 2
    $dados['nome']="soares"; $ data [ 'name'] = "soares";
    $dados['prenome']="joão"; $ data [ 'first name'] = "Julie";
    return $dados; return $ data;

    //exemplo 3 / / example 3
    $dados['antonio']['nome']="sousa"; $ data [ 'antonio'] [ 'name'] = "doener";
    $dados['antonio']['idade']="19"; $ data [ 'antonio'] [ 'age'] = "19";
    $dados['pedro']['nome']="lemos"; $ data [ 'Pedro'] [ 'name'] = "read";
    $dados['pedro']['idade']="25"; $ data [ 'Pedro'] [ 'age'] = "25";

    } )

    ?>
    private function lidaDados(ev:ResultEvent):void { private function lidaDados (ev: ResultEvent): void (
    //exemplo 1, recebe apenas uma variavel: / / example 1, receives only one variable:
    meucampo.text=ev.result meucampo.text = ev.result

    //exemplo 2, recebe um array de variavels: / / example 2, receives an array of variavels:
    meuCampo.text=ev.result.nome; //devolve soares meuCampo.text = ev.result.nome; / / returns soares
    meuCampo.text=ev.result.prenome; //devolve joão meuCampo.text = ev.result.prenome; / / Julie returns

    //exemplo 3, recebe uma “matriz” de arrays: / / example 3, receives a "matrix" of arrays:
    meuCampo.text=ev.result.antonio.nome; //devolve sousa meuCampo.text = ev.result.antonio.nome; / / returns valeria
    meuCampo.text=ev.result.antonio.idade; //devolve 19 meuCampo.text = ev.result.antonio.idade; / / returns 19
    meuCampo.text=ev.result.joao.nome; //devolve lemos meuCampo.text = ev.result.joao.nome; / / returns read
    meuCampo.text=ev.result.joao.idade; //devolve 25 meuCampo.text = ev.result.joao.idade; / / returns 25

    } )

    Para facilitar este processo, cria uma variavel bindable: To facilitate this process, creates a variable bindable:

    [Bindable]
    public var DadosRo:Object; public var DadosRo: Object;

    e depois na função que recebe os dados do RO, coloca and after the function that receives data from the RO, raises

    DadosRo=new Object(); DadosRo = new Object ();

    DadosRo = ev.result as Object; DadosRo = ev.result the Object;

    ea partir daí os seus dados podem ser acedido a partir dessa variavel em qualquer parte do seu código, e serão actualizados sempre que o remoteObject for chamado. and hence their data can be accessed from this variable in any part of your code, and will be updated whenever the remoteObject is called.

    No exemplo 3: In the example 3:
    em vez de meuCampo.text=ev.result.joao.nome; instead meuCampo.text = ev.result.joao.nome;

    poderia usar: could use:
    meuCampo.text=DadosRo.joao.nome; meuCampo.text = DadosRo.joao.nome;

    Deu pra perceber?? It pra understand?

    Abraço.

    Bom, eu não sei se tem seguido a minha série de tutoriais ( http://msdevstudio.com/blog/2008/04/08/adobe-flex-a-partir-do-zero-parte-iv/ ) mas na quarta parte exemplifico um bocado do sistema de comunicação com um backend em php, talvez te possa ajudar a compreender melhor alguns promenores do Flex. Well, I do not know if you have followed my series of tutorials (http://msdevstudio.com/blog/2008/04/08/adobe-flex-a-partir-do-zero-parte-iv/) but in the fourth exemplifico a bit part of the communication system with a backend in php, perhaps you can help us better understand some details of Flex.

  5. José Carlos Fonseca Jose Carlos Fonseca
    Abril 23, 2008 às 9:46 pm | Permalink April 23, 2008 at 9:46 pm | Permalink

    Boas Mário, John Good,

    Simplesmente genial. Simply brilliant. Funcionou direitinho. It worked direitinho.

    Sim!! Yes! Tenho seguido todos os teus tutoriais, estão de mais. I have followed all your tutorials, are more. Se não fosse você concerteza a aprendizagem do flex iria ser mais demorada. If you were not concerteza the learning of flex would be more time consuming. Grande ajuda, Obrigado!! Big help, Thank you!

    (lá vem o chato!!!) Outra questão, eu tenho um viewStack onde para cada um item é um component. (there comes the flat!) Another question, I have a viewStack to where each item is a component. Estes components são accionados por um botão, acontece que depois de visitar uma vez, na proxima visita não faz o refresh. These components are activated by a button, which happens after visiting once, next trip does not refresh.
    É possivel contornar isto? It is possible to circumvent this?

    Se quiseres, podes adicionar o meu email ao messenger. If you wish, you can add my email to IM.

    Mais uma vez obrigado. Thanks again.

    José Carlos Fonseca Jose Carlos Fonseca
    Fafe - Portugal Fafe - Portugal

  6. Abril 25, 2008 às 8:24 pm | Permalink April 25, 2008 at 8:24 pm | Permalink

    Carlos, desculpa só responder agora.. Carlos, excuse only answer now .. tenho andado um pouco atarefado com trabalo :pe se calhar por isso não percebi bem a sua duvida, se o código não for muito extenso coloque aí..senão tente explicar mais detalhadamente.. I have been a little busy with working: foot is perhaps therefore not clear their doubts, if the code is not put there very long .. but try to explain further .. : P

    um abraço. a hug.

  7. José Carlos Fonseca Jose Carlos Fonseca
    Abril 30, 2008 às 11:43 pm | Permalink April 30, 2008 at 11:43 pm | Permalink

    Olá Mário, desde já obrigado pela resposta e não tens que te desculpar. Hello John, now you for answers and you do not have to apologize.
    EStive a rever o meu código e acho que já descobri o erro. EStive to review the code and I think I have discovered the error.
    No entanto gostaria de te colocar outra questão, estou a tentar fazer algo que irá ter acesso atravéz de login. However I would ask you another question, I am trying to do something that will have access through the login. Como é que mostro o ecrã1 para o administrador, o ecrã2 para o utilizador, etc. How do you show the ecrã1 to the administrator, the ecrã2 to the user, and so on. Já tentei, mas acho que ainda estou verde em flex. We have tried, but I think I am still green in flex.

    Obrigado. Thank you.

    Um Abraço. A Abraço.

    José Carlos Fonseca Jose Carlos Fonseca
    Fafe - Portugal Fafe - Portugal

  8. Maio 1, 2008 às 6:11 am | Permalink May 1, 2008 at 6:11 am | Permalink

    Bem Carlos, podes fazer isso de 2 maneiras, agora depende da necessidade ou não de usares um backend (php, java, etc..) Carlos Well, you can do this in 2 ways, now depends on whether or not consumers using a backend (php, java, etc. ..)

    Sem Backend. Without Backend.
    A solução pode passar por definires uma variavél global, ou seja, declaras a variavél, por exemplo The solution can go through definires a variavél overall, or declaras the variavél, for example
    var admin:Boolean = false; var admin: Boolean = false;
    E depois, basta verificares sempre essa variavel quando é pedido acesso à parte de admin. Then, just when verificares always this variable is sought access to part of admin.

    O ideal será separares a tua aplicação por pelo menos 3 states; Login, Admin, User The ideal is separares your application by at least 3 states; Login, Admin, User
    Depois basta fazeres o login, e na funçao que valida o login definires a variavél admin=true; e mudares pro state respectivo, neste caso currentState=”Admin”; ou se for user, admin=false; currentState=”User”; Then just make the log, and the roles that validates the login definires the variavél admin = true, and change their pro state, in this case currentState = "Admin", or if user, admin = false; currentState = "User";

    Outra forma de fazer isso, é usares um backend em php por exemplo, e fazeres uso de sessões, para verificares se o user está identificado como admin ou não… mas assim é um bocado mais extenso, mas se vires que é a melhor forma, diz que eu faço-te um pequeno exemplo. Another way to do this, is using a backend in php for example, and make use of sessions, to verificares if the user is identified as admin or not… but it is a bit more extensive, but if you see what is the best way, says I do you a small example.

    Seria isso que querias? It would be what we wanted?

    Abraço.

  9. José Carlos Fonseca Jose Carlos Fonseca
    Maio 1, 2008 às 10:30 am | Permalink May 1, 2008 10:30 am | Permalink

    Bom dia Mário, Hello John,

    De facto o ideal seria criar um backend em php e usar sessões. In fact the idea would create a backend in php and use sessions. Arranjas-me então um exemplo. Arranjas me an example.

    Obrigado. Thank you.

    Abraço.

    José Carlos Fonseca Jose Carlos Fonseca
    Fafe - Portugal Fafe - Portugal

  10. José Carlos Fonseca Jose Carlos Fonseca
    Maio 2, 2008 às 8:35 pm | Permalink May 2, 2008 at 8:35 pm | Permalink

    Olá Mário, Hello John,

    No teu Sistema Imobiliário a caixa de login não é um popup pois não. As your Real Estate System to the login box is not as a popup not. Usas-te states?? You use yourself states? Tentei fazer o efeito, mas a caixa não surge desde cima e não consigo fazer o efeito final. I tried to do this, but the box does not appear from above and can not make the final effect.

    Na aplicação que estou a tentar fazer acontece algo do género: In applying what I am trying to do is something like:

    - faço o login, entro em vários ecrãs e faço logout sem fechar o browser. -- Do I sign in, enter into various screens and I out without closing the browser. Ao fazer login outra vez entra no último ecrã que estive e não no que está programado para aparecer e os efeitos só são feitos na primeira vez. When you sign in again enter the last screen and I was not in what is scheduled to appear and the effects are only made the first time.

    - E se estiver dentro da aplicação e fizer F5(refresh) sai e pede para fazer login. -- And if you're within the application and make F5 (refresh) comes out and asked to sign.
    Isto é normal? This is normal? Dá para contronar. Grants for contronar.

    Obrigado pela tua ajuda e paciência. Thanks for your help and patience.

    Um abraço. A hug.

    Jose Carlos Fonseca Jose Carlos Fonseca
    Fafe - Portugal Fafe - Portugal

  11. Maio 2, 2008 às 9:45 pm | Permalink May 2, 2008 at 9:45 pm | Permalink

    Bem carlos, o efeito inicial é um simples painel, que é criado no topo da aplicação com visibilidade=false; depois do efeito iniciado é mostrado. Carlos Well, the initial effect is a simple panel, which is created on top of the application with visibility = false; started after the end is shown.
    O efeito final é um simples mx:Move (como o inicial), ambos com a easingFunction=Elastic (mx.effects.easing.Elastic ) e depois visibility=false; quando o efeito termina (podes saber quando o efeito termina, com um eventListner ao efeito, algo como efeito.addEventListener(EffectEvent.EFFECT_END, funcao_que_esconde_o_panel); The final effect is a simple mx: Move (as the original), both with easingFunction = Elastic (mx.effects.easing.Elastic) and then visibility = false; ends when the effect (you can know when the effect ends with a eventListner the end, something like efeito.addEventListener (EffectEvent.EFFECT_END, funcao_que_esconde_o_panel);

    na funcao: in function:
    private function funcao_que_esconde_panel(evt:EffectEvent) { private function funcao_que_esconde_panel (evt: EffectEvent) (
    painel_login.visibility=false; painel_login.visibility = false;
    efeito.removeEventListner(EffectEvent.EFFECT_END, funcao_que_esconde_o_panel); efeito.removeEventListner (EffectEvent.EFFECT_END, funcao_que_esconde_o_panel);
    } )

    Se fizeres isso com eventos, deves remover os eventListners… Do this with events, you should remove the eventListners…

    Quando voltas a fazer o login de novo, na função que verifica a validade do login, indica para ele voltar ao state que queres com a indicação. When laps to make the sign again, the function that checks the validity of the log, it indicates to return to the state you want to alert. this.currentstate=”StateEntrada”; this.currentstate = "StateEntrada";

    Ao fazeres o F5 é normal isso acontecer, o que podes fazer, é com a tal sessão, verificar isso logo na entrada, no login, e se a sessão for válida ele vai directo ao State desejado, não mostrando o painel de login, já que a sessão é mantida quando carregas no F5. To make the F5 is normal that happens, what you can do is with this session, check this once in the entry in the log, and if the session is valid direct the State vai he wanted, showing no sign of the panel, already that the session is held when loading in the F5. Este fim de semana não devo ter muito tempo pra te fazer um exemplo, mas assim que possa eu faço. This end of the week I should not have much time to get you an example, but so can I do.

  12. José Carlos Fonseca Jose Carlos Fonseca
    Maio 11, 2008 às 3:21 pm | Permalink May 11, 2008 at 3:21 pm | Permalink

    Boa tarde Mário, Good afternoon John,

    Podes dar-me uma ajuda? You can give me a hand?

    Após inserir em alguns textinputs, queria que os dados surgissem num datagrid sem gravar na BD. After entering into some textinputs, wanted the data arise in a datagrid without record in BD. E gravar na BD, atraves de um botao, gravar tudo o que estiver na mesma DataGrid. And write to the BD through a button, record everything that is in the same DataGrid.

    Obrigado. Thank you.

  13. Maio 11, 2008 às 6:54 pm | Permalink May 11, 2008 at 6:54 pm | Permalink

    Carlos, o aconselhado é criar um ArrayCollection, e trabalhar todos os seus dados nele, que tanto serve como dataProvider para a dataGrid, bem como para depois o enviar para a base de dados. Carlos, the advice is to create a ArrayCollection, and work all your data on it, which serves as both dataProvider for dataGrid, and to then send to the database.

    Tenho um exemplo no blog que explica como um arrayCollection pode servir para trabalhar com os dados na base de dados. I have an example in the blog that explains how a arrayCollection can serve to work with data in the database.

    veja: http://msdevstudio.com/blog/2008/03/25/flex-datagrid-operaes-no-dataprovider/ See: http://msdevstudio.com/blog/2008/03/25/flex-datagrid-operaes-no-dataprovider/

    Quanto ao gravar na base de dados, enviar esse arrayCollection como parametro para o remoteObject. On the record in the database, send that arrayCollection as parameter for the remoteObject.
    Ve o exemplo, se não conseguires fazer, coloca as tuas duvidas Ve an example, if do not achieve, puts your doubts ;)

    Abraço.

  14. José Carlos Fonseca Jose Carlos Fonseca
    Maio 15, 2008 às 6:56 pm | Permalink May 15, 2008 at 6:56 pm | Permalink

    Olá Mario, Hello Mario,

    já tenho um arrayCollection com os dados. I have a arrayCollection with data.

    no remoteObject seria assim? No remoteObject would be?

    {dados} () data

    em que “dados” é o meu arrayCollection. where "data" is my arrayCollection.

    E no PHP como é que seria para inserir na tabela uma vez que o arrayCollection tem a seguinte estrutura: And in PHP how it would be to insert in the table since the arrayCollection is structured as follows:

    dados = ["campo1, campo2, campo3" data = [ "campo1, campo2, campo3"
    "campo3, campo4, campo5"] "campo3, campo4, campo5"]

    Obrigado! Thank you!

    José Carlos Fonseca Jose Carlos Fonseca
    Fafe - Portugal Fafe - Portugal

  15. Maio 15, 2008 às 9:09 pm | Permalink May 15, 2008 at 9:09 pm | Permalink

    Boas! Good! :-)
    Ora então, considerando a seguinte funçao no php But then, considering the following roles in php

    function insere($dados){ function inserts ($ data) (

    $sql=”INSERT INTO `table` (`campo1`, `campo2`, `campo3`, `campo4`, `campo5`, `campo6`) VALUES (’$dados[0][campo1]‘, ‘$dados[0][campo2]‘, ‘$dados[0][campo3]‘, ‘$dados[1][campo4]‘, ‘$dados[1][campo5]‘, ‘$dados[1][campo6]‘)”; $ sql = "INSERT INTO` table `(` campo1 `,` campo2 `,` campo3 `,` campo4 `,` campo5 `,` `campo6) VALUES ( '$ data [0] [campo1]', '$ data [0] [campo2] ',' $ data [0] [campo3] ',' $ data [1] [campo4] ',' $ data [1] [campo5] ',' $ data [1] [campo6] ') ";

    if(mysql_query($sql)) return “ok”; if (mysql_query ($ sql)) return "ok";
    else return “error :”.mysql_error(); else return "error". mysql_error ();

    } )

    depois basta chamar a funçao no remote object, algo como um metodo assim no then simply call the roles in the remote object, something like a method well in

    mx:remoteObject …resto…como target, detination..> mx: remoteObject rest…… as target, detination ..>
    mx:method name=”insere” result=”insereRes(event)” > mx: method name = "insert" result = "insereRes (event)">
    mx:arguments> MX: arguments>
    dados> data>
    {dados} () data
    /dados> / data>
    /mx:arguments> / MX: arguments>
    /mx:method> / MX: Method>
    /mx:remoteObject> / MX: remoteObject>

    ps faltam as “< ” no inicio de cada linha, porque para colocar o código tem que ser assim! ps lacking the "<" at the beginning of each line, because to put the code has to be that way!

    Isto deve resolver a tua questão… This should solve your question… :)

    Um arrayCollection é tratado como um array de arrays no php, ou a tipica matriz (grelha de dados) e um simples Array é tratado como array… A arrayCollection is treated as an array of arrays in php, or the typical matrix (scale of data) and a simple array is treated as array…

    Esperimenta e diz como correu…. Esperimenta and it went like….

  16. José Carlos Fonseca Jose Carlos Fonseca
    Maio 29, 2008 às 2:34 pm | Permalink May 29, 2008 at 2:34 pm | Permalink

    Olá Mário, Hello John,

    Estive ausente por uns dias por isso é que só agora respondo. I was absent for a few days so it is only now that answer.

    Funcionou impcável! It worked impcável! Obrigado. Thank you.

    Estou a tentar controlar os campos textinput antes de enviar os dados para o datagrid. I am trying to control the camps textinput before sending the data to the datagrid. Só me falta um teste que não estou a conseguir. Only I lack a test that I am not achieve.

    Verificar se o que inserir no textinput já existe no datagrid. Check if you enter the textinput already exists in the datagrid. Podes dar-me uma ajuda? You can give me a hand?

    Obrigado. Thank you.

    José Carlos Fonseca Jose Carlos Fonseca
    Fafe - Portugal Fafe - Portugal

  17. Maio 29, 2008 às 2:41 pm | Permalink May 29, 2008 at 2:41 pm | Permalink

    private function existe(texto:String):Boolean { private function exists (text: String): Boolean (

    var existeV:Boolean; Var existeV: Boolean;

    existeV=false; existeV = false;
    for(var x:int=0; x<meuDataProvider.lenght; x ) { for (var x: int = 0; x <meuDataProvider.lenght; x ) (

    if(String(meuDataProvider[x].campo_a_comparar)==texto) existeV=true; if (String (meuDataProvider [x]. campo_a_comparar) == text) existeV = true;

    } )
    return existeV; Return existeV;
    } )

    para verificar basta usares to verify just using
    if(existe(String(meu_text_imput.text))=true) { //existe } if (there (String (meu_text_imput.text)) = true) (/ /) exists
    else //não existe. else / / does not exist.

    Nota que não testei, mas deve funcionar sem problemas. Note that not tested, but should work without problems.

    Seria isso? It would be this?
    Abraço.

  18. José Carlos Fonseca Jose Carlos Fonseca
    Maio 29, 2008 às 3:29 pm | Permalink May 29, 2008 at 3:29 pm | Permalink

    Boas Mário, John Good,

    Perfeito! Perfect! O meu erro era que não estava a passar para String na condição IF. My mistake was not going on to String on condition IF.

    Mais um pedido de ajuda: Another request for help:

    Tenho em tabelas dados hierarquizados, ou seja, equipamentos->marcas->modelos I have a hierarchical data tables, or equipment-> brands-> models
    EX: Monitores -> ELOTouch -> 15 Polgadas EX: Monitors -> ELOTouch -> 15 Polgadas

    Criar um ecrã para mostrar estes dados o melhor, acho eu, seria atraves de um TreeControl datagrid. Create a screen to show these data the better, I think, would be a TreeControl datagrid.

    No TreeControl aparecia Monitores -> ELOTouch -> 15 Polgadas e no dataGrid os vários dados do respectivo equipamento(nº de serie, cadastro, data, etc) In TreeControl appeared Monitors -> ELOTouch -> 15 Polgadas and dataGrid the various data of their equipment (number of series, registration, date, etc.)

    Será muito trabalhoso fazer isto? It will be very hard to do this? Por acaso tens algum exemplo por onde eu possa guiar? Did you have any example where I can guide? Ainda não encontrei nada na net. Not yet found nothing in the net.

    Obrigado. Thank you.

    José Carlos Fonseca Jose Carlos Fonseca
    Fafe - Portugal Fafe - Portugal

  19. Maio 29, 2008 às 3:44 pm | Permalink May 29, 2008 at 3:44 pm | Permalink

    Bem, realmente os exemplos que se vêm são todos em MXML ou XML também por isso nunca trabalhei com as Tree’s, mas olha para este exemplo: Well, actually the examples which are are all in MXML or XML also why never worked with the Tree's, but look at this example:

    http://blog.flexexamples.com/2007/12/03/using-an-array-as-a-data-provider-in-a-flex-tree-control/ http://blog.flexexamples.com/2007/12/03/using-an-array-as-a-data-provider-in-a-flex-tree-control/

    como dataProvider tem um Array de objectos, isto pode ser recriado em action script e depois só tens que mandar o output do php no mesmo formato, que se já estás a mandar correctamente para o flex, deve servir sem problemas, mas tens que construir os teus dados no php como objectos… as dataProvider has an array of objects, this can be recreated in action script and then just have to mandar the output of php in the same format, which you are already mandar properly for the flex, must serve without problems, but you have to build the php in your data as objects…

    $array['dados']->nome=campoCategoria; $ array [ 'data'] -> name = campoCategoria;
    $array['dados']->conteudo[0]->valor1=Campo1; $ array [ 'data'] -> content [0] -> value1 = Campo1;
    $array['dados']->conteudo[1]->valor2=Campo2; $ array [ 'data'] -> content [1] -> value2 = Campo2;

    mas se eu encontrar algum exemplo eu aviso…. but if I find any example I notice….

    Abraço.

  20. Maio 29, 2008 às 3:47 pm | Permalink May 29, 2008 at 3:47 pm | Permalink

    Nem de proposito, ve aqui: Neither of respect, ve here:

    http://www.adobe.com/devnet/flex/quickstart/working_with_tree/ http://www.adobe.com/devnet/flex/quickstart/working_with_tree/

    junto ao final da pagina tem a criação de um dataProvider para a tree, basta em php usares a mesma estrutura de dados. near the end of the page is the creation of a dataProvider for the tree, just in php using the same data structure.

    o código fonte está em: the source is:
    http://www.adobe.com/devnet/flex/quickstart/working_with_tree/src/TreeKeepOpen/index.html http://www.adobe.com/devnet/flex/quickstart/working_with_tree/src/TreeKeepOpen/index.html

    Abraço.

  21. José Carlos Fonseca Jose Carlos Fonseca
    Maio 29, 2008 às 4:23 pm | Permalink May 29, 2008 at 4:23 pm | Permalink

    Ok, já vou ver e depois digo alguma coisa. Okay, now I see and then say something.

    Já agora: na expressão Already now: the expression
    if(String(dados[x].campo)==texto) existeV=true; if (String (data [x]. field) == text) existeV = true;

    a palavra campo é uma variavel(string) que recebe 3 valores. the word field is a variable (string) which receives 3 values. Conforme está nao funciona pois campo nao pertence a dados. As is not working as it does not belong to field data. Como resolver? How to solve?

    Abraço.

  22. José Carlos Fonseca Jose Carlos Fonseca
    Maio 30, 2008 às 12:32 am | Permalink May 30, 2008 at 12:32 p.m. am |