Taming the beast: Events, Buttons and Code snippets

PHP, PHP Code Generator, Tutorials

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.

$email="test@test.com";
 $from="admin@test.com";
 $msg="Hello there ";
 $subject="Sample subject";
 $ret=runner_mail(array('to' => $email, 'subject' => $subject, 
'body' => $msg, 'from'=> $from));
 if(!$ret["mailed"])
 echo $ret["message"];

Example 2:

Check related items in Order Details table before deleting a record from Orders table.

global $dal;
 $tblOrder = $dal->Table("OrderDetails");
 $rs = $tblOrder->Query("OrderID=".$deleted_values["OrderID"],"");
 $data = db_fetch_array($rs);
 if($data)
 return false;
 else
 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

var ctrlCountry = Runner.getControl(pageid, 'country');
var ctrlState = Runner.getControl(pageid, 'state');
ctrlCountry.on('change', function(e){
if (this.getValue() == 'US'){
ctrlState.show();
}else{
ctrlState.hide();
}
});

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

$email_msg = "";
$email_msg.= "List of records";
foreach($keys as $idx=>$val)
{
$email_msg.= "Record: ".($idx+1)."\r\n";
//select values from TableName based on $val["ID1"]
$tblName = $dal->Table("TableName");
$rstmp = $tblName->Query("ID1=".$val["ID1"],"");
$datatmp = db_fetch_array($rstmp);
$email_msg.= "FieldName1: ".$datatmp["FieldName1"]."\r\n";
$email_msg.= "FieldName2: ".$datatmp["FieldName2"]."\r\n";
$email_msg.= "\r\n";
}
//send email
$email="test@test.com";
$subject="Sample subject";
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):

foreach($keys as $idx=>$val)
{
$sql = "update Invoices set Status='Paid' where InvoiceID=" .$val["InvoiceID"];
CustomQuery($sql);
}

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

global $data;
if ($data["LastName"])
$value = $data["LastName"].", ".$value;

Example 2:

Convert a string into the upper case:

$value = strtoupper($value);

Example 3:

Format 10-digit phone number into the following format (xxx) xxx-xxx:

if (strlen($value)==10)
 {
 $value="(" . substr($value,0,3) . ") " . substr($value,3,3) . "-" . substr($value,6);
 }

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 doesn’t 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.

//create dropdown box 
$str = ""; 
$str.= ""; 
echo $str; 

Example 3:

Show list from customer orders

global $dal;
 $tblOrders = $dal->Table("Orders");
 $rs = $tblOrders->Query("OrderID=".$_REQUEST["edtidi1"],"");
 $data = db_fetch_array($rs);
 $CustomerID = $data["CustomerID"];
 echo "Orders placed by " .$CustomerID. "
 ";
 $rsOrders = $tblOrders->Query("customerid='".$CustomerID."'","");
 while($data=db_fetch_array($rsOrders))
 {
 echo "". 
$data["OrderID"]." ".$data["OrderDate"]."
 ";
 }

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 doesn’t have access to the current Make value. Therefore we will define the session variable in the ProcessValuesView($values) or ProcessValuesEdit($values) events. We choose this event because it has access to all field values on the Edit/View pages:

$_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:

echo "Show similar cars";

Endnotes

This is it. If you want to check how well you understand the difference between those methods take a quick RunnerIQ 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.

