Sei sulla pagina 1di 28

PHP RUNNER

IMGENES EN CAMPO:

OTRA FORMA CON VARCHAR:

Como calcular valores al vuelo con PHPRunner


En el Evento Javascript OnLoad de ADDPAGE

Ejemplo de programacin:

// DEFINO LAS VARIABLES LIGADAS A CAJAS DE TEXTO DEL FORMULARIO


var 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 JAVASCRIPT


PARA 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;i<(num-1);i++)
{mult=0;if((i%2)!=0)
{total=total+(array[i]*1);}
else
{mult=array[i]*2;if(mult>9)
total=total+(mult-9);else
total=total+mult;}}
decena=total/10;decena=Math.floor(decena);decena=(decena+1)*10;final=(decenatotal);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 snippets
BY ADMIN, ON APRIL 28TH, 2011

If you're new here, you may want to subscribe to my RSS 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 Snippet

Each 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.

Events
Events 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 Events
A 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="test@test.com";
2.

$from="admin@test.com";

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.

else

8.

return true;

Javascript OnLoad Events

Using Javascript API you 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 US

1. 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 job


Ask 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 about
2. 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.

Buttons

You 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 buttons
Example 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 email
15. $email="test@test.com";

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: Custom


Use 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 it

1. 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 snippet


Adding 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 snippets
Example 1:
Display current time.

echo now();

Example 2:
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.

1. //create dropdown box


2. $str = "";
3. $str.= "
4. <select onchange=\"window.location.href=this.options[this.
5.

selectedIndex].value;\">

6. <option value=\"\">Please select</option>


7.
8. ";
9. //select values from database
10. global $conn;
11. $strSQL = "select company from tablename";
12. $rs = db_query($strSQL,$conn);
13. while ($data = db_fetch_array($rs))
14.

$str.="

15. <option value=\"tablename_list.php?ctlSearchFor=".


$data["company"].
16.
"&srchOptShowStatus=1&ctrlTypeComboStatus=0&srchWinShowStatus=0&
a=
17.

integrated&id=1&criteria=and&type1=&value11=".
$data["company"].

18.
"&field1=company&option1=Contains&not1=a=search&value=1\">".

19.

$data["company"]."</option>

20.
21. ";
22. $str.="</select>
23.
24. ";
25. echo $str;
26.

Example 3:
Show list from customer orders

1. 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.
10.

while($data=db_fetch_array($rsOrders))
{

11.

echo "<a href="Orders_edit.php?editid1=%22.$data[%22OrderID


%22]." target="_blank">".

12. $data["OrderID"]."</a> ".$data["OrderDate"]."


13.

";

14.

Session Variables
You 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) or ProcessValuesEdit($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 "<a href='Cars_list.php?a=integrated&ctlSearchFor=" .


$_SESSION["Make"] .
2. "&simpleSrchFieldsComboOpt=Make&simpleSrchTypeComboNot=&simpleSr
chTypeComboOpt=Equals'>Show similar cars</a>";

Endnotes
This 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 the Add
page: JavaScript OnLoad event or Edit page: JavaScript OnLoad event on
the Events tab).
Note: Change the values listed in red to match your specific needs.
var ctrlPrice = Runner.getControl(pageid, 'Price');
var ctrlQuantity = Runner.getControl(pageid, 'Quantity');
var ctrlTotal = Runner.getControl(pageid, 'Total');
function func() {
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. ' <img src="green.png" alt="" />';

4.

$color="black";

5. } else {
6.

$value ='<strong>'.$value. '</strong> <img src="red.png"


alt="" />';

7.

$color="red";

8. }
9. $value="<span style='color: " . $color . ";'>$value</span>";

Grabar datos en otra table


//********** Save new data in another table ************
global $conn,$strTableName;
$strSQLSave = "INSERT INTO AnotherTable (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 in red to match your specific needs.
1. Proceed to the Visual Editor page, switch to HTML mode and add a
custom input field to your form. Make sure you specify field ID.

<INPUT id=test type=text>

2. Add the following code to Javascript OnLoad event of the page where
custom field was added:

this.on('beforeSave', function(formObj, fieldControlsArr,


pageObj){
var val = $("#test").val();
formObj.baseParams['test'] = val;
});

3. In any event like Before record added or Before


process use $_REQUEST["test"] to access the custom field value.

En before record
echo "<script>alert('" .$_REQUEST["test"]. "')</script>";
combo para busquedas

Add 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
Editor page.

(Insert PHP code snippet) button on the Visual

Note: Change the values listed in red to match your specific needs.
//create dropdown box
$str = "";
$str.= "<select onchange=\"window.location.href=this.options[thi
s.".
"selectedIndex].value;\"><option value=\"\">Please select</opt
ion>";
//select values from database
global $conn;
$strSQL = "select company from tablename";
$rs = db_query($strSQL,$conn);
while ($data = db_fetch_array($rs))
$str.="<option value=\"tablename_list.php?ctlSearchFor=".
$data["company"].
"&srchOptShowStatus=1&ctrlTypeComboStatus=0&srchWinShowStatu
s=0&a=".
"integrated&id=1&criteria=and&type1=&value11=".
$data["company"].
"&field1=company&option1=Contains&not1=a=search&value=1\">".
$data["company"]."</option>";
$str.="</select>";
echo $str;

ACCESO A VARIABLES PHP


1 Esto en beforedysplay

echo "<script>
window.username = '" . $_SESSION["UserID"]. "';
window.group = '" . $_SESSION["GroupID"]. "';
</script>";

2. Use new variables (username and group) in Javascript OnLoad event. For
example, make a control disabled, if user in not admin:

if (username!='admin')

{
var ctrl = 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 "<script>
window.tipousu = '" . $rsconsulsupervisor["tipousuario"] . "';
window.superv = '" . $rsconsulsupervisor["supervisor"] . "';
window.username = '" . $_SESSION["UserID"]. "';
window.group = '" . $_SESSION["GroupID"]. "';
</script>";

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

Add page: JavaScript OnLoad event or Edit page: JavaScript


OnLoad event on the Events tab).
the

Note: Change the values listed in red to match your specific needs.

var ctrlPrice = Runner.getControl(pageid, 'Price');


var ctrlQuantity = Runner.getControl(pageid, 'Quantity');
var ctrlTotal = Runner.getControl(pageid, 'Total');

function func() {
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
in

Javascript OnLoad event.


Note: Change the values listed in red to match your specific needs.

var ctrl = 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 the Visual Editor page, 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}).
Here New_section1 is the section name. Now paste it to the code below.
Note: Change the values listed in red to match your specific needs.
1. To make section expanded, use the following code in

Javascript

OnLoad event:

var section="New_section1";
$("#section_"+section).show();
$("#section_"+section+"Butt").attr("src", 'images/minus.gif');

2. To make section collapsed, use the following code in

OnLoad event:

var section="New_section1";

Javascript

$("#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 CUSTOM


include("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 USUARIOS
function 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 SNIPPET
echo "<script>
window.vusuario = '" . $_SESSION["UserID"] . "';
window.vtipo = '" . $_SESSION["TIPOUSUARIO"] . "';
</script>";

function OnPageLoad(pageid)
{

var CTusuario = Runner.getControl(pageid, 'USUARIO');


CTusuario.setValue(vusuario) ;
CTusuario.hide();

Potrebbero piacerti anche