This topic is locked

How to change Edit type of the field on the fly

5/6/2015 7:29:42 PM
PHPRunner Tips and Tricks
Sergey Kornilov admin

Imagine the situation where some field appears on Add/Edit pages as a dropdown box but sometimes it needs to appear as a regular text box. The most important thing is that this sort of behaviour needs to happen on the fly, based on some other field value.
Here is a typical Cars database where each car has Make and Model. 'Make' is setup as a dropdown box. We want model to be a list of radio-buttons when Make is 'Audi' and a simple text box when Make is 'BMW'.
This is how it looks on the Add page:


  1. While we cannot assign two different 'Edit as' types to the same field we can have two different fields and show/hide them on the fly.
    Modify SQL Query as follows adding Model field one more time with an alias:

SELECT

ID,

Make,

Model,

Model as Model2,

YearOfMake

from cars


2. Make sure that Model2 field appears on Add/Edit pages.

Change field label from 'Model2' to 'Model'. This can be done in Label Editor.
3. Setup 'Make' field as a dropdown box. Setup 'Model' field as a Lookup wizard - set of Radio-buttons. Make it dependent on 'Make' field. Setup 'Model2' as a simple text box.
4. 'Add page: Javascript OnLoad' event. In this code we show/hide Model/Model2 fields based on what was selected in Make dropdown box.

var ctrlMake = Runner.getControl(pageid, 'Make');

ctrlMake.on('change', function(e){
if (this.getValue() == 'Audi'){

$("tr[data-fieldname='Model']").show();

$("tr[data-fieldname='Model2']").hide();

}else{

$("tr[data-fieldname='Model']").hide();

$("tr[data-fieldname='Model2']").show();

}
});
$("tr[data-fieldname='Model2']").hide();


5. One more thing. Since Model2 is not a real field we need to prevent it from being saved in the database. We do that in 'Add page: BeforeAdd' event

if ($values['Make']=='BMW') {

$values['Model']=$values['Model2'];

}
unset($values['Model2']);
return true;


6. If you need to use the same functionality on the Edit page copy both events code to respective events of the Edit page.
This is it.