Comunidad de diseño web y desarrollo en internet online

No logro conectar combobox con BD en Appserv

Citar            
MensajeEscrito el 28 Nov 2011 03:32 am
Hola, estoy tratando de reutilizar los codigos que han aportado muchos aca para poder conectar o rescatar datos desde mysql en mi proyecto flex pero me dan problemas todos y los otros no logro como hacerlo ya que no entiendo muy bien.

Les dejo mi codigo de los archivos .mxml, script.as, config.as y php.
Me serviria de mucha ayuda porque es para mi examen.

El codigo no lo entiendo del todo, no se programar muy bien en flex, he estado aprendiendo de apoco con su help content y lo unico que he podido usar por mi cuenta son las validaciones y los scripts. Pero el archivo.as y todos los demas los genero flex 3 automaticamente cuando hice la coneccion en el menu DATA --> create aplication from data base.

Necesito tu ayuda no se como poder crear el combobox o que rescate los resultados desde la base de datos.

Dejo aqui mi codificacion que me ha costado un monton hubicar bien en esto del flex 3:

<b>pacientes.xml</b>

<?xml version="1.0" encoding="utf-8"?>
<!--
Main application MXML file.
MXML defines the UI layout of your application as well as the connection of UI components
to your data source (via data binding) and the ActionScript event handlers that
implement your application's UI logic.
The MXML file that starts with an <mx:Application> tag is the main source code file
for your Flex application.
-->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" pageTitle="pacientes"
creationComplete="initApp()" backgroundGradientColors="[#ffffff, #ffffff]">

<mx:Script source="pacientesScript.as" />

