with CFv5 I have created a dynamic dropdown pair (Category and Subcategory) following this FAQ. The dropdowns and ajax work fine.
Than I create a copy of the form to be called by the edit action from CCv5 as explained in this FAQ.
All the fields values are correctly grabbed from the DB, also the first dropdown is well sourced from the DB, while the second dropdown it just selects the first subcategory at the top of the list.
First I tried to simply set the selected value with javascript:
var string = <?php echo json_encode($form->data['Category']['id']); ?>;
var element = document.getElementById('category_id');
element.value = string;
Than I have read this post and tried Bob's solution "setting a JavaScript variable in the On Load event, then re-creating the second drop-down and setting the value will work"
window.onload = function(){
var string = <?php echo json_encode($form->data['Category']['id']); ?>; //Get the subcategory id
var element = document.getElementById('fin-category_id'); // Div that contains the dropdown
var child = document.getElementById('category_id'); // This is the dropdown
var oldChild = element.removeChild(child); // Remove the dropdodwn and store in oldChild to be reused later
element.appendChild(oldChild); // Re-create the dropdown
child.value = string; // Set selected value
}
I tried also to modify the ajax form event as suggested in this post:
<?php
$options = array();
if ( !$form->data['Data'] || count($form->data['Data']) < 1 ) {
// no result was found
$options[] = 'Select a category';
} else {
foreach ( $form->data['Data'] as $d ) {
$selected = '';
if ( isset($form->data['Category']['id']) && $form->data['Category']['id'] == $d->id ) {
$selected = "selected='selected'";
}
$options[] = "<option value='{$d->id}' $selected >{$d->naam}</option>";
}
}
echo json_encode($options);
?>
Any idea?