AS3 Flash How to make text fields required? - actionscript-3

I want to know how to put restrictions in the fields like if the user didn't type anything or still has a blank field, then it should not submit but shows *required field or something like that. Examples would be great.
The codes. I don't know where to start from here
var fllname:TextField;
var address:TextField;
var ContactNo:TextField;
var quantity:TextField;
var otrack:TextField;
btnSubmit1.addEventListener(MouseEvent.CLICK, submit);
function submit(e:MouseEvent):void{
var urlvars: URLVariables = new URLVariables;
urlvars.fllname = fllname.text;
urlvars.Oadd = address.text;
urlvars.ContactNo = ContactNo.text;
urlvars.oquantiy = quantity.text;
urlvars.otrack = otrack.text;
urlvars.cake = txtCake.text;
urlvars.frosting = txtFrosting.text;
urlvars.topping = txtToppings.text;
urlvars.topping2 = txtToppings2.text;
urlvars.filling = txtFilling.text;
urlvars.amt = lblAmount.text;
var urlreq:URLRequest = new URLRequest("http://localhost/MCC/order.php");
urlreq.method = URLRequestMethod.POST;
urlreq.data = urlvars;
var loader : URLLoader = new URLLoader;
loader.dataFormat = URLLoaderDataFormat.VARIABLES;
loader.load(urlreq);
nextFrame();
}

You can use the enabled parameter to control if your btnSubmit1 is clickable, so you will probably need to start with is disabled.
btnSubmit1.enabled = false;
btnSubmit1.addEventListener(MouseEvent.CLICK, submit);
Next you will need to listen to the TextEvent.TEXT_INPUT event on all your TextFields
fllname.addEventListener(TextEvent.TEXT_INPUT,paramChanged);
address.addEventListener(TextEvent.TEXT_INPUT,paramChanged);
//etc etc
This will notify you any-time the user changes their value, you can then create a single function (or a function for each control) to test the values, once they pass you can re-enable the submit button.
function paramChanged(event:TextEvent):void
{
if (fllname.text != "" && address.text != "")//add your other fields here
{
btnSubmit1.enabled = true;
}
else
{
btnSubmit1.enabled = false;//If something changes that means we now fail the test you will want to disable the button again
}
}
You could make custom test functions for each field as needed.

Related

Passing variables through navigateURL to open iFrame as3

By using NavigateURL I can easily pass variables as below through Flash to paypal, this works no problem and can include all the data required.
var req:URLRequest = new URLRequest("https://www.paypal.com/cgi-bin/webscr");
var reqVars:URLVariables = new URLVariables();
reqVars.cmd = "_xclick-subscriptions";
reqVars.business = "BUSINESS CODE";
reqVars.lc = "GR";
reqVars.item_name = "Product Name";
reqVars.item_number = "Product Number 0001";
reqVars.no_note = "1";
reqVars.no_shipping = "2";
reqVars.src = "1";
reqVars.a3 = "15.00";
reqVars.p3 = "1";
reqVars.t3 = "Y";
reqVars.currency_code = "EUR";
//and so on
req.data = reqVars;
req.method = URLRequestMethod.POST;
navigateToURL(req);
By using callIframe as shown below I can easily open an iFrame from Flash.
calliFrame("http://www.webAddress.com/" +"?iframe=true&width=800&height=550", "Page Title", "Page Description");
function calliFrame(url:String, title:String, desc:String):void{
if (ExternalInterface.available) {
trace("calling prettyPhoto");
try {
ExternalInterface.call('$.prettyPhoto.open', url, title, desc);
} catch (event:Error) {
trace("Error occurred!");
}
} else {
trace("External Interface unavailable");
}
}
Is it possible to pass the navigateURL variables through the calliFrame method? I've tried variations but not gotten to either transfer the data or show the page.
I hoped something like the example below would work but only get a blank page or list of the data shown in the iFrame:
calliFrame("https://www.paypal.com/cgi-bin/webscr" +reqVars +"?iframe=true&width=800&height=550", "Page Title", "Page Description");
Any help would be much appreciated, thanks in advance.
The second parameter is the window name, so all you gotta do is pass the name of your iframe.
public function navigateToURL(request:URLRequest, window:String = null):void
docs: http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/net/package.html#navigateToURL()

