CRUD with RestfulX: Part 1/2 – Retrieve
Lets create an example to show how to use basic database operations (aka CRUD – Create, Retrieve, Update, and Delete) with RestfulX.
The project is pretty simple and will evolve as I write future articles using this example: an application to control events and people that attend to these events.
Here is our initial database structure defined into db/models.yml (sorry for keeping it in portuguese!):
participante: - nome: string - email: string - data_registro: date evento: - nome: string - local: string - data: date - ativo: boolean
Now lets configure db/seeds.yml to load initial data into the database:
Evento.create(:nome => "Congresso de TI", :local => "Auditorio XYZ", :data => '2010-01-01', :ativo => true) Participante.create(:nome => "Elvis Fernandes", :email => "elvis@exemplo.com", :data_registro => '2009-12-01') Participante.create(:nome => "Jose da Silva", :email => "jose@exemplo.com", :data_registro => '2009-10-12' ) Participante.create(:nome => "Maria da Silva", :email => "maria@exemplo.com", :data_registro => '2009-10-12' )
Now we create the models, migrations, and update the database structure:
ruby script/generate rx_yaml_scaffold rake db:refresh rake db:seed
Here is the code for the screen where we’ll show the retrieved data about our model named Participante. This file is placed into the app/flex/projectname/views folder:
<?xml version="1.0" encoding="utf-8"?>
<mx:Canvas xmlns:mx="http://www.adobe.com/2006/mxml" width="400" height="334">
<mx:Script>
<![CDATA[
import org.restfulx.utils.TypedArray;
import mx.controls.Alert;
import mx.rpc.events.FaultEvent;
import restfulxelvisetibr.models.Participante;
import org.restfulx.Rx;
private function onSuccessResultHandler(models:TypedArray):void
{
lblStatus.text = "Models carregados com sucesso.";
}
private function onFailureResultHandler(event:FaultEvent):void
{
Alert.show("Ocorreu um erro ao listar os participantes", "Erro");
}
]]>
</mx:Script>
<mx:Label x="10" y="10" text="Lista de participantes cadastrados"/>
<mx:DataGrid id="dgParticipantes"
dataProvider="{Rx.models.cached(Participante)}"
x="10" y="36" width="380" height="254">
<mx:columns>
<mx:DataGridColumn headerText="Nome" dataField="nome"/>
<mx:DataGridColumn headerText="E-mail" dataField="email"/>
<mx:DataGridColumn headerText="Data de registro" dataField="dataRegistro"/>
</mx:columns>
</mx:DataGrid>
<mx:Label id="lblStatus"
x="10" y="306" />
<mx:Button id="btnCarregar"
label="Carregar dados"
click="{Rx.models.index(Participante, onSuccessResultHandler, onFailureResultHandler)}"
right="10" bottom="10"/>
</mx:Canvas>
The focus here is the RestfulX, so I’ll assume you understand all about interface, functions, etc in the above example. Lets talk about how to populate the DataGrid with id dgParticipantes.
Look at the code executed by btnCarregar (line 41): Rx.models.index(Participante, onSuccessResultHandler, onFailureResultHandler). This function is responsible for the Retrieve operation on the database. It sends a GET to the server and converts the XML returned by the server into instances of the appropriate class (Participante, in our example). From this moment on all the loaded data is accessible through the RestfulX cache.
Once the data is loaded into cache, we shall use the Rx.models.cached(Participante) (line 26) function to set the DataGrid’s dataProvider. This function will take all the cached instances and show them on the DataGrid without trying to hit the server. This function returns a ModelsCollection instance, that extends an ArrayCollection.
Each row present into the participantes table will be shown by the DataGrid, and we only need to give to the dataField property of each column the corresponding field name.
The Rx.models.index function asks for only one mandatory parameter, the model that must be loaded into the cache (Participante, in our exemple). The second parameter can be a function called when the models get loaded or an array with other parameters we can use into this function. The third parameter is the function that should be called if RestfulX cannot load the requested data.
The array given by the second parameter in the index function may confuse us when we begin using RestfulX, but the benefit of this array is visible: if you want to use, say, the last parameter (append), you doesn’t need to inform the value “null” for all the precedent parameters.
So to use this array in our exemple, we could write this function this way:
Rx.models.index( Participante, { onSuccess: onSuccessResultHandler, onFailure: onFailureResultHandler } )
If you only need to load the data into the cache without verify the success or the failure of the operation, you can omit these two parameters. But these callback functions are useful to show a feedback to the user about what is happening into the system.
Soon I’ll post other articles about the other basic database operations with RestfulX, then I’ll talk a little more about the other parameters I told you here.
Poderia avaliar este artigo, por favor? |

Pingback: CRUD com o RestfulX: Parte 2/2 – Create, Update e Delete | Elvis Fernandes
Pingback: CRUD com o RestfulX – aplicação funcionando | Elvis Fernandes
Pingback: CRUD com o RestfulX – aplicação funcionando - redeRIA | Agregador de noticias, artigos, tutoriais Flex, Flash, JavaFX, AJAX e Rich internet applications em geral!