I had to set up a fairly complex workflow where a content Field on the backend of a content type was a list of checkboxes that were dynamically populated from an associated node's custom Field content. In order to do this I created a field of list(text) checkbox type and wrote a module using hook_form_alter to target it and dynamically populate it with the correct options. And I eventually got it working EXCEPT that the checkboxes don't stay checked. The form does save options, but then whenever the node is edited, it doesn't remember what was previously saved. I also need to set a default value for the field. I've tried several approaches, but I'm no PHP master, and definitely no Drupal 7 PHP master, and nothing is working so far.

In psuedoish-code here's what I want to do:

<?php
//if the field array already has selected values saved
if ($form['myfield']['und'][#value]) {
//the default values it shows should be those previously selected values
$form['myfield']['und']['#default_value'] = $node->myfield['und'][#value];
//if the field array doesn't have any values
} else {
//the default array values should be all the values (the whole array I used to build the options)
$form['myfield']['und']['#default_value'] = $array_i_used_to_populate_options;
}
?>

But this doesn't work. I don't think #value works this way, or in this context.

#value_callback seems interesting, but I couldn't find enough documentation to really understand what it's all about.

I seem to also be running into trouble because I want to set the values of an array to the values of another array.

I tried using the CCK PHP Field addons for Drupal 7, but I couldn't get the code that was working in my module to work in a function - or I didn't call the function correctly from the PHP input areas on my Field, not sure which. In fact, I couldn't get even a basic test function to return values when called from the allowed values function field, but this could be user error on my part.

Anyone ever worked on custom checkboxes, or have any ideas? Any suggestions would be greatly appreciated - thanks!

Comments

axxint’s picture

So I finally figured out a way to do it, but there may be a much easier (and more correct) way! Since I was working with arrays, I set up some loops to go and assign default values on a per-item basis.

<?php
//set default value to previously saved or first 5 items from options list
   
$countsaved = count($this_node->myfield['und'])-1;//minus one because arrays start with 0 instead of 1
   
$optionsreindexed = array_values($form['myfield']['und']['#options']);//because this array had a non-numeric key
   
if ($this_node->myfield['und'][0]['value']){
        for (
$p=0;$p<=$countsaved;$p++){
           
$form['myfield']['und']['#default_value'][$p] = $this_node->myfield['und'][$p]['value'];
        }
    } else {
        for (
$p=0;$p<=5;$p++){
           
$form['myfield']['und']['#default_value'][$p] = $optionsreindexed[$p];
        }
    }
?>