Trigger UiApp-builder callback within another routine

Serge's solution here seemed like the way to go about this, but I'm a bit afraid that my circumstances may be too different...
I have a button where users can add a new set of rows with controls to a FlexTable, in order to allow them to insert a new member into a record set. After designing and building the app to do this (and despite assurances to the contrary), a requirement was then added for the users to be able to edit the record sets at a later date.
I've finally managed to get the data retrieved and correctly displayed on the Ui - for single member record sets. As a final stage, I am now attempting to extend this to accommodate record sets having more than one member. Obviously this requires determining how many members there are in the record set, and then adding the new rows/control group to the FlexTable, before loading the member into each control group.
So within this routine, (depending on how many members there are) I may need to trigger the same callback, which the user normally does with a button. However, the difference with Serge's fine example, is that his code triggers the checkbox callback at the end of his routine once all the Ui components are in place. My situation needs to do this on the fly - and so far I'm getting 'Unexpected error', which suggests to me that the Ui is not able to update with the added FlexTable controls before my code attempts to assign values to them.
Does anyone have any insight into this problem? Is my only recourse to completely re-build a fixed Ui and dispense with the dynamic rowset model?
Code follows -
1. event for adding controls:
var app = UiApp.getActiveApplication();
var oFlexGrid = app.getElementById('ExpenseDetail');
var oRowCount = app.getElementById('rowCount');
var oScriptDBId = app.getElementById('scriptDBId');
var iRows = parseInt(e.parameter.rowCount);
var sVId = e.parameter.scriptDBId;
var vGridDefs = loadArrayById(sVId); //retrieve upload definition array from ScriptDB
var vControlNames = [];
if (isOdd(iRows)){
var sColour = 'AliceBlue';
} else {
var sColour = 'LavenderBlush';
};
oFlexGrid.insertRow(0);
oFlexGrid.insertRow(0);
oFlexGrid.insertRow(0);
oFlexGrid.insertRow(0);
oFlexGrid.setRowStyleAttributes(0,{'backgroundColor':sColour});
oFlexGrid.setRowStyleAttributes(1,{'backgroundColor':sColour});
oFlexGrid.setRowStyleAttributes(2,{'backgroundColor':sColour});
oFlexGrid.setRowStyleAttributes(3,{'backgroundColor':sColour});
var vExpenseDef = Get_NamedRangeValues_(CONST_SSKEY_APP,'UIAPP_GridExpense');
iRows = iRows+1;
vControlNames = CreateGrid_MixedSet_(iRows, vExpenseDef, oFlexGrid, app);
oRowCount.setText(iRows.toString()).setValue(iRows.toString());
//SOME INCONSEQUENTIAL CODE REMOVED HERE, LET ME KNOW IF YOU NEED IT
vGridDefs = vGridDefs.concat(vControlNames); // unify grid definition arrays
var sAryId = saveArray('expenseFieldDef', vGridDefs);
oScriptDBId.setText(sAryId).setValue(sAryId); //store array and save ScriptDB ID
if (e.parameter.source == 'btnExpenseAdd'){
hideDialog(); //IGNORE CHEKCBOX-DRIVEN CALLS
};
return app;
2. routine that calls the event
var app = UiApp.getActiveApplication();
var oPanelExpense = app.getElementById('mainPanelExpense');
var oPanelIncome = app.getElementById('mainPanelIncome');
var oPanelEdit = app.getElementById('mainPanelEdit');
var chkExpenseAdd= app.getElementById('chkExpenseAdd');
var bExpenseTrigger = e.parameter.chkExpenseAdd;
var sVoucherId = nnGenericFuncLib.cacheLoadObject(CACHE_EDIT_VOUCHERID);
var sVoucher = e.parameter.ListSearch1Vouchers;
var aryVoucherInfo = getVoucherEditDetail(sVoucherId);
//SAVE FOR RECORD MARKING CALLBACK
nnGenericFuncLib.cacheSaveObject(CACHE_EDIT_OLDRECORDS, JSON.stringify(aryVoucherInfo), CACHE_TIMEOUT);
sVoucher = nnGenericFuncLib.textPad(sVoucher, '0', 7);
var bExp = (sVoucher.substring(0,2) == '03')
var oRowCount = app.getElementById('rowCount');
var iRowCount = parseInt(e.parameter.rowCount);
var sControlName = '';
var vControlVal = '';
var iExpIdx = 0;
var sControlType = '';
var oControl = '';
var vSummaryTotal = 0;
for (var iVal in aryVoucherInfo){
sControlName = aryVoucherInfo[iVal][2];
vControlVal = aryVoucherInfo[iVal][3];
switch (sControlName){
case 'ESUM60':
vSummaryTotal = vControlVal;
break;
case 'EXUSRN':
continue; //DON'T OVERWRITE CURRENT USERNAME
break;
};
if (sControlName.indexOf('_')!=-1){ //TEST FOR CONTROL SET MEMBER
var aryControlSet = sControlName.split('_');
if (parseInt(aryControlSet[1])>iRowCount){//*** TRIGGER THE EVENT ***
Logger.log(bExpenseTrigger + ' - ' + !bExpenseTrigger);
chkExpenseAdd.setValue(!bExpenseTrigger, true);
iRowCount = iRowCount +1;
};
};
oControl = app.getElementById(sControlName);
var vCache = cacheSaveReturn(CACHE_UIEX_LISTS,sControlName);
if (typeof vCache == 'undefined'){
oControl.setValue(vControlVal);
oControl.setText(vControlVal);
//controlSetTextBox(oControl,vControlVal);
//controlSetDateBox(oControl,vControlVal);
} else {
if (!(nnGenericFuncLib.arrayIsReal(vCache))){
vCache = JSON.parse(vCache);
};
vCache = vCache.indexOf(vControlVal);
if (vCache != -1){
oControl.setSelectedIndex(vCache);
} else {
controlSetListBox(oControl,vControlVal);
};
};
};
//SOME CODE REMOVED HERE
hideDialog();
return app;
Mogsdad to the rescue!
The answer (see above) for those at the back of the class (with me) is to simply pass the app instance parameter (e) to the event function, calling it directly from the main routine, thus keeping the chronology in step for when it returns the app to complete the routine. No need for the checkbox in this situation.
This only took me all day, but thanks Mogsdad! :)
Snippet below taken from 1/2 way down code sample 2 in the OP:
if (sControlName.indexOf('_')!=-1){ //TEST FOR CONTROL SET MEMBER
var aryControlSet = sControlName.split('_');
if (parseInt(aryControlSet[1])>iRowCount){
eventAddExpense(e); //THAT'S ALL IT TAKES
iRowCount = iRowCount +1;
};
};

