27
PHP RUNNER IMÁGENES EN CAMPO:

PHP RUNNER.docx

Embed Size (px)

Citation preview

PHP RUNNERIMGENES EN CAMPO:

OTRA FORMA CON VARCHAR:

Como calcular valores al vuelo con PHPRunnerEn el Evento Javascript OnLoad de ADDPAGE

Ejemplo de programacin:

// DEFINO LAS VARIABLES LIGADAS A CAJAS DE TEXTO DEL FORMULARIOvar vprecio = Runner.getControl(pageid, 'precio');var vcantidad = Runner.getControl(pageid, 'cantidad');var vsubtotal = Runner.getControl(pageid, 'subtotal');

function func() {

//variable total = transformarflotante(vprecio) * tranfflotante(vcantidad)

vsubtotal.setValue(parseFloat(vprecio.getValue()) * parseFloat(vcantidad.getValue()));

};

//acciono los eventos on keyup - cuando la tecla ya se pulso llama a func//

vprecio.on('keyup', func);vcantidad.on('keyup', func);

UTILIZACION DE FUNCIONES JAVASCRIPTPARA VALIDAR CEDULA EJMPLO:*** HACER UN PROGRAMA .JS***function cedula(sVal){var xcedula=sVal;array=xcedula.split("");num=array.length;if(num==10){total=0;digito=(array[9]*1);for(i=0;i9)total=total+(mult-9);elsetotal=total+mult;}}decena=total/10;decena=Math.floor(decena);decena=(decena+1)*10;final=(decena-total);if((final==10&&digito==0)||(final==digito)){return true;}else{return"La Cdula no es valida";}}else{return"La Cdula no puede tener menos de 10 digitos";}}*** GUARDAR ESTE PROGRAMA EN LA RUTA:C:\Program Files\PHPRunner6.0\source\include\validate

Esta funcin la puedo incorporar en las validaciones:

DAR CLIC CLIC EN Y APARECE:

LA FUNCION QUE HABIAMOS COPIADO EN ESTE CASO CEDULA

CON ESTO SE VALIDAR LA CEDULA DE LA PERSONA Y CUANDO LA GENERAS YA TENDRAS UN CAMPO VALIDADO CON LA CEDULA.

$rs=CustomQuery("select max(editdate) as mx from TableName");if ($data=db_fetch_array($rs)){echo "Last update: ".$data["mx"];}else {echo "";}