14 thoughts on “Taming the beast: Events, Buttons and Code snippets

  1. I have run to the end of my 90 days of support but would love to find someone that can teach me how to do these nifty things. I am definitely one of your users that is new to php but doing really powerful things with phprunner. Is there any kind of class that can be taken to teach us how to use the really great features that you have put into this program, even when we don’t know php all that well? That would be my wish.

  2. 1) great to see this kind of tutorial. I would like to see live examples using the codes suggested
    2) test was good but perhaps a little long. 10 questions max for my attention span!
    3)I would pay $25 no problem. This is a great looking template and hope phprunner6.0 will be this good looking. I do get comments that 5.3 and previous look dated which I guess is why the big overhaul in 6.0.
    I think more purchasable templates would be good but the user needs to be able to customise easily. I struggle to get calendar template to do what I want as there is much tricky code that I dont understand the implications of.

    That’s all – keep up the good work
    Gareth

  3. I think you are on the right track and I really appreciate the effort you are making. I loved the idea of allowing users to post their own tips, tricks, and know-how also. Like the previous comment, I struggled for days before I finally got the calendar program to do what I wanted, mainly with the permission levels to view different schedules. It would be nice for us to be able to share those tips if that would not violate any of your copyright notices. Maybe you could have the site set up where you could review the tips before posting them. One site I go to has a special area for code only supported mostly by end users. Your skill level is obviously way above the average user and thus, difficult to bring down to most users level. I will check out your quiz program soon. Thanks! Keep on Developing! LarryM

  4. This is it. If you want to check how well you understand the difference between those methods take a quick RunnerIQ test. This test was built by PHPRunner btw.

    Would love to see a tutorial on how the RunnerIQ test quiz was build using PHPRunner.

  5. Nice test – nice functionality – not overly fancy but yet clean and functional. Question count maybe a tad high – some questions were not relevant in this tutorial so I had a few mistakes [sigh] :-). If I had a need for such a template, I’d pay 10-25 dollars for it. I think if you keep making these tutorials (which is a good thing), then such a test to go with it is good as it helps with retention of the info. All in all, I recall my first use of phprunner – there were so many little tricks and techniques that you had to sift through the forums to find, to get advanced things done. Very capable product, hence the need for these tutorials and good documentation to get these tips/tricks in front of the users. I had found that if you get into modifying the templates, you can really unleash power and do most anything (not that that is easy – to varying degrees). That recent article about the Book idea and post by electro rick was really insightful with excellent points et al. I am looking forward to the v6 generation…

  6. This is a wonderful tutorial for the various custom actions which can be done using the application.

    RunnerIQ test is also wonderful. I would wish to purchase the same for $1.

  7. Nice tutorial. Most of this info exists elsewhere, but it’s nice to pull it together like this and point out specific things. More real examples (as mentioned by others) would be good. As a note: I am a lazy programmer (which is why I love your product – it does it for me!) so the more you can make this kind of advanced funcionality available via GUI selections in the app the better.

    Sharing tips and tricks between users is a good idea too. Also, “expert app reviewers” would be cool. Like: I create an app but want to run it by someone else and get thoughs about the approach – is it the best way to accomplish the task. Would people pay for that? Is that a good idea?… I don’t know, just having that thought now.

    Test was nice use of Runner. Maybe less quetions would be better.

    Thanks for your great product!

  8. I really like you taking an interest in helping your customers with coding snippets. I have written many, and they really help.

    I feel .. The examples need more comments to describe the coding flow.
    I like to write in “The Kings English”. I have been very successful with this technique. Would be nice if the variables were a little more descriptive and the coding, i.e. using “The King’s English” .. no so cryptic. If I were to use your code I would completely restructure it for flow and readability. (Someone besides me may have to debug it)

    I cannot say enough about PhpRunner. It got me out of a MAJOR jam. I have been a fan ever since.

    I feel that customers that renew their yearly license should be able to use these snippets w/o charge. Now … feature enhancements / skins etc. .. another story.

    Take Care,

    Peter

  9. Hello Serjey,

    Greetings ! Well Done.

    I had a query which I am waiting since several years to come. I think I had put it several times over the forum. I had compared several products with phprunner. the best example is sqlmaestro php generator. Of course every product has its pros and cons so this is not in an effort to compare both, but I would like to add a facility which will just enhance this product to new levels which cannot be imagined by anyone. The query goes below:-

    In a master detail form, I had requested that every field in the master detail form should be able to give reference of the same in a sql query. I mean that we should be able to give a simple sql in the column name to populate values based on any field (master or detail)

    like for example I have a master column customerid and when i am in detail form I want orders displayed only of the customer id selected in the master table the sql may be simple looking as below

    select orderno from ordermst where customerid = :masterform.customerid

    Now here I am in detail record here.

    Every user is not that familiar with php to write the above complicated codes you have given. Of course it is in good and intelligent effort of yours, but it does not satisfy the user needs. My head started turning after looking at that code. So request to declare a simple variable by default for every column of the table by default and allow it to be referred in any sql given for any column. If this is done I think phprunner will never look back. I wish you all the best.

    And btw, This is the only major constraint I had found in phprunner since last 2 years. I had been observing this at very close context.

  10. Many thanks Sergey for your effort to compile this tutorial.

    Further topics for new tutorials could be:
    • Handling of variables, that is are not stored in database e.g. variables for user communication, preparing questions to user as in the RunnersIQ Test and to get user’s decisions like “would you prefer to do this or that”, based on findings of DB querys and application logic.
    • Understanding events, what can be done at the various steps of the lifetime of a query, what information is available etc. I wasted a lot of time to find out that an operation is not possible eg. working at a list item.

    The RunnerIQ Test is too long, I canceled it half way.
    I would pay for the template 25 $.

    Thanks for you fabulous approach to support and customer information.

    Best Regards

    Ulrich Lüer
    UL.Consult GmbH

  11. I like the tutorial, but have a suggestion.

    Where listing the snippets in PHP, could you also put the equivalent in ASP? That would be tremendously helpful.

  12. The quiz template is a good idea. However, for it to be a complete system, there should be an admin side for creating quizes via the web and running reports.

  13. Maurice,

    Quiz template is a complete system. It allows you to create new quizzes via web, add reports and charts etc.

Leave a Reply

Your email address will not be published. Required fields are marked *