Displaying PopupPanel

THREE QUESTIONS:
Why does my popupPanel not display correctly?
How can I only get it to appear once if clicked multiple times?
How can I add a Close button to the popupPanel?
function showPassword(e){
var app = UiApp.getActiveApplication();
var vrtPanel = app.getElementById("vrtPanel");
//Create Spreadsheet Source
var spSheet = SpreadsheetApp.openById('0Aur3owCpuUY-dF92dGp3c2RORGNkY011dGFnMjBXbXc');
var spTeacherList = spSheet.getSheetByName('TeacherList');
//Create the form elements
var hdlTeacherName = app.createServerHandler('getTeacherName').addCallbackElement(vrtPanel);
var lbxTeacherName = app.createListBox().setId('lbxTeacherName').setName('lbxTeacherName').addChangeHandler(hdlTeacherName);
var lstTeacherNames = spTeacherList.getRange(1,1,spTeacherList.getLastRow(),1).getValues();
lstTeacherNames.sort();
for (var l = 0; l < lstTeacherNames.length; l++) {
lbxTeacherName.addItem(lstTeacherNames[l],l);
}
var lblTeacherName = app.createLabel('Teacher Name:');
var txtTeacherName = app.createTextBox().setName('txtTeacherName').setId('txtTeacherName').setVisible(false);
var lblExt = app.createLabel('Ext:');
var txtExt = app.createTextBox().setName('txtExt').setId('txtExt');
var lblEmail = app.createLabel('Email:');
var txtEmail = app.createTextBox().setName('txtEmail').setId('txtEmail');
var lblSchool = app.createLabel('School:');
var txtSchool = app.createTextBox().setName('txtSchool').setId('txtSchool');
var btnCreate = app.createButton('Create Event');
//Create validation handler
var valSubmit = app.createServerClickHandler('valSubmit');
valSubmit.addCallbackElement(vrtPanel);
//Add this handler to the button
btnCreate.addClickHandler(valSubmit);
//Add all the elemnts to the panel
var formTable = app.createFlexTable().setCellPadding(3);
vrtPanel.add(formTable);
formTable
.setWidget(0,0,lbxTeacherName)
.setWidget(0,1,txtExt)
.setWidget(0,2,txtTeacherName)
.setWidget(1,0,txtEmail)
.setWidget(2,0,btnCreate);
//Add all the panel to the popup
var popPassword = app.createDecoratedPopupPanel(false, true).setId("popPassword");
popPassword.add(vrtPanel);
app.add(vrtPanel);
app.add(popPassword);
return app;
}
There is some disorder in the way you use the popupPanel, you have to add it to your main panel and add the table you want to show in it to the popup itself.
You should also decide where you want to show it.
Here is the relevant part of your code working :
//Add all the elemnts to the panel
var formTable = app.createFlexTable().setCellPadding(3);
formTable
.setWidget(0,0,lbxTeacherName)
.setWidget(0,1,txtExt)
.setWidget(0,2,txtTeacherName)
.setWidget(1,0,txtEmail)
.setWidget(2,0,btnCreate);
var popPassword = app.createDecoratedPopupPanel(false, true).setPopupPosition(150,300).setId("popPassword");
vrtPanel.add(popPassword.add(formTable));
popPassword.show();
return app;
}
To answer the second point : il won't show up multiple time, just once.
point 3 : if you want to close it with a button you will have to add a button and a server handler to close it (by getting it with an ID just as any other widget) but it would be easier and userfriendly to take advantage of the autohide feature, just change the definition parameters like this :
var popPassword = app.createDecoratedPopupPanel(true).setPopupPosition(150,300).setId("popPassword");
edit : in the example above you can also use
app.getElementById('popPassword').hide()
in your 'valSubmit' function (called by the button) even without the autohide so the popup will hide when the handler function executes.

