If within code processing AJAX request I set default value of checkboxes this default value is ignored by forms system and all checkboxes are instead created as unchecked.

I tracked down the issue to its origin and provide patch fixing this issue.

CommentFileSizeAuthor
#75 1100170-nr-bot.txt1.32 KBneeds-review-queue-bot
#63 interdiff_62-63.txt627 bytesAnandhi Karnan
#63 checkbox_default_value_1100170-63.patch2.73 KBAnandhi Karnan
#62 1100170-62.patch1.9 KBEricB1021
#61 1100170-61.patch801 bytesshashank5563
#60 1100170-60.patch0 bytesshashank5563
#59 1100170-59.patch1.94 KBshashank5563
#58 1100170-58.patch1.17 KBshashank5563
#56 1100170-56.patch1.93 KBimot3k
#51 1100170-51.patch1.88 KBAnas_maw
#46 1100170-46.patch1.93 KBkpv
#46 interdiff.txt851 byteskpv
#43 1100170-43.patch1.2 KBunrealauk
#40 1100170-40.patch886 bytesmahtab_alam
#39 1100170-39.patch1.58 KBmahtab_alam
#36 form_process_checkbox_default_value_ajax_fix-1100170-36.patch739 bytesZemelia
#35 1100170-35.patch892 bytesnachosalvador
#28 form_process_checkboxes_default_value_ajax_fix-1100170-5.patch663 bytesvarghese
#17 1100170-17.patch1.02 KBjibran
#10 form_process_checkboxes_default_value_ajax_fix-1100170-10.patch704 bytestimos
#5 form_process_checkboxes_default_value_ajax_fix-1100170-5.patch663 bytesAnonymous (not verified)
form_process_checkboxes_default_value_ajax_fix.patch605 bytesAnonymous (not verified)

Issue fork drupal-1100170

Command icon Show commands

Start within a Git clone of the project using the version control instructions.

Or, if you do not have SSH keys set up on git.drupalcode.org:

Support from Acquia helps fund testing for Drupal Acquia logo

Comments

Status: Needs review » Needs work

The last submitted patch, form_process_checkboxes_default_value_ajax_fix.patch, failed testing.

Anonymous’s picture

Status: Needs work » Needs review
Anonymous’s picture

Version: 7.0 » 7.2
Priority: Normal » Major

This bug still exists in Drupal 7.2. The patch I originally provided applies perfectly to Drupal 7.2 and fixes this issue. I raise priority to major for this bugfix to be included in the upcoming Drupal 7.3. Please review this bug and accompanying fix. Thank you!

sun’s picture

Version: 7.2 » 8.x-dev
Priority: Major » Normal
Status: Needs review » Needs work
Issue tags: +Needs backport to D7

Could you create a unified patch using git, please? See http://drupal.org/patch/create for more information.

Anonymous’s picture

Version: 8.x-dev » 7.x-dev
Priority: Normal » Major
Status: Needs work » Needs review
FileSize
663 bytes

Here is unified patch using git for 7.x-dev branch. I raise priority to major in the hope that this bugfix will be included in the upcoming Drupal 7.9. Please review it. Thank you!

marcingy’s picture

Version: 7.x-dev » 8.x-dev

Needs to be fixed in d8 first and then backported

marcingy’s picture

Priority: Major » Normal

And back to normal as well

timos’s picture

It has not been backported on D7 yet.
I tested (manually) the patch on a 7.9 and it seems work.

timos’s picture

Hello

After more use of my patched installation, i found at least one bug caused by the #5 patch, but, actually it seems come from node_reference module and not really from the patch.

If you use the references module and you create a new node reference field like that :

  • create a new field, node reference type and an autocomplete text field as widget and submit
  • on the field-settings edit form choose only on content type as referenceable and submit

So you get the global edit field form, where the 'content type referenceable' settings is displayed again, and there, all the content types are checked and not only this you selected in the first step.

If you uncheck all the content type but one and you submit. The setting is saved and if you test the field, only the content type checked can be referenced. But if you edit again, both field-settings form or global field edit form, all your content types are checked again.

This behaviour is due to the #5 patch (if the patch is not applied, the behaviour is ok)