Taming the beast: Events, Buttons and Code snippetsBY ADMIN, ON APRIL 28TH, 2011If you're new here, you may want to subscribe to myRSS feed. Thanks for visiting!You can expand the functionality of the web applications built by ASPRunner and PHPRunner by adding ASP and PHP code. Depending on your business needs and the type of data you need to access you can use any of the following 4 vehicles: Events Button View as: Custom Insert PHP/ASP Code SnippetEach extension method serves its own specific purpose and choosing the right tool for the job might be a daunting task. I will describe each of these tools in greater detail and then we will look at a few use cases illustrating the best fit for each tool.EventsEvents are fragments of ASP or PHP code executable after a certain action. You can define what an event should do and when it should be executed. (http://xlinesoft.com/phprunner/docs/events.htm)Server EventsA typical server side event would be to send an email with a new data, save data in another table, check record uniqueness, show related to current record info etc. You can either select one of predefined events or write your own from scratch. You can also choose when you want the event to be executed. For example: After record added, Before record deleted, After record updated etc.Example 1:Send an email notification every time the user submits a new entry. Here is an example of the "Send Simple Email" event that can be executed after the record has been added to the table.1. $email="[email protected]";2. $from="[email protected]";3. $msg="Hello there ";4. $subject="Sample subject";5. $ret=runner_mail(array('to' => $email, 'subject' => $subject,6. 'body' => $msg, 'from'=> $from));7. if(!$ret["mailed"])8. echo $ret["message"];Example 2:Check related items in Order Details table before deleting a record from Orders table.1. global $dal;2. $tblOrder = $dal->Table("OrderDetails");3. $rs = $tblOrder->Query("OrderID=".$deleted_values["OrderID"],"");4. $data = db_fetch_array($rs);5. if($data)6. return false;7. else8. return true;Javascript OnLoad EventsUsingJavascript APIyou can manipulate the fields on the Add and Edit pages by adding you own custom code to the Javascript OnLoad Events. For example you can calculate the value of the field on the fly depending on the values supplied in other fields. Or you can hide and display a control based on the values selected in another field.Example 1:Hide dropdown State if selected country is not US1. var ctrlCountry = Runner.getControl(pageid, 'country');2. var ctrlState = Runner.getControl(pageid, 'state');3. ctrlCountry.on('change', function(e){4. if (this.getValue() == 'US'){5. ctrlState.show();6. }else{7. ctrlState.hide();8. }9. });How to choose a right event for the jobAsk yourself the following questions:1. When? Events are executed at the very specific moment during page processing. For example, if you want to send an email after new record was added use AfterAdd event. Learn more about2. What data you need access to? Each event comes with its own set of parameters. Pick event that provides access to the data you need. For example, on the Edit page you need to store the value of field LastName in session variable. Event BeforeProcessEdit provides access to all field values on the edit page. This is the event you need to use.ButtonsYou can insert the a button into your web application to trigger a user-driven event executed on the button click. The button can be placed anywhere on the page. It supports both server and client side events for ASP and PHP. You can insert Javascript to be executed on the client side after the button is clicked, PHP or ASP code on the server side, and Javascript on the client side after the server side code is executed.More info on buttonsExample 1:Send the records selected on the List page via email.Add the following code to the OnServer event (Server tab):1. $email_msg = "";2. $email_msg.= "List of records";3. foreach($keys as $idx=>$val)4. {5. $email_msg.= "Record: ".($idx+1)."\r\n";6. //select values from TableName based on $val["ID1"]7. $tblName = $dal->Table("TableName");8. $rstmp = $tblName->Query("ID1=".$val["ID1"],"");9. $datatmp = db_fetch_array($rstmp);10. $email_msg.= "FieldName1: ".$datatmp["FieldName1"]."\r\n";11. $email_msg.= "FieldName2: ".$datatmp["FieldName2"]."\r\n";12. $email_msg.= "\r\n";13. }14. //send email15. $email="[email protected]";16. $subject="Sample subject";17. runner_mail(array('to' => $email, 'subject' => $subject, 'body' => $email_msg));Example 2:Modify the value of a field for all selected records on the List page.Add the following code to the OnServer event (Server tab):1. foreach($keys as $idx=>$val)2. {3. $sql = "update Invoices set Status='Paid' where InvoiceID=" .$val["InvoiceID"];4. CustomQuery($sql);5. }View As: CustomUse View As type Custom to modify the way field displayed on List/View/Print pages. View as: Custom provides access to any field value within the same record, which you can reference with the following syntax:$data["FieldName"]More info on "View as: Custom"Example 1:Display value of field FirstName as if LastName field is defined.You need to set the type of the field 'FirstName' to Custom and add the following code to it1. global $data;2. if ($data["LastName"])3. $value = $data["LastName"].", ".$value;Example 2:Convert a string into the upper case:1. $value = strtoupper($value);Example 3:Format 10-digit phone number into the following format (xxx) xxx-xxx:1. if (strlen($value)==10)2. {3. $value="(" . substr($value,0,3) . ") " . substr($value,3,3) . "-" . substr($value,6);4. }Insert PHP/ASP code snippetAdding PHP or ASP code snippets you can modify the appearance and functionality of any page. For example, you can add additional control elements to a web page or display some additional information. You can insert code snippet anywhere on the page. Unlike other methods Code Snippet doesnt provide any access to page data. You will have to use Session Variables to make data available to code snippet.More info on code snippetsExample 1:Display current time.echo now();Example 2:Add dropdown list box with values for searchE.g. when you select a company name from dropdown list box, only the data concerning selected company are displayed.1. //create dropdown box2. $str = "";3. $str.= "4. 6. Please select7. 8. ";9. //select values from database10. global $conn;11. $strSQL = "select company from tablename";12. $rs = db_query($strSQL,$conn);13. while ($data = db_fetch_array($rs))14. $str.="15. ".19. $data["company"]."20. 21. ";22. $str.="23. 24. ";25. echo $str;26. Example 3:Show list from customer orders1. global $dal;2. $tblOrders = $dal->Table("Orders");3. $rs = $tblOrders->Query("OrderID=".$_REQUEST["edtidi1"],"");4. $data = db_fetch_array($rs);5. $CustomerID = $data["CustomerID"];6. echo "Orders placed by " .$CustomerID. "7. ";8. $rsOrders = $tblOrders->Query("customerid='".$CustomerID."'","");9. while($data=db_fetch_array($rsOrders))10. {11. echo "".12. $data["OrderID"]." ".$data["OrderDate"]."13. ";14. }Session VariablesYou can use session variables anywhere in PHP/ASP code. It is particularly useful if you need to pass a certain value that is not available otherwise.Example 1:We need to add a link to the View page of the Cars table that would display all cars with the same car Make. We need to add a Code Snippet that displays 'Show similar cars' link. However the code snippet doesnt have access to the current Make value. Therefore we will define the session variable in theProcessValuesView($values)orProcessValuesEdit($values)events. We choose this event because it has access to all field values on the Edit/View pages:1. $_SESSION["Make"]=$values["Make"];Now we can go back to the Code Snippet on the View page and use the$_SESSION["Make"]variable.The code in the Code Snippet would look like this:1. echo "Show similar cars";EndnotesThis is it. If you want to check how well you understand the difference between those methods take a quickRunnerIQ test. This test was built by PHPRunner btw.We want your feedback in the following areas:1. What do you think about this tutorial? Is it too technical? Not enough examples? What other code related tutorials you want to see?2. RunnerIQ test. Is it too long? Too short? Boring? What kind of tests you want us to create?3. RunnerIQ test was created by PHPRunner (did I say that already?). Would you be interested in purchasing this quiz template for PHPRunner/ASPRunnerPro? What's the fair price for this ($1, $5, $10, $25, priceless?)Post your comments below.

