Support for Drupal 7 is ending on 5 January 2025—it’s time to migrate to Drupal 10! Learn about the many benefits of Drupal 10 and find migration tools in our resource center.
By jsenich on
Is it possible to set multiple default values using the #default_value attribute for a checkboxes or multi-select form control? If so could somebody post an example for how to do this?
Comments
Set up an array of values for #default_value
You want to set up an array of values for the #default_value. The trick is the value of each default value is the index of the options array.
So for example if you have
if blue and green are default values you would have
and the code to produce the form field something like
It worked
It worked and saved my day . Thanks a lot .
What I did was
$existing = array(12 => 12, 23 => 23, 35 => 35);
During Edit form...
When i am editing the node content, i tried to populate a multiselect field with values from the database, and it worked for me when i specified both the #options and #default_value with the same array in my form code:
Note this would mean all the
Note this would mean all the options are on/selected by default