So i digged down in the references module (because, it's the only form where i found this bug) and i think the problem comes from the way how the #default_value node reference field is built.
It is done in the node_reference.module line 82 :

<?php
$settings = $field['settings'];

  $form = array();
  $form['referenceable_types'] = array(
    '#type' => 'checkboxes',
    '#title' => t('Content types that can be referenced'),
    '#multiple' => TRUE,
    '#default_value' => $settings['referenceable_types'],
    '#options' => array_map('check_plain', node_type_get_names()),
  );
?>

I didn't manage to find where the $field['settings']['referenceable_types'] array is populated (I suppose it's populated by the field API) but the result can be see with the debug function :

<?php
'#default_value' => 
        array (
          'atelier' => 'atelier',
          'article' => 0,
          'date' => 0,
          'page' => 0,
          'recette' => 0,
        ),
?>

The handler of default value for checkboxes is defined by the patch like that :

<?php
'#default_value' => isset($value[$key]) || (is_array($element['#default_value']) && in_array($key, $element['#default_value'])) ? $key : NULL,
?>

So in the situation i describe above the condition match and the default value for the checkbox element is set to a not NULL value and the render for checkbox element is checked.

So, the problem comes from the node references module and i posted an issue for that (http://drupal.org/node/1365412) , but maybe we have to anticipate this kind of error with just a little change :

<?php
'#default_value' => isset($value[$key]) || (is_array($element['#default_value']) && in_array($key, $element['#default_value']) && $element['#default_value'][$key] != 0) ? $key : NULL,
?>

where the condition doesn't match if the $key is in the array but $element['#default_value'][$key] equals to 0, and so the checkbox element is not checked when it is rendered.

I'll try to make a new patch with this little add.

Cheers

timos’s picture

here the patch with the little change mentioned above
thanks for review
cheers

Status: Needs review » Needs work

The last submitted patch, form_process_checkboxes_default_value_ajax_fix-1100170-10.patch, failed testing.

Damien Tournoud’s picture

Issue tags: +Needs tests

This might be a legit bug, but without a test to reproduce it, this patch cannot be accepted.

The solution looks like a hack at first sight, so the real issue might be elsewhere, but anyway, we cannot proceed without a test to reproduce it.

timos’s picture

Status: Needs work » Needs review

Hi

Sorry i just see this issue is for D8 (actually i saw it, but as the #5 patch is for D7, i go on in this way).

As, this issue is still in the D7 version, how can i do to test this patch for D7 ? do i have to create a new issue for D7 or just change the version for tag for this issue to submit the patch, then port again the issue to D8 ?

timos’s picture

hefox’s picture

Status: Needs review » Needs work

In an ajax callback, the current values of element, i.e. the $form_state['input'], overrides the default value, so if the element already exists in the form and has input, so changing #default_value doesn't matter. See _form_builder_handle_input_element

So is this a bug or by design?

joachim’s picture

> So is this a bug or by design?

If it's by design it really needs documenting, as it's a real headdesker.

jibran’s picture

FileSize
1.02 KB

Patch from #10 re-rolled against d8.

jibran’s picture

Status: Needs work » Needs review
joachim’s picture

Thinking more about this I reckon it's by design.

If you display a form element to the user, and they enter data, and then it's AJAXed in some way, the user is going to expect that their input is not lost.

Obviously, there will be particular cases where you *do* want that to happen -- perhaps the AJAX callback is meant to process and modify the user's input, or there's just some sort of good reason to replace it.

But the basic behaviour seems right to me. Though it would be good to get input on this from the FormAPI expects.

Also, either way, it needs documenting.

Status: Needs review » Needs work

The last submitted patch, 1100170-17.patch, failed testing.

Chris Gillis’s picture

How can it be by design when the checkboxes element (or I assume this might be all multiple-value elements) is handled differently from other elements? I have a simple form that looks like:

  $form['role'] = array(
      '#type' => 'select',
      '#title' => t('Role'),
      '#options' => $roles_options,
      '#default_value' => $role_selected,
  );
  $form['dates'] = array(
      '#type' => 'checkboxes',
      '#title' => t('Dates'),
      '#options' => $dates_options,
      '#default_value' => $dates_selected,
  );

When the form is rebuit with AJAX, the role field shows the computed value, but not the dates field? Inconsistency like that is clearly a bug to be fixed...

Chris Gillis’s picture

A simple workaround is to unset the input in form state. So in my example I would simply add:

unset($form_state['input']['dates']);
joachim’s picture

> How can it be by design when the checkboxes element (or I assume this might be all multiple-value elements) is handled differently from other elements

Hmm, that's a very good point!

juanjo_vlc’s picture

Issue summary: View changes

On my case, I made an ajax callback which adds options to a checkboxes list, I want those new options be checked by default. I understand the design behavior, but I think it's necessary some way to archieve the other case.

marcingy’s picture

@juanjo_dv you should be able to achieve that with https://api.drupal.org/api/drupal/developer%21topics%21forms_api_referen...

varghese’s picture

function fees_form_alter(&$form, &$form_state, $form_id) {
switch ($form_id) {
case 'fees_node_form':
$form['title'] = NULL;
$class_name[0] = 'Select';
$class_name= $class_name+get_class_list();
$form['field_common_class_id']['und']['#options'] = $class_name;
break;
case 'fees_paid_node_form':
$form['title'] = NULL;
$query = 'select n.nid,f.field_fees_name_value,c.field_common_class_id_value from node n
JOIN field_data_field_fees_name f ON n.nid = f.entity_id
JOIN field_data_field_common_class_id c ON n.nid = c.entity_id
JOIN field_data_field_status s ON n.nid = s.entity_id and s.field_status_value = 1';
$result = db_query($query);
$fees_list[] = 'Select';
foreach ($result as $record) {
$fees_list[$record->nid] = $record->field_fees_name_value;
}
$form['field_common_fees_id']['und']['#options'] = $fees_list;

$form['field_common_fees_id']['und']['#ajax'] = array('event' => 'change', 'callback' => 'ajax_student_list_fees_callback','wrapper' => 'student-list');
$form['field_common_student_user_id']['und']['#prefix'] = '

';
$form['field_common_student_user_id']['und']['#suffix'] = '

';
$form['field_common_student_user_id']['und']['#type'] = 'checkboxes';
// $form['field_common_student_user_id']['und']['#default_value'] = $selected;

$selected = isset($form_state['values']['field_common_fees_id']) ? $form_state['values']['field_common_fees_id']['und'][0]['value'] : 0;

if(isset($selected) && $selected > 0) {
$options = _ajax_student_list_fees_callback($selected);
$form['field_common_student_user_id']['und']['#default_value'] = array(115,121);
$form['field_common_student_user_id']['und']['#options'] = $options;
}
break;
}
return $form;
}

function ajax_student_list_fees_callback($form, $form_state){
return render($form['field_common_student_user_id']['und']);
}

But fees is not checked. May I know what I did wrong here?

Anonymous’s picture

It's not ideal, but #22 was the only solution which worked for me in the form callback on core 7.38.

unset($form_state['input']['form_element']);
$form['form_element'] = array(
    '#type' => 'checkboxes',
    ...
);
varghese’s picture

lazzyvn’s picture

for type checkbox there is shame issue
i fix by

foreach($form as $key_field=>&$info)
if(!empty($info) && $info[LANGUAGE_NONE]['#type']=='checkbox'){
$info[LANGUAGE_NONE]['#checked']=(bool) $info[LANGUAGE_NONE]['#value'];
}

Version: 8.0.x-dev » 8.1.x-dev

Drupal 8.0.6 was released on April 6 and is the final bugfix release for the Drupal 8.0.x series. Drupal 8.0.x will not receive any further development aside from security fixes. Drupal 8.1.0-rc1 is now available and sites should prepare to update to 8.1.0.

Bug reports should be targeted against the 8.1.x-dev branch from now on, and new development or disruptive changes should be targeted against the 8.2.x-dev branch. For more information see the Drupal 8 minor version schedule and the Allowed changes during the Drupal 8 release cycle.

Version: 8.1.x-dev » 8.2.x-dev

Drupal 8.1.9 was released on September 7 and is the final bugfix release for the Drupal 8.1.x series. Drupal 8.1.x will not receive any further development aside from security fixes. Drupal 8.2.0-rc1 is now available and sites should prepare to upgrade to 8.2.0.

Bug reports should be targeted against the 8.2.x-dev branch from now on, and new development or disruptive changes should be targeted against the 8.3.x-dev branch. For more information see the Drupal 8 minor version schedule and the Allowed changes during the Drupal 8 release cycle.

Version: 8.2.x-dev » 8.3.x-dev

Drupal 8.2.6 was released on February 1, 2017 and is the final full bugfix release for the Drupal 8.2.x series. Drupal 8.2.x will not receive any further development aside from critical and security fixes. Sites should prepare to update to 8.3.0 on April 5, 2017. (Drupal 8.3.0-alpha1 is available for testing.)

Bug reports should be targeted against the 8.3.x-dev branch from now on, and new development or disruptive changes should be targeted against the 8.4.x-dev branch. For more information see the Drupal 8 minor version schedule and the Allowed changes during the Drupal 8 release cycle.

Version: 8.3.x-dev » 8.4.x-dev

Drupal 8.3.6 was released on August 2, 2017 and is the final full bugfix release for the Drupal 8.3.x series. Drupal 8.3.x will not receive any further development aside from critical and security fixes. Sites should prepare to update to 8.4.0 on October 4, 2017. (Drupal 8.4.0-alpha1 is available for testing.)

Bug reports should be targeted against the 8.4.x-dev branch from now on, and new development or disruptive changes should be targeted against the 8.5.x-dev branch. For more information see the Drupal 8 minor version schedule and the Allowed changes during the Drupal 8 release cycle.

Version: 8.4.x-dev » 8.5.x-dev

Drupal 8.4.4 was released on January 3, 2018 and is the final full bugfix release for the Drupal 8.4.x series. Drupal 8.4.x will not receive any further development aside from critical and security fixes. Sites should prepare to update to 8.5.0 on March 7, 2018. (Drupal 8.5.0-alpha1 is available for testing.)

Bug reports should be targeted against the 8.5.x-dev branch from now on, and new development or disruptive changes should be targeted against the 8.6.x-dev branch. For more information see the Drupal 8 minor version schedule and the Allowed changes during the Drupal 8 release cycle.

nachosalvador’s picture

Status: Needs work » Needs review
FileSize
892 bytes

Developing a custom form with D8.5 I've experienced same problems to set #default_value after ajax callback. Just rerolled #28 to D8.5 and fortunately works fine.

Zemelia’s picture

Same issue with "checkbox"(Checkbox.php) form element
Patch attached.

Status: Needs review » Needs work
Zemelia’s picture

Sorry, previous patch is wrong.

mahtab_alam’s picture

mahtab_alam’s picture

rodrigoaguilera’s picture

From what I can check the patch from #35 and #40 are the same. Please don't upload duplicate patches.

I feel we should focus on the "checkboxes" element instead of "checkbox" and keep the issue within the title scope.

unrealauk’s picture

I found one bug. When I try to update user entity via admin page I can't remove user roles.

unrealauk’s picture

Status: Needs work » Needs review
FileSize
1.2 KB

I'll try to fix it by my self, please review my patch.

Version: 8.5.x-dev » 8.6.x-dev

Drupal 8.5.6 was released on August 1, 2018 and is the final bugfix release for the Drupal 8.5.x series. Drupal 8.5.x will not receive any further development aside from security fixes. Sites should prepare to update to 8.6.0 on September 5, 2018. (Drupal 8.6.0-rc1 is available for testing.)

Bug reports should be targeted against the 8.6.x-dev branch from now on, and new development or disruptive changes should be targeted against the 8.7.x-dev branch. For more information see the Drupal 8 minor version schedule and the Allowed changes during the Drupal 8 release cycle.

itamair’s picture

I have got checkboxes into cells of a table $element that is added (via Ajax) into a buildOptionsForm (form settings) of a @ViewsStyle plugin
So my use case regards checkboxes elements added via ajax into a form that has already been added by a parent ajax process.

Both #43 and #40 don't work for me, and the checkbox that should load with a #default_value => TRUE are instead alla unchecked.
Either I am unable to unset the $form_state input as there is no way to do that in D8 (afaik), as $form_state->input property is protected.

So any luck for me with any of the solutions here proposed ... (will keep following this).

kpv’s picture

In Checkbox::valueCallback(), $input is checked for FALSE but not NULL. Now this one seems to work, though $input shouldn't be set to NULL and still needs to be fixed.

kpv’s picture

This one seems to be a won't fix issue.
There is no practical way (at least in some cases) to distinguish new (dynamically added) checkboxes (which need to be set to their default values) from empty ones (which need to be left empty) after submit. It happens because browsers do not submit anything for empty checkboxes. All such checkboxes are treated as unchecked. FormBuilder::handleInputElement() tries to resolve it:

      // For browser-submitted forms, the submitted values do not contain
      // values for certain elements (empty multiple select, unchecked
      // checkbox). During initial form processing, we add explicit NULL
      // values for such elements in FormState::$input. When rebuilding the
      // form, we can distinguish elements having NULL input from elements
      // that were not part of the initially submitted form and can therefore
      // use default values for the latter, if required. Programmatically
      // submitted forms can submit explicit NULL values when calling
      // self::submitForm() so we do not modify FormState::$input for them.

Though it doesn't work at least when checkboxes are added in a #process callback of a form and new checkboxes get added also before the rebuild.

junaidpv’s picture

Just perplexed with this issue then found this thread.

Thanks for some of above comments mentioning that it happens because checkboxes field having user input.

Following strategy helped me to solve it.

$input = $form_state->getUserInput();
unset($input['breakpoints']);
$form_state->setUserInput($input);

Here "breakpoints" is my checkboxes field getting dynamically changed. So, just clear user input against that field while you handle it in Ajax update.

Version: 8.6.x-dev » 8.8.x-dev

Drupal 8.6.x will not receive any further development aside from security fixes. Bug reports should be targeted against the 8.8.x-dev branch from now on, and new development or disruptive changes should be targeted against the 8.9.x-dev branch. For more information see the Drupal 8 and 9 minor version schedule and the Allowed changes during the Drupal 8 and 9 release cycles.

Fernly’s picture

Status: Needs review » Needs work

I tried out patch 46. It works for ajax loaded form parts. However, a side effect is that all normal checkboxes such as boolean fields in nodes are impossible to tick off (and save that way). After ticking off a checkbox and saving a node, the checkbox (and field value) is still 'on'.

The patch basically breaks all non-ajax loaded checkboxes in Drupal.

Anas_maw’s picture

Status: Needs work » Needs review
FileSize
1.88 KB

This patch should solve the issue now, please review

Anas_maw’s picture

Status: Needs review » Needs work

My latest patch didn't solve the issue, I ended up using the workaround in #48

Version: 8.8.x-dev » 8.9.x-dev

Drupal 8.8.7 was released on June 3, 2020 and is the final full bugfix release for the Drupal 8.8.x series. Drupal 8.8.x will not receive any further development aside from security fixes. Sites should prepare to update to Drupal 8.9.0 or Drupal 9.0.0 for ongoing support.

Bug reports should be targeted against the 8.9.x-dev branch from now on, and new development or disruptive changes should be targeted against the 9.1.x-dev branch. For more information see the Drupal 8 and 9 minor version schedule and the Allowed changes during the Drupal 8 and 9 release cycles.

payel_g’s picture

I have tried #48. It successfully unset and update the form_state value of the field. In my case it is radio button. But I can't show the default_value as checked after ajax callback. Any suggestions.

Ericmaster’s picture

Just tried patch 46 as I was having issues with an altered BEF form. It did partially work for me, but I had to add a condition in my form to pull the right default value on ajax call. Hopefully no side effects on other forms?

imot3k’s picture

Attached patch should fix the issue mentioned in #50.

shashank5563’s picture

@Anas_maw,

When I have applied #51 patch on my website. It is working fine with ajax base checkbox functionality. But, when I try to unpublish any content that content does not unpublish due to the code in the patch.

I have installed a new drupal setup and apply the patch then I found the checkbox does not mark uncheck.
You can try yourself with drupal fresh installation.

Thanks

shashank5563’s picture

This patch is working fine in both the cases. Please review
1. If the user uses an ajax loaded form, in this case, it is working fine.
2. Also, If the user uses a boolean field like a normal checkbox. even then it is working fine.

shashank5563’s picture

The attached patch fixes the issue mentioned in #58.

shashank5563’s picture

FileSize
0 bytes

I have checked and found core this code ( if ($input === FALSE || is_null($input)) {) in Checkbox.php.
So we can apply another patch for this condition.

Please Reveiw.

shashank5563’s picture

FileSize
801 bytes

Hey, Can someone delete the 1100170-60.patch. Because, it is uploaded mistakenly.

This patch fixes the #51 patch issue.

EricB1021’s picture

Fixing the last few patches to include both checkboxes.php and checkbox.php.

Anandhi Karnan’s picture

Here is the patch which fixes the failed test cases of patch #62. Please review.

Status: Needs review » Needs work

The last submitted patch, 63: checkbox_default_value_1100170-63.patch, failed testing. View results

Anandhi Karnan’s picture

Status: Needs work » Needs review

Version: 8.9.x-dev » 9.2.x-dev

Drupal 8 is end-of-life as of November 17, 2021. There will not be further changes made to Drupal 8. Bugfixes are now made to the 9.3.x and higher branches only. For more information see the Drupal core minor version schedule and the Allowed changes during the Drupal core release cycle.

Version: 9.2.x-dev » 9.3.x-dev
bkline’s picture

I feel we should focus on the "checkboxes" element instead of "checkbox" and keep the issue within the title scope.

So if I open a separate ticket reporting that it's not just the #default_value property which is affected but dynamic changes to the #description property are also ignored, I won't get told my new bug report is a duplicate of this one?

(Oh, and happy 11th anniversary for this ticket. 🎉)

phoang made their first commit to this issue’s fork.

Janec made their first commit to this issue’s fork.

Version: 9.3.x-dev » 9.4.x-dev

Drupal 9.3.15 was released on June 1st, 2022 and is the final full bugfix release for the Drupal 9.3.x series. Drupal 9.3.x will not receive any further development aside from security fixes. Drupal 9 bug reports should be targeted for the 9.4.x-dev branch from now on, and new development or disruptive changes should be targeted for the 9.5.x-dev branch. For more information see the Drupal core minor version schedule and the Allowed changes during the Drupal core release cycle.

Version: 9.4.x-dev » 9.5.x-dev

Drupal 9.4.9 was released on December 7, 2022 and is the final full bugfix release for the Drupal 9.4.x series. Drupal 9.4.x will not receive any further development aside from security fixes. Drupal 9 bug reports should be targeted for the 9.5.x-dev branch from now on, and new development or disruptive changes should be targeted for the 10.1.x-dev branch. For more information see the Drupal core minor version schedule and the Allowed changes during the Drupal core release cycle.

Dinh Bao Tran’s picture

Just a heads up, the current approach (like in #63 and #71) can causes issues with core checkbox inputs (e.g The chechboxes used in Manage form display's widget settings), making them unable to save.

needs-review-queue-bot’s picture

Status: Needs review » Needs work
FileSize
1.32 KB

The Needs Review Queue Bot tested this issue. It either no longer applies to Drupal core, or fails the Drupal core commit checks. Therefore, this issue status is now "Needs work".

Apart from a re-roll or rebase, this issue may need more work to address feedback in the issue or MR comments. To progress an issue, incorporate this feedback as part of the process of updating the issue. This helps other contributors to know what is outstanding.

Consult the Drupal Contributor Guide to find step-by-step guides for working with issues.

Version: 9.5.x-dev » 11.x-dev

Drupal core is moving towards using a “main” branch. As an interim step, a new 11.x branch has been opened, as Drupal.org infrastructure cannot currently fully support a branch named main. New developments and disruptive changes should now be targeted for the 11.x branch. For more information, see the Drupal core minor version schedule and the Allowed changes during the Drupal core release cycle.