Current Record: Dynamic_select_boxes #90

Dynamic select boxes To create two select boxes whose one is dependent (slave) of the other (master), we need to use some javascript with J...

Current Record: Dynamic_select_boxes #90

Dynamic select boxes To create two select boxes whose one is dependent (slave) of the other (master), we need to use some javascript with J...

[Permalink]

Dynamic select boxes

To create two select boxes whose one is dependent (slave) of the other (master), we need to use some javascript with Jason.

Create the valuelists.ini:


;valuelist for the slave
[slaves_list]
__sql__ = "select slave_id, slave_name, master_id from slaves"

; valuelist for the masters
[masters_list]
__sql__ = "select master_id,master_name from masters"

fields.ini:

[master]
vocabulary=masters_list

[slave]
vocabulary=slaves_list

delegate class in the table directory :

...
function block__after_new_record_form(){
echo <<<END
<script language="javascript"><!--
var slave_field= document.getElementById('slave');
var master_field = document.getElementById('master');
END;
// Let's get all the slaves available.
$app =& Dataface_Application::getInstance();
$query =& $app->getQuery();
$table =& Dataface_Table::loadTable($query['-table']);
$slaves = $table->getValuelist('slaves_list');
$slave_masters = $table->getValuelist('slaves_list__meta');
// Note that the slaves_list__meta valuelist is automatically created
// because we had three columns in the slaves valuelist.
// The first and third columns effectively create a 2nd valuelist
// named 'slaves_list__meta'

// $slaves is an array with keys slave_id and values slave_name
// slave_masters is an array with keys slave_id and values master_id

import('Services/JSON.php');
$json =& new Services_JSON(); // A JSON encoder to allow us to easily
// convert PHP arrays to javascript arrays.
echo '
var slaves_options = '.$json->encode($slaves).';
var slaves_master = '.$json->encode($slave_masters).';
';

echo <<<END
master_field.onchange = function(){
var selected_master = master_field.options[master_field.selectedIndex].value;
slave_field.options.length = 0;
var index = 0;
for ( slave_id in slaves_options){
if ( selected_master == slaves_master[slave_id] ){
slave_field.options[index++] = new Option(slaves_options[slave_id], slave_id);
}
}
};
//--></script>
END;
}

// Also place this javascript after an edit record form...
function block__after_edit_record_form(){
return $this->block__after_new_record_form();
}

The 2.0 version has a depselect module to produce cascading dynamic select boxes very simply.

blog comments powered by Disqus
Powered by Xataface
(c) 2005-2024 All rights reserved