Upload pre-selected file with actionscript

I'm creating a photoshop extension where I need to save the file people are working on and upload it to a server. So I want the extension to be able to automatically choose the current file and upload it to my server.
Problem is I don't know how to pre-select a file for people. Here's my code so far:
var app:Application = Photoshop.app;
var doc:Document = app.documents.add();
doc.selection.selectAll();
var color:RGBColor = new RGBColor();
color.red = 0;
color.green = 0;
color.blue = 255;
doc.selection.fill(color);
var saveOptions:JPEGSaveOptions = new JPEGSaveOptions();
//Add other PDF save options here.
doc.saveAs(File.applicationStorageDirectory, saveOptions);
var jsonOBJ:Object = {};
jsonOBJ.option = "iphone";
jsonOBJ.title = "c";
jsonOBJ.description = "s";
jsonOBJ.app_store_url = "iphone";
jsonOBJ.tags = "c";
jsonOBJ.temp_number = 1;
var _service:HTTPService = new HTTPService();
_service.url = "http://localhost:3000/designs";
_service.method = "POST";
_service.contentType = "application/json";
_service.resultFormat = "text";
_service.useProxy = false;
_service.makeObjectsBindable = true;
_service.addEventListener(FaultEvent.FAULT,faultRX);
_service.addEventListener(ResultEvent.RESULT,resultRX);
_service.showBusyCursor = true;
_service.send( JSON.encode( jsonOBJ ) );
function resultRX():void
{
trace(ResultEvent.RESULT);
}
function faultRX():void
{
trace(FaultEvent.FAULT);
}
var file:FileReference;
var filefilters:Array;
var req:URLRequest;
filefilters = [ new FileFilter('Images', '*.jpg') ]; // add other file filters
file.browse(filefilters);
It's a photoshop extension. I ended up using FileReference and link to the file. it worked. I dunno how to actually upload the image though. When I use file.upload(requestUrl), it sends along a wrong content type. –