<mx:Script>
<![CDATA[

private function limpiar():void
{
Pac_RutCol.text="";
Pac_NombreCol.text="";
Pac_ApellidoCol.text="";
Pac_DirecciónCol.text="";
Pac_CelularCol.text="";
Pac_CorreoCol.text="";
Pac_ObservaciónCol.text="";


}

private function validarRutBuscar():void
{
// Definicion de Variables Utilizadas
var suma2:int=0;
var rut2:String=filterTxt.text;
var ultimoN2:String=filterTxt.text;
var numMag2:int=2;
var resto2:int=0;
var i2:int;


//Aqui vemos cuantos digitos tiene el rut

if(rut2.length == 9) {

rut2 = rut2.substring(0,8);
filterTxt.text=rut2;
ultimoN2 = ultimoN2.substring(8,9);
txiRut2.text=ultimoN2;

}
else if(rut2.length == 8)
{
rut2 = rut2.substring(0,7);
filterTxt.text=rut2;
ultimoN2 = ultimoN2.substring(7,8);
txiRut2.text=ultimoN2;

}


// Defino el arreglo con los posibles digitos verificadores
var digVer2:Array = new Array("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "K", "0");
var parteNumerica2:Array = new Array();

for(i2=0;i2<rut2.length;i2++)
{
parteNumerica2[i2]=rut2.charAt(i2);
}

// Calcula el digito verificador del rut
for (i2=parteNumerica2.length-1; i2>=0; i2--, numMag2++)
{
suma2 += parteNumerica2[i2]*numMag2;
if (numMag2>6)
{
numMag2 = 1;
}
}
// Esto arroja el valor que debe tener el digito verificador
resto2 = 11-(suma2%11);
//Alert.show("resto-->"+resto+" || digVer[resto]-->"+digVer[resto]);

if(digVer2[resto2] == txiRut2.text.toUpperCase())
{
Alert.show("Rut Encontrado", "Buscando Rut",
Alert.OK, this,
alertListener, null, Alert.OK);
separaRutBuscar();
juntarTodo2.text= rut2 + ultimoN2;
separaRutBuscar();

}
else
{
Alert.show("Rut no encontrado, vuelva a digitar. Ejemplo:", "Buscando Rut");
filterTxt.text="";
txiRut2.text="";
juntarTodo2.text="";

}
}


public function separaRutBuscar():void
{
if(juntarTodo2.text !="")
{
var rut2:String = juntarTodo2.text;


trace (rut2);
if(rut2.length == 9)
{
var valor1:String = rut2.substring(0,2);
valor1 = valor1 + ".";
var valor2:String = rut2.substring(2,rut2.length-4);
valor2 = valor2 + ".";
var valor3:String = rut2.substring(5,rut2.length-1);
valor3 = valor3 + "-";
var valor4:String = rut2.substring(8);
valor4 = valor4;
filterTxt.text = valor1 + valor2 + valor3 + valor4;

trace(filterTxt.text);


}
else if(rut2.length == 8)
{
var valor5:String = rut2.substring(0,1);
valor5 = valor5 + ".";
var valor6:String = rut2.substring(1,rut2.length-4);
valor6 = valor6 + ".";
var valor7:String = rut2.substring(4,rut2.length-1);
valor7 = valor7 + "-";
var valor8:String = rut2.substring(7);
valor8 = valor8;
filterTxt.text = valor5 + valor6 + valor7 + valor8;

trace(filterTxt.text);

}
}

}


// Import necessary classes.
import mx.controls.Alert;
import mx.events.ValidationResultEvent;

// Event listener for the valid and invalid events.
private function handleValid(eventObj:ValidationResultEvent):void {
if(eventObj.type==ValidationResultEvent.VALID)
// Enable Submit button.
submitButton.enabled = true;
else
submitButton.enabled = false;
}

// Submit form is everything is valid.
private function submitForm():void {
Alert.show("Registro Validado y Guardado Correctamente!");
}

]]>
</mx:Script>

<mx:Validator id="reqValidrut" required="true"
source="{Pac_RutCol}" property="text"
valid="handleValid(event)" invalid="handleValid(event)" requiredFieldError="Introducir sin guión ni puntos"/>
<mx:Validator id="reqValidnombre" required="true"
source="{Pac_NombreCol}" property="text" requiredFieldError="Introduzca Nombre"
valid="handleValid(event)" invalid="handleValid(event)"/>
<mx:Validator id="reqValidapellido" required="true" requiredFieldError="Introduzca Apellido"
source="{Pac_ApellidoCol}" property="text"
valid="handleValid(event)" invalid="handleValid(event)"/>
<mx:Validator id="reqValiddireccion" required="true" requiredFieldError="Introduzca Dirección"
source="{Pac_DirecciónCol}" property="text"
valid="handleValid(event)" invalid="handleValid(event)"/>
<mx:Validator id="reqValidcelular" required="true" requiredFieldError="Introduzca Celular"
source="{Pac_CelularCol}" property="text"
valid="handleValid(event)" invalid="handleValid(event)"/>
<mx:EmailValidator id="reqValidcorreo" required="true" requiredFieldError="Introduzca correo. Ejemplo: [email protected]"
source="{Pac_CorreoCol}" property="text"
missingUsernameError="Requiere nombre de correo. Ejemplo: [email protected]"
invalidCharError="No puede contener caracteres invalidos como (!#$%/¨*[]{})"
missingAtSignError="Requiere el caracter '@' despues de nombre. Ejemplo: [email protected]"
missingPeriodInDomainError="Correo sin nombre de servidor o dominio. Ejemplo: [email protected]"
invalidDomainError="Requiere nombre de dominio. Ejemplo: [email protected]"
tooManyAtSignsError="Correo contiene muchos caracteres @"/>


<!--
Externalized script "include" tag.
This file contains the UI logic for the CRUD application. All application logic
in Flex is written in ActionScript, the same language used by Flash.
Although all of this code could have been included directly in the mx:Script tag
within this file, we recommend externalizing it for clarity.
-->


<!--
The tags below define the application's UI components and their initial properties.
Every tag can be accessed in ActionScript via its "id" property, similar to HTML tags
accessed via JavaScript.
Note that unlike HTML, Flex does not use a flow-based model. With the exception of
some containers, Flex controls are positioned on the page using their width and height
properties, so the order of the tags in the file does not affect the layout.
-->
<mx:ViewStack id="applicationScreens" width="100%" height="100%">
<mx:Canvas id="view" width="100%" height="100%">

<!--
This DataGrid is bound to a data provider, the object "dataArr" which is
instantiated in the included script file. In general, data providers are collections
such as Array, ArrayCollection, XMLObject, etc. that are declared with the [Bindable]
tag and set as the "dataProvider" property of a UI component. When the data in
a data provider changes, Flex will automatically update any bound UI components
with the new data.
-->
<mx:DataGrid id="dataGrid"
dataProvider="{dataArr}"
rowCount="8"
editable="true"
resizableColumns="true"
headerRelease="setOrder(event);"
right="10" left="10" top="10" bottom="71">
<mx:columns>
<mx:DataGridColumn headerText="Rut" dataField="Pac_RutCol" />
<mx:DataGridColumn headerText="Nombre" dataField="Pac_NombreCol" />
<mx:DataGridColumn headerText="Apellido" dataField="Pac_ApellidoCol" />
<mx:DataGridColumn headerText="Dirección" dataField="Pac_DirecciónCol" />
<mx:DataGridColumn headerText="Celular" dataField="Pac_CelularCol" />
<mx:DataGridColumn headerText="Correo" dataField="Pac_CorreoCol" />
<mx:DataGridColumn headerText="Observación" dataField="Pac_ObservaciónCol" />
<mx:DataGridColumn headerText="Pac_Tip_Men_Num" dataField="Pac_Tip_Men_NumCol" />
</mx:columns>
</mx:DataGrid>

<!--
These Buttons call ActionScript functions defined in
employeesScript.as when they are clicked (as defined by the "click"
event on the tag). In general, UI event handling in Flex is done by assigning
handler functions to the events on the UI component.
-->
<mx:Button id="btnAddNew" click="goToUpdate(), limpiar() " icon="@Embed('icons/AddRecord.png')" toolTip="Agregar Paciente" x="10" bottom="10"/>
<mx:Button id="btnDelete" click="deleteItem() " icon="@Embed('icons/DeleteRecord.png')" toolTip="Borrar Paciente" x="58" bottom="10"/>
<mx:Label text="Buscar paciente por Rut" right="300" bottom="11"/>
<mx:TextInput id="filterTxt" width="238" toolTip="Escriba sin puntos ni lineas" enter="validarRutBuscar(), filterResults()" right="58" bottom="10" maxChars="9"/>
<mx:Button click="validarRutBuscar(), filterResults()" id="filterButton" icon="@Embed('icons/SearchRecord.png')" toolTip="Buscar por Rut" right="10" bottom="10"/>
<mx:TextInput id="juntarTodo2" width="18" backgroundColor="#B7BABC" alpha="0.0" color="#B7BABC" backgroundAlpha="0.0" fontSize="6" editable="false" enabled="false" x="10" y="302"/>
<mx:TextInput id="txiRut2" width="14" backgroundAlpha="0.0" borderColor="#B7BABC" themeColor="#B7BABC" color="#B7BABC" alpha="0.0" x="36" y="302"/>

</mx:Canvas>
<mx:Script>

<![CDATA[
import mx.collections.ArrayCollection;
import mx.controls.dataGridClasses.DataGridColumn;
import mx.rpc.remoting.*;
import mx.controls.*;
import mx.rpc.events.*
import flash.events.Event;
import mx.managers.FocusManager;
import mx.events.ValidationResultEvent;




private function alertListener(eventObj:CloseEvent):void {
// Check to see if the OK button was pressed.
if (eventObj.detail==Alert.OK) {
stage.focus = Pac_NombreCol;
Pac_NombreCol.setSelection(Pac_NombreCol.text.length,Pac_NombreCol.text.length);
}
}


public function separaRut():void
{
if(juntarTodo.text !="")
{
var rut:String = juntarTodo.text;


trace (rut);
if(rut.length == 9)
{
var valor1:String = rut.substring(0,2);
valor1 = valor1 + ".";
var valor2:String = rut.substring(2,rut.length-4);
valor2 = valor2 + ".";
var valor3:String = rut.substring(5,rut.length-1);
valor3 = valor3 + "-";
var valor4:String = rut.substring(8);
valor4 = valor4;
Pac_RutCol.text = valor1 + valor2 + valor3 + valor4;

trace(Pac_RutCol.text);


}
else if(rut.length == 8)
{
var valor5:String = rut.substring(0,1);
valor5 = valor5 + ".";
var valor6:String = rut.substring(1,rut.length-4);
valor6 = valor6 + ".";
var valor7:String = rut.substring(4,rut.length-1);
valor7 = valor7 + "-";
var valor8:String = rut.substring(7);
valor8 = valor8;
Pac_RutCol.text = valor5 + valor6 + valor7 + valor8;

trace(Pac_RutCol.text);

}
}

}


private function validarRut():void
{
// Definicion de Variables Utilizadas
var suma:int=0;
var rut:String=Pac_RutCol.text;
var ultimoN:String=Pac_RutCol.text;
var numMag:int=2;
var resto:int=0;
var i:int;


//Aqui vemos cuantos digitos tiene el rut

if(rut.length == 9) {

rut = rut.substring(0,8);
Pac_RutCol.text=rut;
ultimoN = ultimoN.substring(8,9);
txiRut.text=ultimoN;

}
else if(rut.length == 8)
{
rut = rut.substring(0,7);
Pac_RutCol.text=rut;
ultimoN = ultimoN.substring(7,8);
txiRut.text=ultimoN;

}


// Defino el arreglo con los posibles digitos verificadores
var digVer:Array = new Array("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "K", "0");
var parteNumerica:Array = new Array();

for(i=0;i<rut.length;i++)
{
parteNumerica[i]=rut.charAt(i);
}

// Calcula el digito verificador del rut
for (i=parteNumerica.length-1; i>=0; i--, numMag++)
{
suma += parteNumerica[i]*numMag;
if (numMag>6)
{
numMag = 1;
}
}
// Esto arroja el valor que debe tener el digito verificador
resto = 11-(suma%11);
//Alert.show("resto-->"+resto+" || digVer[resto]-->"+digVer[resto]);

if(digVer[resto] == txiRut.text.toUpperCase())
{
Alert.show("Rut Valido", "Validación...",
Alert.OK, this,
alertListener, null, Alert.OK);
separaRut();
juntarTodo.text= rut + ultimoN;
separaRut();

}
else
{
Alert.show("El Rut no es valido");
Pac_RutCol.text="";
txiRut.text="";
juntarTodo.text="";

}
}







]]>
</mx:Script>

<mx:Canvas id="update" width="100%" height="100%">
<mx:Form width="100%" height="291" id="pacientesForm">
<mx:FormItem label="Rut:" id="Pac_Rut_form" required="true">
<mx:TextInput id="Pac_RutCol" restrict="0123456789k" maxChars="9" toolTip="Ingrese rut sin puntos ni lineas" width="90" mouseFocusChange="validarRut()"/>
</mx:FormItem>
<mx:FormItem label="Nombre:" id="Pac_Nombre_form" required="true">
<mx:TextInput id="Pac_NombreCol" text="" maxChars="15" toolTip="Escriba el nombre" restrict="a-z ñ A-Z Ñ" width="120" focusEnabled="true"/>
</mx:FormItem>
<mx:FormItem label="Apellido:" id="Pac_Apellido_form" required="true">
<mx:TextInput id="Pac_ApellidoCol" text="" maxChars="15" restrict="a-z ñ A-Z Ñ" width="120" toolTip="Escriba el apellido"/>
</mx:FormItem>
<mx:FormItem label="Dirección:" id="Pac_Dirección_form" required="true">
<mx:TextInput id="Pac_DirecciónCol" text="" maxChars="25" width="190" toolTip="Escriba la dirección"/>
</mx:FormItem>
<mx:FormItem label="Celular:" id="Pac_Celular_form" required="true">
<mx:TextInput id="Pac_CelularCol" text="" restrict="0123456789" width="70" toolTip="Escriba el celular"/>
</mx:FormItem>
<mx:FormItem label="Correo:" id="Pac_Correo_form" required="true">
<mx:TextInput id="Pac_CorreoCol" text="" maxChars="25" width="190" toolTip="Escriba el correo. Ejemplo: [email protected]"/>
</mx:FormItem>
<mx:FormItem label="Observación:" id="Pac_Observación_form">
<mx:TextInput id="Pac_ObservaciónCol"/>
</mx:FormItem>
<mx:FormItem label="Pac_Tip_Men_Num:" id="Pac_Tip_Men_Num_form">
<mx:ComboBox id="Tip_Men_NombreCmb" />
</mx:FormItem>
<mx:TextInput id="juntarTodo" width="0" backgroundColor="#B7BABC" alpha="0.0" color="#B7BABC" backgroundAlpha="0.0" fontSize="6" editable="false" enabled="false"/>
<mx:TextInput id="txiRut" width="0" backgroundAlpha="0.0" borderColor="#B7BABC" themeColor="#B7BABC" color="#B7BABC" alpha="0.0"/>
</mx:Form>
<mx:Button label="Guardar" id="submitButton" enabled="false" click="insertItem(), limpiar()" right="648" bottom="43"/>
<mx:Button label="Volver" id="btnCancel" click="goToView()" right="577" bottom="43"/>
</mx:Canvas>

</mx:ViewStack>
</mx:Application>






<b>pacienteScript.as</b>





/**
* ActionScript source file that defines the UI logic and some of the data access code.
* This file is linked into the main application MXML file using the mx:Script tag.
* Most of the functions in this file are called by event handlers defined in
* the MXML.
*/
import mx.collections.ArrayCollection;
import mx.controls.Alert;
import mx.controls.dataGridClasses.DataGridColumn;
import mx.controls.dataGridClasses.DataGridItemRenderer;
import mx.events.CloseEvent;
import mx.events.DataGridEvent;
import mx.rpc.events.ResultEvent;
import mx.managers.CursorManager;
import mx.utils.ObjectUtil;

import mx.rpc.http.HTTPService;
import mx.rpc.events.FaultEvent;
import mx.rpc.AsyncToken;

//include the constant definition of the server endpoint URL
include "pacientesconfig.as";

/**
* gateway : this is the communication layer with the server side php code
*/
private var gateway:HTTPService = new HTTPService();

/**
* the array collection holds the rows that we use in the grid
*/
[Bindable]
public var dataArr:ArrayCollection = new ArrayCollection();

/**
* column that we order by. This is updated each time the users clicks on the
* grid column header.
* see headerRelease="setOrder(event);" in the DataGrid instantiation in the
* mxml file
*/
private var orderColumn:Number;


/**
* the list of fields in the database table
* needed to parse the response into hashes
*/
private var fields:Object = { 'Pac_Rut':String, 'Pac_Nombre':String, 'Pac_Apellido':String, 'Pac_Dirección':String, 'Pac_Celular':Number, 'Pac_Correo':String, 'Pac_Observación':String, 'Pac_Tip_Men_Num':Number};

/**
* Executes when the mxml is completed loaded. Initialize the Rest Gateway.
*/
private function initApp():void
{

/**
* initialize the gateway
* - this will take care off server communication and simple xml protocol.
*/
gateway.url = ENDPOINT_URL;
gateway.method = "POST";
gateway.useProxy = false;
gateway.resultFormat = "e4x";

/**
* set the event handler which prevents editing of the primary key
*/
dataGrid.addEventListener(DataGridEvent.ITEM_EDIT_BEGINNING, editCellHandler);

/**
* set the event handler which triggers the update actions - everytime an
* edit operation is finished
*/
dataGrid.addEventListener(DataGridEvent.ITEM_EDIT_END, editCellEnd);

gateway.addEventListener(ResultEvent.RESULT, resultHandler);
gateway.addEventListener(FaultEvent.FAULT, faultHandler);

fill();
}

/**
* Disallow editing of the primary key column.
* @param e DataGridEvent contains details about the row and column of the grid
* where the user clicked
*/
private function editCellHandler(e:DataGridEvent):void
{
/**
* if the user clicked on the primary key column, stop editing
*/
if(e.dataField == "Pac_RutCol")
{
e.preventDefault();
return;
}
}

/**
* Click handler for "Filter" button.
* When setting another filter, refresh the collection, and load the new data
*/
private function filterResults():void
{
fill();
}

/**
* Event handler triggered when the user finishes editing an entry
* triggers an "update" server command
*/
private function editCellEnd(e:DataGridEvent):void
{
var dsRowIndex:int = e.rowIndex;
var dsFieldName:String = e.dataField;
var dsColumnIndex:Number = e.columnIndex;

var vo:* = dataArr[dsRowIndex];

var col:DataGridColumn = dataGrid.columns[dsColumnIndex];
var newvalue:String = dataGrid.itemEditorInstance[col.editorDataField];

trace("a:" + dsRowIndex + ", " + dsFieldName + ", " + dsColumnIndex);

var parameters:* =
{
"Pac_Rut": vo.Pac_RutCol, "Pac_Nombre": vo.Pac_NombreCol, "Pac_Apellido": vo.Pac_ApellidoCol, "Pac_Dirección": vo.Pac_DirecciónCol, "Pac_Celular": vo.Pac_CelularCol, "Pac_Correo": vo.Pac_CorreoCol, "Pac_Observación": vo.Pac_ObservaciónCol, "Pac_Tip_Men_Num": vo.Pac_Tip_Men_NumCol }

parameters[dsFieldName.substr(0,dsFieldName.length-3)] = newvalue;

/**
* execute the server "update" command
*/
doRequest("Update", parameters, saveItemHandler);

}

/**
* result handler for the "update" server command.
* Just alert the error, or do nothing if it's ok - the data has already
* been updated in the grid
*/
private function saveItemHandler(e:Object):void
{
if (e.isError)
{
Alert.show("Error: " + e.data.error);
}
else
{
}
}

/**
* dragHeader handler for the datagrid. This handler is executed when the user
* clicks on a header column in the datagrid
* updates the global orderColumn variable, refreshes the TableCollection
* @param event DataGridEvent details about the column
*/
private function setOrder(event:DataGridEvent):void
{
orderColumn = event.columnIndex;
var col:DataGridColumn = dataGrid.columns[orderColumn];
col.sortDescending = !col.sortDescending;

event.preventDefault();
fill();
}

/**
* Click handler for the "Save" button in the "Add" state
* collects the information in the form and adds a new object to the collection
*/
private function insertItem():void {
var parameters:* =
{
"method": "Insert", "Pac_Rut": Pac_RutCol.text, "Pac_Nombre": Pac_NombreCol.text, "Pac_Apellido": Pac_ApellidoCol.text, "Pac_Dirección": Pac_DirecciónCol.text, "Pac_Celular": Pac_CelularCol.text, "Pac_Correo": Pac_CorreoCol.text, "Pac_Observación": Pac_ObservaciónCol.text, "Pac_Tip_Men_Num": Tip_Men_NombreCmb.text };

/**
* execute the server "insert" command
*/
doRequest("Insert", parameters, insertItemHandler);
}

/**
* Result handler for the insert call.
* Alert the error if it exists
* if the call went through ok, return to the list, and refresh the data
*/
private function insertItemHandler(e:Object):void
{
if (e.isError)
{
Alert.show("Error: " + e.data.error);
}
else
{
goToView();
fill();
}
}

/**
* general utility function for refreshing the data
* gets the filtering and ordering, then dispatches a new server call
*
*/
private function fill():void
{
/**
* find the order parameters
*/
var desc:Boolean = false;
var orderField:String = '';

if(!isNaN(orderColumn))
{
var col:DataGridColumn = dataGrid.columns[orderColumn];
desc = col.sortDescending;
//remove the 'Col' particle
orderField = col.dataField.substr(0,col.dataField.length-3);
}

dataGrid.enabled = false;
CursorManager.setBusyCursor();

var parameters:* =
{
"orderField": orderField,
"orderDirection": (desc) ? "DESC" : "ASC",
"filter": filterTxt.text
}
/**
* execute the server "select" command
*/
doRequest("FindAll", parameters, fillHandler);
}

/**
* result handler for the fill call.
* if it is an error, show it to the user, else refill the arraycollection with the new data
*
*/
private function fillHandler(e:Object):void
{
if (e.isError)
{
Alert.show("Error: " + e.data.error);
}
else
{
dataArr.removeAll();
for each(var row:XML in e.data.row)
{
var temp:* = {};
for (var key:String in fields)
{
temp[key + 'Col'] = row[key];
}

dataArr.addItem(temp);
}

CursorManager.removeBusyCursor();
dataGrid.enabled = true;
}
}

/**
* Click handler for the "delete" button in the list
* confirms the action and launches the deleteClickHandler function
*/
private function deleteItem():void {

if (dataGrid.selectedItem)
{
Alert.show("Seguro de borrar el paciente seleccionado?",
"Confirmando Borrar", 3, this, deleteClickHandler);
}

}

/**
* Event handler function for the Confirm dialog raises when the
* Delete button is pressed.
* If the pressed button was Yes, then the product is deleted.
* @param object event
* @return nothing
*/
private function deleteClickHandler(event:CloseEvent):void
{
if (event.detail == Alert.YES)
{
var vo:* = dataGrid.selectedItem;

var parameters:* =
{
"Pac_Rut": vo.Pac_RutCol
}

/**
* execute the server "delete" command
*/
doRequest("Delete", parameters, deleteHandler);

setTimeout( function():void
{
dataGrid.destroyItemEditor();
},
1);
}
}

public function deleteHandler(e:*):void
{
if (e.isError)
{
Alert.show("Error: " + e.data.error);
}
else
{
var Pac_Rut:Number = parseInt(e.data.toString(), 10);
for (var index:Number = 0; index < dataArr.length; index++)
{
if (dataArr[index].Pac_RutCol == Pac_Rut)
{
dataArr.removeItemAt(index);
break;
}
}
}
}

/**
* deserializes the xml response
* handles error cases
*
* @param e ResultEvent the server response and details about the connection
*/
public function deserialize(obj:*, e:*):*
{
var toret:Object = {};

toret.originalEvent = e;

if (obj.data.elements("error").length() > 0)
{
toret.isError = true;
toret.data = obj.data;
}
else
{
toret.isError = false;
toret.metadata = obj.metadata;
toret.data = obj.data;
}

return toret;
}

/**
* result handler for the gateway
* deserializes the result, and then calls the REAL event handler
* (set when making a request in the doRequest function)
*
* @param e ResultEvent the server response and details about the connection
*/
public function resultHandler(e:ResultEvent):void
{
var topass:* = deserialize(e.result, e);
e.token.handler.call(null, topass);
}

/**
* fault handler for this connection
*
* @param e FaultEvent the error object
*/
public function faultHandler(e:FaultEvent):void
{
var errorMessage:String = "Connection error: " + e.fault.faultString;
if (e.fault.faultDetail)
{
errorMessage += "\n\nAdditional detail: " + e.fault.faultDetail;
}
Alert.show(errorMessage);
}

/**
* makes a request to the server using the gateway instance
*
* @param method_name String the method name used in the server dispathcer
* @param parameters Object name value pairs for sending in post
* @param callback Function function to be called when the call completes
*/
public function doRequest(method_name:String, parameters:Object, callback:Function):void
{
// add the method to the parameters list
parameters['method'] = method_name;

gateway.request = parameters;

var call:AsyncToken = gateway.send();
call.request_params = gateway.request;

call.handler = callback;
}


/**
* Click handler when the user click the "Create" button
* Load the "Update" canvas.
*/
public function goToUpdate():void
{
applicationScreens.selectedChild = update;
}

/**
* Load the "View" canvas.
*/
public function goToView():void
{
applicationScreens.selectedChild = view;
}






<b>pacientesconfig.as<b/>





/**
* change this to point to your poll.php on the web server
*/
//public const ENDPOINT_URL:String = "http://localhost:8080//AVISAMED/pacientesRest";
public const ENDPOINT_URL:String = "Pacientes.php";





<b>Pacientes.php</b>





<?php
require_once(dirname(__FILE__) . "/AVISAMEDconn.php");
require_once(dirname(__FILE__) . "/functions.inc.php");
require_once(dirname(__FILE__) . "/XmlSerializer.class.php");
/**
* This is the main PHP file that process the HTTP parameters,
* performs the basic db operations (FIND, INSERT, UPDATE, DELETE)
* and then serialize the response in an XML format.
*
* XmlSerializer uses a PEAR xml parser to generate an xml response.
* this takes a php array and generates an xml according to the following rules:
* - the root tag name is called "response"
* - if the current value is a hash, generate a tagname with the key value, recurse inside
* - if the current value is an array, generated tags with the default value "row"
* for example, we have the following array:
*
* $arr = array(
* "data" => array(
* array("id_pol" => 1, "name_pol" => "name 1"),
* array("id_pol" => 2, "name_pol" => "name 2")
* ),
* "metadata" => array(
* "pageNum" => 1,
* "totalRows" => 345
* )
*
* )
*
* we will get an xml of the following form
*
* <?xml version="1.0" encoding="ISO-8859-1"?>
* <response>
* <data>
* <row>
* <id_pol>1</id_pol>
* <name_pol>name 1</name_pol>
* </row>
* <row>
* <id_pol>2</id_pol>
* <name_pol>name 2</name_pol>
* </row>
* </data>
* <metadata>
* <totalRows>345</totalRows>
* <pageNum>1</pageNum>
* </metadata>
* </response>
*
* Please notice that the generated server side code does not have any
* specific authentication mechanism in place.
*/



/**
* The filter field. This is the only field that we will do filtering after.
*/
$filter_field = "Pac_Rut";

/**
* we need to escape the value, so we need to know what it is
* possible values: text, long, int, double, date, defined
*/
$filter_type = "text";

/**
* constructs and executes a sql select query against the selected database
* can take the following parameters:
* $_REQUEST["orderField"] - the field by which we do the ordering. MUST appear inside $fields.
* $_REQUEST["orderValue"] - ASC or DESC. If neither, the default value is ASC
* $_REQUEST["filter"] - the filter value
* $_REQUEST["pageNum"] - the page index
* $_REQUEST["pageSize"] - the page size (number of rows to return)
* if neither pageNum and pageSize appear, we do a full select, no limit
* returns : an array of the form
* array (
* data => array(
* array('field1' => "value1", "field2" => "value2")
* ...
* ),
* metadata => array(
* "pageNum" => page_index,
* "totalRows" => number_of_rows
* )
* )
*/
function findAll() {
global $conn, $filter_field, $filter_type;

/**
* the list of fields in the table. We need this to check that the sent value for the ordering is indeed correct.
*/
$fields = array('Pac_Rut','Pac_Nombre','Pac_Apellido','Pac_Dirección','Pac_Celular','Pac_Correo','Pac_Observación','Pac_Tip_Men_Num');

$where = "";
if (@$_REQUEST['filter'] != "") {
$where = "WHERE " . $filter_field . " LIKE " . GetSQLValueStringForSelect(@$_REQUEST["filter"], $filter_type);
}

$order = "";
if (@$_REQUEST["orderField"] != "" && in_array(@$_REQUEST["orderField"], $fields)) {
$order = "ORDER BY " . @$_REQUEST["orderField"] . " " . (in_array(@$_REQUEST["orderDirection"], array("ASC", "DESC")) ? @$_REQUEST["orderDirection"] : "ASC");
}

//calculate the number of rows in this table
$rscount = mysql_query("SELECT count(*) AS cnt FROM `pacientes` $where");
$row_rscount = mysql_fetch_assoc($rscount);
$totalrows = (int) $row_rscount["cnt"];

//get the page number, and the page size
$pageNum = (int)@$_REQUEST["pageNum"];
$pageSize = (int)@$_REQUEST["pageSize"];

//calculate the start row for the limit clause
$start = $pageNum * $pageSize;

//construct the query, using the where and order condition
$query_recordset = "SELECT Pac_Rut,Pac_Nombre,Pac_Apellido,Pac_Dirección,Pac_Celular,Pac_Correo,Pac_Observación,Pac_Tip_Men_Num FROM `pacientes` $where $order";

//if we use pagination, add the limit clause
if ($pageNum >= 0 && $pageSize > 0) {
$query_recordset = sprintf("%s LIMIT %d, %d", $query_recordset, $start, $pageSize);
}

$recordset = mysql_query($query_recordset, $conn);

//if we have rows in the table, loop through them and fill the array
$toret = array();
while ($row_recordset = mysql_fetch_assoc($recordset)) {
array_push($toret, $row_recordset);
}

//create the standard response structure
$toret = array(
"data" => $toret,
"metadata" => array (
"totalRows" => $totalrows,
"pageNum" => $pageNum
)
);

return $toret;
}

/**
* constructs and executes a sql count query against the selected database
* can take the following parameters:
* $_REQUEST["filter"] - the filter value
* returns : an array of the form
* array (
* data => number_of_rows,
* metadata => array()
* )
*/
function rowCount() {
global $conn, $filter_field, $filter_type;

$where = "";
if (@$_REQUEST['filter'] != "") {
$where = "WHERE " . $filter_field . " LIKE " . GetSQLValueStringForSelect(@$_REQUEST["filter"], $filter_type);
}

//calculate the number of rows in this table
$rscount = mysql_query("SELECT count(*) AS cnt FROM `pacientes` $where");
$row_rscount = mysql_fetch_assoc($rscount);
$totalrows = (int) $row_rscount["cnt"];

//create the standard response structure
$toret = array(
"data" => $totalrows,
"metadata" => array()
);

return $toret;
}

/**
* constructs and executes a sql insert query against the selected database
* can take the following parameters:
* $_REQUEST["field_name"] - the list of fields which appear here will be used as values for insert.
* If a field does not appear, null will be used.
* returns : an array of the form
* array (
* data => array(
* "primary key" => primary_key_value,
* "field1" => "value1"
* ...
* ),
* metadata => array()
* )
*/
function insert() {
global $conn;

//build and execute the insert query
$query_insert = sprintf("INSERT INTO `pacientes` (Pac_Rut,Pac_Nombre,Pac_Apellido,Pac_Dirección,Pac_Celular,Pac_Correo,Pac_Observación,Pac_Tip_Men_Num) VALUES (%s,%s,%s,%s,%s,%s,%s,%s)" , GetSQLValueString($_REQUEST["Pac_Rut"], "text"), #
GetSQLValueString($_REQUEST["Pac_Nombre"], "text"), #
GetSQLValueString($_REQUEST["Pac_Apellido"], "text"), #
GetSQLValueString($_REQUEST["Pac_Dirección"], "text"), #
GetSQLValueString($_REQUEST["Pac_Celular"], "int"), #
GetSQLValueString($_REQUEST["Pac_Correo"], "text"), #
GetSQLValueString($_REQUEST["Pac_Observación"], "text"), #
GetSQLValueString($_REQUEST["Pac_Tip_Men_Num"], "int")#
);
$ok = mysql_query($query_insert);

if ($ok) {
// return the new entry, using the insert id
$toret = array(
"data" => array(
array(
"Pac_Rut" => $_REQUEST["Pac_Rut"],
"Pac_Nombre" => $_REQUEST["Pac_Nombre"], #
"Pac_Apellido" => $_REQUEST["Pac_Apellido"], #
"Pac_Dirección" => $_REQUEST["Pac_Dirección"], #
"Pac_Celular" => $_REQUEST["Pac_Celular"], #
"Pac_Correo" => $_REQUEST["Pac_Correo"], #
"Pac_Observación" => $_REQUEST["Pac_Observación"], #
"Pac_Tip_Men_Num" => $_REQUEST["Pac_Tip_Men_Num"]#
)
),
"metadata" => array()
);
} else {
// we had an error, return it
$toret = array(
"data" => array("error" => mysql_error()),
"metadata" => array()
);
}
return $toret;
}







/**
* constructs and executes a sql update query against the selected database
* can take the following parameters:
* $_REQUEST[primary_key] - thethe value of the primary key
* $_REQUEST[field_name] - the list of fields which appear here will be used as values for update.
* If a field does not appear, null will be used.
* returns : an array of the form
* array (
* data => array(
* "primary key" => primary_key_value,
* "field1" => "value1"
* ...
* ),
* metadata => array()
* )
*/
function update() {
global $conn;

// check to see if the record actually exists in the database
$query_recordset = sprintf("SELECT * FROM `pacientes` WHERE Pac_Rut = %s",
GetSQLValueString($_REQUEST["Pac_Rut"], "text")
);
$recordset = mysql_query($query_recordset, $conn);
$num_rows = mysql_num_rows($recordset);

if ($num_rows > 0) {

// build and execute the update query
$row_recordset = mysql_fetch_assoc($recordset);
$query_update = sprintf("UPDATE `pacientes` SET Pac_Nombre = %s,Pac_Apellido = %s,Pac_Dirección = %s,Pac_Celular = %s,Pac_Correo = %s,Pac_Observación = %s,Pac_Tip_Men_Num = %s WHERE Pac_Rut = %s",
GetSQLValueString($_REQUEST["Pac_Nombre"], "text"),
GetSQLValueString($_REQUEST["Pac_Apellido"], "text"),
GetSQLValueString($_REQUEST["Pac_Dirección"], "text"),
GetSQLValueString($_REQUEST["Pac_Celular"], "int"),
GetSQLValueString($_REQUEST["Pac_Correo"], "text"),
GetSQLValueString($_REQUEST["Pac_Observación"], "text"),
GetSQLValueString($_REQUEST["Pac_Tip_Men_Num"], "int"),
GetSQLValueString($row_recordset["Pac_Rut"], "text")
);
$ok = mysql_query($query_update);
if ($ok) {
// return the updated entry
$toret = array(
"data" => array(
array(
"Pac_Rut" => $row_recordset["Pac_Rut"],
"Pac_Nombre" => $_REQUEST["Pac_Nombre"], #
"Pac_Apellido" => $_REQUEST["Pac_Apellido"], #
"Pac_Dirección" => $_REQUEST["Pac_Dirección"], #
"Pac_Celular" => $_REQUEST["Pac_Celular"], #
"Pac_Correo" => $_REQUEST["Pac_Correo"], #
"Pac_Observación" => $_REQUEST["Pac_Observación"], #
"Pac_Tip_Men_Num" => $_REQUEST["Pac_Tip_Men_Num"]#
)
),
"metadata" => array()
);
} else {
// an update error, return it
$toret = array(
"data" => array("error" => mysql_error()),
"metadata" => array()
);
}
} else {
$toret = array(
"data" => array("error" => "No row found"),
"metadata" => array()
);
}
return $toret;
}

/**
* constructs and executes a sql update query against the selected database
* can take the following parameters:
* $_REQUEST[primary_key] - thethe value of the primary key
* returns : an array of the form
* array (
* data => deleted_row_primary_key_value,
* metadata => array()
* )
*/
function delete() {
global $conn;

// check to see if the record actually exists in the database
$query_recordset = sprintf("SELECT * FROM `pacientes` WHERE Pac_Rut = %s",
GetSQLValueString($_REQUEST["Pac_Rut"], "text")
);
$recordset = mysql_query($query_recordset, $conn);
$num_rows = mysql_num_rows($recordset);

if ($num_rows > 0) {
$row_recordset = mysql_fetch_assoc($recordset);
$query_delete = sprintf("DELETE FROM `pacientes` WHERE Pac_Rut = %s",
GetSQLValueString($row_recordset["Pac_Rut"], "text")
);
$ok = mysql_query($query_delete);
if ($ok) {
// delete went through ok, return OK
$toret = array(
"data" => $row_recordset["Pac_Rut"],
"metadata" => array()
);
} else {
$toret = array(
"data" => array("error" => mysql_error()),
"metadata" => array()
);
}

} else {
// no row found, return an error
$toret = array(
"data" => array("error" => "No row found"),
"metadata" => array()
);
}
return $toret;
}

/**
* we use this as an error response, if we do not receive a correct method
*
*/
$ret = array(
"data" => array("error" => "No operation"),
"metadata" => array()
);

/**
* check for the database connection
*
*
*/
if ($conn === false) {
$ret = array(
"data" => array("error" => "database connection error, please check your settings !"),
"metadata" => array()
);
} else {
mysql_select_db($database_conn, $conn);
/**
* simple dispatcher. The $_REQUEST["method"] parameter selects the operation to execute.
* must be one of the values findAll, insert, update, delete, Count
*/
// execute the necessary function, according to the operation code in the post variables
switch (@$_REQUEST["method"]) {
case "FindAll":
$ret = findAll();
break;
case "Insert":
$ret = insert();
break;
case "Update":
$ret = update();
break;
case "Delete":
$ret = delete();
break;
case "Count":
$ret = rowCount();
break;
}
}


$serializer = new XmlSerializer();
echo $serializer->serialize($ret);
die();
?>

Por carlos.baeza.r

1 de clabLevel



 

firefox
Citar            
MensajeEscrito el 28 Nov 2011 07:35 am
Segui una guia por este link : http://collectioncode.com/flexas/llenar-combobox-en-flex/

Pero tapoco pude dar con nada. Me da los siguientes errores:

Pero como yo ya tengo un archivo llamado pacientesScript.ass lo que hice fue copiar el codigo e editar los campos correscondientes pero no me deja pasar el codigo cuando escribo los datos:

package clases{

me da un error llamado:

1083: Syntax error: package is unexpected.

Lo borro y continua al siguiente error…

public class Combos{

me da un error llamado:

Classes must not be nested.

Despues el error continua en esta linea:

public var obj:Conectar = new Conectar(“amfphp/gateway.php”);//Conectarse a la DB

me da 3 errores llamados:

1046:Type was not found or was not a compile-time constant: Conectar.
1180: Call to a possibly undefined method Conectar.
1180: Call to a possibly undefined method Conectar.

Al borrar la linea me da un error en:

obj.call(“combos.getCombo”, new Responder(exito, error), datos);
}

y pensando en eso ya no se puede continuar.


/**
* ActionScript source file that defines the UI logic and some of the data access code.
* This file is linked into the main application MXML file using the mx:Script tag.
* Most of the functions in this file are called by event handlers defined in
* the MXML.
*/
import mx.collections.ArrayCollection;
import mx.controls.Alert;
import mx.controls.dataGridClasses.DataGridColumn;
import mx.events.CloseEvent;
import mx.events.DataGridEvent;
import mx.managers.CursorManager;
import mx.rpc.AsyncToken;
import mx.rpc.events.FaultEvent;
import mx.rpc.events.ResultEvent;
import mx.rpc.http.HTTPService;

//include the constant definition of the server endpoint URL
include "pacientesconfig.as";

/**
* gateway : this is the communication layer with the server side php code
*/
private var gateway:HTTPService = new HTTPService();

/**
* the array collection holds the rows that we use in the grid
*/
[Bindable]
public var dataArr:ArrayCollection = new ArrayCollection();

/**
* column that we order by. This is updated each time the users clicks on the
* grid column header.
* see headerRelease="setOrder(event);" in the DataGrid instantiation in the
* mxml file
*/
private var orderColumn:Number;


/**
* the list of fields in the database table
* needed to parse the response into hashes
*/
private var fields:Object = { 'Pac_Rut':String, 'Pac_Nombre':String, 'Pac_Apellido':String, 'Pac_Dirección':String, 'Pac_Celular':Number, 'Pac_Correo':String, 'Pac_Observación':String, 'Pac_Tip_Men_Num':Number};

/**
* Executes when the mxml is completed loaded. Initialize the Rest Gateway.
*/
private function initApp():void
{

/**
* initialize the gateway
* - this will take care off server communication and simple xml protocol.
*/
gateway.url = ENDPOINT_URL;
gateway.method = "POST";
gateway.useProxy = false;
gateway.resultFormat = "e4x";

/**
* set the event handler which prevents editing of the primary key
*/
dataGrid.addEventListener(DataGridEvent.ITEM_EDIT_BEGINNING, editCellHandler);

/**
* set the event handler which triggers the update actions - everytime an
* edit operation is finished
*/
dataGrid.addEventListener(DataGridEvent.ITEM_EDIT_END, editCellEnd);

gateway.addEventListener(ResultEvent.RESULT, resultHandler);
gateway.addEventListener(FaultEvent.FAULT, faultHandler);

fill();
}

/**
* Disallow editing of the primary key column.
* @param e DataGridEvent contains details about the row and column of the grid
* where the user clicked
*/
private function editCellHandler(e:DataGridEvent):void
{
/**
* if the user clicked on the primary key column, stop editing
*/
if(e.dataField == "Pac_RutCol")
{
e.preventDefault();
return;
}
}

/**
* Click handler for "Filter" button.
* When setting another filter, refresh the collection, and load the new data
*/
private function filterResults():void
{
fill();
}

/**
* Event handler triggered when the user finishes editing an entry
* triggers an "update" server command
*/
private function editCellEnd(e:DataGridEvent):void
{
var dsRowIndex:int = e.rowIndex;
var dsFieldName:String = e.dataField;
var dsColumnIndex:Number = e.columnIndex;

var vo:* = dataArr[dsRowIndex];

var col:DataGridColumn = dataGrid.columns[dsColumnIndex];
var newvalue:String = dataGrid.itemEditorInstance[col.editorDataField];

trace("a:" + dsRowIndex + ", " + dsFieldName + ", " + dsColumnIndex);

var parameters:* =
{
"Pac_Rut": vo.Pac_RutCol, "Pac_Nombre": vo.Pac_NombreCol, "Pac_Apellido": vo.Pac_ApellidoCol, "Pac_Dirección": vo.Pac_DirecciónCol, "Pac_Celular": vo.Pac_CelularCol, "Pac_Correo": vo.Pac_CorreoCol, "Pac_Observación": vo.Pac_ObservaciónCol, "Pac_Tip_Men_Num": vo.Pac_Tip_Men_NumCol }

parameters[dsFieldName.substr(0,dsFieldName.length-3)] = newvalue;

/**
* execute the server "update" command
*/
doRequest("Update", parameters, saveItemHandler);

}

/**
* result handler for the "update" server command.
* Just alert the error, or do nothing if it's ok - the data has already
* been updated in the grid
*/
private function saveItemHandler(e:Object):void
{
if (e.isError)
{
Alert.show("Error: " + e.data.error);
}
else
{
}
}

/**
* dragHeader handler for the datagrid. This handler is executed when the user
* clicks on a header column in the datagrid
* updates the global orderColumn variable, refreshes the TableCollection
* @param event DataGridEvent details about the column
*/
private function setOrder(event:DataGridEvent):void
{
orderColumn = event.columnIndex;
var col:DataGridColumn = dataGrid.columns[orderColumn];
col.sortDescending = !col.sortDescending;

event.preventDefault();
fill();
}

/**
* Click handler for the "Save" button in the "Add" state
* collects the information in the form and adds a new object to the collection
*/
private function insertItem():void {
var parameters:* =
{
"method": "Insert", "Pac_Rut": Pac_RutCol.text, "Pac_Nombre": Pac_NombreCol.text, "Pac_Apellido": Pac_ApellidoCol.text, "Pac_Dirección": Pac_DirecciónCol.text, "Pac_Celular": Pac_CelularCol.text, "Pac_Correo": Pac_CorreoCol.text, "Pac_Observación": Pac_ObservaciónCol.text, "Pac_Tip_Men_Num": Tip_Men_NombreCmb.text };

/**
* execute the server "insert" command
*/
doRequest("Insert", parameters, insertItemHandler);
}

/**
* Result handler for the insert call.
* Alert the error if it exists
* if the call went through ok, return to the list, and refresh the data
*/
private function insertItemHandler(e:Object):void
{
if (e.isError)
{
Alert.show("Error: " + e.data.error);
}
else
{
goToView();
fill();
}
}

/**
* general utility function for refreshing the data
* gets the filtering and ordering, then dispatches a new server call
*
*/
private function fill():void
{
/**
* find the order parameters
*/
var desc:Boolean = false;
var orderField:String = '';

if(!isNaN(orderColumn))
{
var col:DataGridColumn = dataGrid.columns[orderColumn];
desc = col.sortDescending;
//remove the 'Col' particle
orderField = col.dataField.substr(0,col.dataField.length-3);
}

dataGrid.enabled = false;
CursorManager.setBusyCursor();

var parameters:* =
{
"orderField": orderField,
"orderDirection": (desc) ? "DESC" : "ASC",
"filter": filterTxt.text
}
/**
* execute the server "select" command
*/
doRequest("FindAll", parameters, fillHandler);
}

/**
* result handler for the fill call.
* if it is an error, show it to the user, else refill the arraycollection with the new data
*
*/
private function fillHandler(e:Object):void
{
if (e.isError)
{
Alert.show("Error: " + e.data.error);
}
else
{
dataArr.removeAll();
for each(var row:XML in e.data.row)
{
var temp:* = {};
for (var key:String in fields)
{
temp[key + 'Col'] = row[key];
}

dataArr.addItem(temp);
}

CursorManager.removeBusyCursor();
dataGrid.enabled = true;
}
}

/**
* Click handler for the "delete" button in the list
* confirms the action and launches the deleteClickHandler function
*/
private function deleteItem():void {

if (dataGrid.selectedItem)
{
Alert.show("Seguro de borrar el paciente seleccionado?",
"Confirmando Borrar", 3, this, deleteClickHandler);
}

}

/**
* Event handler function for the Confirm dialog raises when the
* Delete button is pressed.
* If the pressed button was Yes, then the product is deleted.
* @param object event
* @return nothing
*/
private function deleteClickHandler(event:CloseEvent):void
{
if (event.detail == Alert.YES)
{
var vo:* = dataGrid.selectedItem;

var parameters:* =
{
"Pac_Rut": vo.Pac_RutCol
}

/**
* execute the server "delete" command
*/
doRequest("Delete", parameters, deleteHandler);

setTimeout( function():void
{
dataGrid.destroyItemEditor();
},
1);
}
}

public function deleteHandler(e:*):void
{
if (e.isError)
{
Alert.show("Error: " + e.data.error);
}
else
{
var Pac_Rut:Number = parseInt(e.data.toString(), 10);
for (var index:Number = 0; index < dataArr.length; index++)
{
if (dataArr[index].Pac_RutCol == Pac_Rut)
{
dataArr.removeItemAt(index);
break;
}
}
}
}

/**
* deserializes the xml response
* handles error cases
*
* @param e ResultEvent the server response and details about the connection
*/
public function deserialize(obj:*, e:*):*
{
var toret:Object = {};

toret.originalEvent = e;

if (obj.data.elements("error").length() > 0)
{
toret.isError = true;
toret.data = obj.data;
}
else
{
toret.isError = false;
toret.metadata = obj.metadata;
toret.data = obj.data;
}

return toret;
}

/**
* result handler for the gateway
* deserializes the result, and then calls the REAL event handler
* (set when making a request in the doRequest function)
*
* @param e ResultEvent the server response and details about the connection
*/
public function resultHandler(e:ResultEvent):void
{
var topass:* = deserialize(e.result, e);
e.token.handler.call(null, topass);
}

/**
* fault handler for this connection
*
* @param e FaultEvent the error object
*/
public function faultHandler(e:FaultEvent):void
{
var errorMessage:String = "Connection error: " + e.fault.faultString;
if (e.fault.faultDetail)
{
errorMessage += "\n\nAdditional detail: " + e.fault.faultDetail;
}
Alert.show(errorMessage);
}

/**
* makes a request to the server using the gateway instance
*
* @param method_name String the method name used in the server dispathcer
* @param parameters Object name value pairs for sending in post
* @param callback Function function to be called when the call completes
*/
public function doRequest(method_name:String, parameters:Object, callback:Function):void
{
// add the method to the parameters list
parameters['method'] = method_name;

gateway.request = parameters;

var call:AsyncToken = gateway.send();
call.request_params = gateway.request;

call.handler = callback;
}


/**
* Click handler when the user click the "Create" button
* Load the "Update" canvas.
*/
public function goToUpdate():void
{
applicationScreens.selectedChild = update;
}

/**
* Load the "View" canvas.
*/
public function goToView():void
{
applicationScreens.selectedChild = view;
}
package clases{
import conexion.Conectar;

import flash.net.Responder;

import mx.collections.ArrayCollection;
import mx.controls.Alert;
import mx.controls.ComboBox;

public class Combos{
public var obj:Conectar = new Conectar("amfphp/gateway.php");//Conectarse a la DB
public var combo:ComboBox;//Combo a llenar
public var option:String;//Opcion 0 del combo
public function getCombo(combo:ComboBox, tabla:String='', campo:String='', condition:String='', option0:String=''):void{

combo = new ComboBox();
option0 = new String();
combo = Tip_Men_NombreCmb;
option0 = null;

var datos:Array = new Array();
datos["tipos_mensajes"] = tabla;//Tabla de consulta
datos["Tip_Men_Nombre"] = campo;//Campo a visualizar
datos["Tip_Men_Numero=Pac_Tip_Men_Num"] = condition;//Condition
obj.call("combos.getCombo", new Responder(exito, error), datos);
}

/*********************************************************/
private function exito(resultado:Array):void{
//Alert.show(resultado[1].toString()+" - "+resultado[2].toString());
if(resultado[0].toString()!='0'){
var lista:ArrayCollection = new ArrayCollection();
var list:Array = new Array();
list = resultado[1];
var oItem:Object;
if(null!=''){//Coloca una opcion en blanco
oItem = new Object();
oItem.data = -1;
oItem.label = null;
lista.addItem(oItem);
}
for(var i:int=0;i<list.length;i++){
oItem = new Object();
oItem.data = list[i]["id"];
oItem.label = list[i]["nom"];
lista.addItem(oItem);
}
Tip_Men_NombreCmb.dataProvider = lista;
}else Alert.show("Atención:\nLa lista se encuentra vacía.");
}//end function exito
private function error(resultado:Array):void{
Alert.show("Error:\nNo se pudo llenar la lista.");
}//end function error
/*********************************************************/

}
}

Por carlos.baeza.r

1 de clabLevel



 

firefox

 

Cristalab BabyBlue v4 + V4 © 2011 Cristalab
Powered by ClabEngines v4, HTML5, love and ponies.