Challenge is simple. Some countries have regions or counties. Others don't. Depending on selection in the first dropdown - show different values in 2nd.

In addition to that, we want to hide field if it does not contain any selectable options.

For simplicity this example will use static data.
<?php
 
// You might need to use $p=$this; if you are inserting this code into page/*.php


// In real life examples, you would probably be pulling data from the database. In this case,
// you might need to use dynamic query and adjust it with ->where() if 
// $_GET['region'] is specified.
$country_list=array('',1=>'United States',2=>'Ireland',3=>'Latvia');
$region_list=array(1=>array('State1','State2'),2=>array('County1','County2'));

$region_list=$region_list[$_GET['region']]?:array();
 
// if you are loading form data from database, then you would need to use value
 // list for loaded country, instead of array(), which is the default.

$f=$p->add('Form');

// Here we are simply adding two drop-downs. Quite straightforward.
$country=$f->addField('dropdown','country')
 ->
setValueList($country_list);
$region=$f->addField('dropdown','region')
 ->
setValueList($region_list);

// This is also quite simple. This works identical when form is being loaded initially
// and also works when filed is being reloaded.
if($region_list){
   
$region->js(true)->closest('dl')->show();
}else{
   
$region->js(true)->closest('dl')->hide();
}

// Finally - here is the magic. When field is changed, other field is reloaded.
// Imagine how many lines of code / hours of work this line just saved you!
$country->js('change',$f->js()->atk4_form('reloadField','region',
     array(
$this->api->getDestinationURL(),'region'=>$country->js()->val())));



blog comments powered by Disqus