How to calculate values on the fly

Let's say there are three fields on the add/edit page: Price, Quantity and Total. To calculate total value on the fly use Javascript code (add it to theAdd page: JavaScript OnLoadevent orEdit page: JavaScript OnLoadevent on theEventstab).Note: Change the values listed inredto match your specific needs.varctrlPrice = Runner.getControl(pageid,'Price');varctrlQuantity = Runner.getControl(pageid,'Quantity');varctrlTotal = Runner.getControl(pageid,'Total');functionfunc() { ctrlTotal.setValue(Number(ctrlPrice.getValue()) * Number(ctrlQuantity.getValue()));};ctrlPrice.on('keyup', func);ctrlQuantity.on('keyup', func);

To set the formatting proceed to Visual Editor and double-click on the field you want to format. In our case it is the field "Profitability". Select 'Custom' View As option. Add your code in the custom code editor. If the value of my current field is greater than zero I will set the font color to black, otherwise to red. Always remember to check the syntax of your code.

1. 2. if ($value < 0) {3. $value =$value. ' ';4. $color="black";5. } else {6. $value =''.$value. ' ';7. $color="red";8. }9. $value="$value";

Grabar datos en otra table//**********Savenewdatainanothertable************global$conn,$strTableName;$strSQLSave="INSERTINTOAnotherTable(Field1,Field2)values(";$strSQLSave.=$values["Field1"].",";$strSQLSave.=$values["Field2"];$strSQLSave.=")";db_exec($strSQLSave,$conn);

Add custom field to form

To add custom field to the form follow the instructions below.Note: Change the values listed inredto match your specific needs.1. Proceed to theVisual Editorpage, switch to HTML mode and add a custom input field to your form. Make sure you specify field ID.

2. Add the following code toJavascript OnLoadevent of the page where custom field was added:this.on('beforeSave',function(formObj, fieldControlsArr, pageObj){varval = $("#test").val(); formObj.baseParams['test'] = val;});

3. In any event likeBefore record addedorBefore processuse$_REQUEST["test"]to access the custom field value.

En before recordecho "alert('" .$_REQUEST["test"]. "')";combo para busquedasAdd dropdown list box with values for search

Add dropdown list box with values for search. E.g. when you select a company name from dropdown list box, only the data concerning selected company are displayed.To add this event use(Insert PHP code snippet) button on theVisual Editorpage.Note: Change the values listed inredto match your specific needs.//createdropdownbox$str="";$str.="Pleaseselect";//selectvaluesfromdatabaseglobal$conn;$strSQL="selectcompanyfromtablename";$rs=db_query($strSQL,$conn);while($data=db_fetch_array($rs))$str.="".$data["company"]."";$str.="";echo$str;

ACCESO A VARIABLES PHP1 Esto en beforedysplayecho"window.username = '".$_SESSION["UserID"]."';window.group = '".$_SESSION["GroupID"]."';";

2. Use new variables (usernameandgroup) inJavascript OnLoadevent. For example, make a control disabled, if user in not admin:if(username!='admin'){ varctrl = Runner.getControl(pageid,'Comments'); ctrl.setDisabled();}

Ejemplos: global $conn;

$strconsultasupervisor = "select * from seguridades where nombreusuario='" .$_SESSION["UserID"]. "'";$rsexistio = db_query($strconsultasupervisor,$conn);$rsconsulsupervisor=db_fetch_array($rsexistio);

echo "window.tipousu = '" . $rsconsulsupervisor["tipousuario"] . "';window.superv = '" . $rsconsulsupervisor["supervisor"] . "';window.username = '" . $_SESSION["UserID"]. "';window.group = '" . $_SESSION["GroupID"]. "';";

