The idea is to show user a picture of selected item making selection easier.
Lets assume you build a car selection form for car rental agency. To implement this functionality in your project you need to tables. The main table (Rentals) and a lookup table (Cars).
1. Set up one of fields in Rentals table as a Lookup Wizard pointing it to Cars table. In our example this field name will be 'Make'.
2. Add the following code to 'Add page: Before Process' event of Rentals table:
$lookupValue = postvalue("value");
if (!empty($lookupValue))
{
global $dal;
$tbl1 = $dal->Table("Cars");
$rs = $tbl1->Query(AddTableWrappers("Make")."=".db_prepare_string($lookupValue),"");
$data = db_fetch_array($rs);
if ($data)
{
$picData = json_decode($data["Image"], true);
$result["src"] = $picData[0]["name"];
$result["success"] = true;
echo json_encode($result);
}
exit();
}
In this event we perform a SQL query retrieving Image field from Cars table based on selected Make field value. Since images are stored in JSON format we need to decode JSON and send the URL of selected image to the output.
3. Add the following code to Rentals table 'Javascript onload event':
$("[id^=value_Make]").on("change", function(){
var $field=$("#lookup_image");
$field.hide();
$.ajax({
type: 'POST',
dataType: 'json',
data: {value: this.value},
success: function(data){
if (data.success) {
$field.attr("src", data.src);
//$field.attr("style", "max-width:500px;");
//uncomment previous line to set up max width of the image
$field.show();
}
}
});
}).change();
In this event we make an AJAX call to the same page we are on (rentals_add.php) passing the value of selected Make. This code is fired when selects a new item from Make dropdown box.
4. Insert 'PHP code snippet' into Rentals table Add page right after Make field.
Use the following code there:
echo "<br><img style='display:none' id='lookup_image' border='0'>";
This code creates an empty placeholder for the image underneath the Make dropdown box.
Post a Comment