AS3 load variables from a txt file which has && formatting

I'm trying to load a txt file of variables into my AS3 project. The problem I have though seems to be down to the fact that the txt file (which is pre formatted and cannot be changed) is formatted using double amphersands... e.g.
&name=mark&
&address=here&
&tel=12345&
I'm using the following code to load the txt file
myLoader.addEventListener(Event.COMPLETE, onLoaded, false, 0, true);
myLoader.dataFormat = URLLoaderDataFormat.VARIABLES;
urlRqSend = new URLRequest(addressToTxt.txt);
public function onLoaded(e:Event):void {
trace(myLoader.data);
}
Using URLLoaderDataFormat.VARIABLES generates the following error:
Error: Error #2101: The String passed to URLVariables.decode() must be a URL-encoded query string containing name/value pairs.
If I use URLLoaderDataFormat.TEXT I can load the data successfully but I'm not able (or don't know how to) access the variables.
Would anyone have any ideas or work arounds to this please.
Thanks,
Mark
I had that kind of problem some time ago.
I suggest you to load first as a text, remove those line breaks, the extra amphersands and parse manually:
var textVariables:String;
var objectVariables:Object = new Object();
...
myLoader.addEventListener(Event.COMPLETE, onLoaded, false, 0, true);
myLoader.dataFormat = URLLoaderDataFormat.TEXT;
urlRqSend = new URLRequest(addressToTxt.txt);
public function onLoaded(e:Event):void {
textVariables = myLoader.data;
textVariables = textVariables.split("\n").join("").split("\r").join(""); // removing line breaks
textVariables = textVariables.split("&&").join("&"); // removing extra amphersands
var params:Array = textVariables.split('&');
for(var i:int=0, index=-1; i < params.length; i++)
{
var keyValuePair:String = params[i];
if((index = keyValuePair.indexOf("=")) > 0)
{
var key:String = keyValuePair.substring(0,index);
var value:String = keyValuePair.substring(index+1);
objectVariables[key] = value;
trace("[", key ,"] = ", value);
}
}
}
I wrote that code directly here, I don't have any AS3 editor here, so, maybe you'll find errors.
If you have data in String and it has a structure just like you wrote, you can do a workaround:
dataInString = dataInString.split("\n").join("").split("\r").join(""); // removing EOL
dataInString = dataInString.slice(0,-1); // removing last "&"
dataInString = dataInString.slice(0,1); // removing first "&"
var array:Array = dataInString.split("&&");
var myVariables:Object = new Object();
for each(var item:String in array) {
var pair:Array = item.split("=");
myVariables[pair[0]] = pair[1];
}
That should make you an object with proper variables.