if (username!='rrrr'){ alert('I\'m a po---" . yousuario . "---pup window'); var observaciones2 = Runner.getControl(pageid, 'observaciones2'); observaciones2.setValue(username);

var observaciones = Runner.getControl(pageid, 'observaciones'); observaciones.setValue(tipousu);}

How to calculate values on the fly

Let's say there are three fields on the add/edit page: Price, Quantity and Total. To calculate total value on the fly use Javascript code (add it to theAdd page: JavaScript OnLoadevent orEdit page: JavaScript OnLoadevent on theEventstab).Note: Change the values listed inredto match your specific needs.varctrlPrice = Runner.getControl(pageid,'Price');varctrlQuantity = Runner.getControl(pageid,'Quantity');varctrlTotal = Runner.getControl(pageid,'Total');functionfunc() { ctrlTotal.setValue(Number(ctrlPrice.getValue()) * Number(ctrlQuantity.getValue()));};ctrlPrice.on('keyup', func);ctrlQuantity.on('keyup', func);

__

How to convert input into upper case

To convert user entered data into upper case, use the following code inJavascript OnLoadevent.Note: Change the values listed inredto match your specific needs.varctrl = Runner.getControl(pageid,'FieldName');ctrl.addStyle('text-transform: uppercase;');

How to work with foldable section

To manipulate a foldable section, you need to know the section name. To find this name proceed to theVisual Editorpage, select the page with foldable section, make the yellow section rectangle selected and switch to HTML mode. Section name will be highlighted (e.g.{$Section New_section1}). HereNew_section1is the section name. Now paste it to the code below.Note: Change the values listed inredto match your specific needs.1. To make section expanded, use the following code inJavascript OnLoadevent:var section="New_section1";$("#section_"+section).show();$("#section_"+section+"Butt").attr("src",'images/minus.gif');

2. To make section collapsed, use the following code inJavascript OnLoadevent:var section="New_section1";$("#section_"+section).hide();$("#section_"+section+"Butt").attr("src",'images/plus.gif');

MAESTROS DETALLE

$rs = CustomQuery("SELECT COUNT(*) as details_number FROM EstadoMicro_Feria WHERE FICHA=".$values['FICHA']);$record = db_fetch_array($rs);

if($record['details_number'] == 0){ $xt->assign("displayDetailTable_EstadoMicro_Feria",false);}

$rs = CustomQuery("SELECT COUNT(*) as details_number FROM EstadoMicro_Feria WHERE FICHA='".$_GET['editid1']."'");$record = db_fetch_array($rs);

if($record['details_number'] == 0){ $xt->assign("displayDetailTable_EstadoMicro_Feria",false);}

PAGINA EXTERNA CUSTOMinclude("include/dbcommon.php");

if(!@$_SESSION["UserID"]){ header("Location: login.php"); return;}

OTRO:session_start();include("include/dbcommon.php");global $conn;$sql = "SELECT GroupID FROM ugmembers WHERE UserName ='".$_SESSION["UserID"]."'";$rs = db_query($sql,$conn);

$authorized_groups = array(-1,1);$is_authorized = FALSE;

while($data = db_fetch_array($rs)){ if(in_array($data['GroupID'],$authorized_groups)) { $is_authorized = TRUE; break; }}

if( ! $is_authorized){ header("Location: login.php?message=expired"); return;}

FILTROS EN LISTAS

$tdatadetallesclases[".sqlHead"] = "SELECT CODMATER, DETALLE_CLASE, FECHA, USUARIO";$tdatadetallesclases[".sqlFrom"] = "FROM detallesclases";$tdatadetallesclases[".sqlWhereExpr"] = "USUARIO ='HARRY'";$tdatadetallesclases[".sqlTail"] = "";EJEMPLO:

SQL: LISTADOS

MANEJO DE USUARIOSfunction AfterSuccessfulLogin($username,$password,$data){// con esto creo variable global de un valor de la tabla de usuarios en este caso tipo$_SESSION['TIPOUSUARIO'] = $data["TIPO"];}function BeforeQueryList($strSQL,$strWhereClause,$strOrderBy){if ($_SESSION["TIPOUSUARIO"] 'COORDIN'){// utlizo esto para que me filter por el usuario especifico de la sesion$strWhereClause = whereAdd($strWhereClause, "USUARIO = '".$_SESSION["UserID"]."'");}}

EN EL FORMULARIO SNIPPETecho "window.vusuario = '" . $_SESSION["UserID"] . "';window.vtipo = '" . $_SESSION["TIPOUSUARIO"] . "';";

function OnPageLoad(pageid){var CTusuario = Runner.getControl(pageid, 'USUARIO');CTusuario.setValue(vusuario) ;CTusuario.hide();