3 Commits

Author SHA1 Message Date
0020f35399 [FIX] survey_record_generation: questions without answer no longer empty fields
When a question was not displayed (conditional question) or skipped, its
field was still given to create() with a None value. The field was then
emptied instead of keeping its default or computed value.

Since the link to an already created record is given at creation, this
also made sale.subscription.line price_unit equal to 0 when the "free
amount" question was not displayed, instead of the product price.

Fields without value are now left out of the values, which also allows
several conditional questions to fill up the same field (e.g. one list
of amounts per periodicity).

Assisted-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 08:54:48 +00:00
bfe59096db [FIX] survey_record_generation: link to already created record at creation
A NOT required "other_record" field was always set after the loop with a
write(), even when the linked record was already created. This late write
triggers the recomputation of stored computed fields depending on the
relation, overriding the values answered by the user.

E.g. with subscription_oca, sale.subscription.line price_unit depends on
sale_subscription_id.partner_id/pricelist_id: a free amount typed in a
numerical_box question (33) was replaced by the product price (20) when
the line was linked to its subscription.

Now the relation is given to create() when the linked record already
exists, so that the user's values are protected from recomputation. The
deferred write is kept for records created later.

Assisted-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 08:54:48 +00:00
9d55588f18 [ADD] survey_dropdown_simple_choice
Some checks failed
pre-commit / pre-commit (pull_request) Failing after 1m35s
tests / test (pull_request) Successful in 1m14s
Display "Multiple choice: only one answer" (simple_choice) survey
questions as a dropdown list instead of radio buttons, per question.

The native radios are kept (hidden by CSS) and still carry the answer:
the dropdown only clicks them, so validation, conditional questions,
"Other" comment, auto-submit and AJAX submit are handled natively.
In review / print mode, only the selected and correct answers are
displayed. Native rendering is kept when suggested answers contain
images.

Assisted-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 18:30:55 +02:00
8 changed files with 233 additions and 199 deletions

View File

@@ -18,7 +18,6 @@ fonctionnent comme d'habitude.
- Si une réponse proposée contient une image, la question reste affichée
en boutons radio.
- À l'impression et dans la revue des réponses, la question est affichée
en boutons radio.
- Le raccourci clavier A-Z (mise en page « Une question par page ») ne
fonctionne pas sur ces questions.
- À l'impression et dans la revue des réponses (« Consulter vos réponses »),
seule la réponse choisie est affichée, ainsi que la bonne réponse pour
un sondage noté.

View File

@@ -2,74 +2,71 @@
import SurveyFormWidget from "@survey/js/survey_form";
// Keep native survey answer pipeline intact (validation, conditional
// questions, AJAX submit): the dropdown change is mapped onto the hidden
// mirror radios that survey_form.js knows about.
// The dropdown only drives the native radios (hidden by CSS): choosing an
// option clicks the matching radio, so validation, conditional questions,
// "Other" comment, auto-submit and AJAX submit are all handled natively.
SurveyFormWidget.include({
events: Object.assign({}, SurveyFormWidget.prototype.events, {
'change select.o_survey_dropdown_choice': '_onDropdownChoiceChange',
'change [data-survey-dropdown="edit"] .o_survey_form_choice_item': '_onDropdownRadioChange',
}),
/**
* Arrow left/right on a focused dropdown must not navigate between pages.
* A focused dropdown is handled like a text input: its keys (letters,
* arrows, enter) must not trigger the survey shortcuts.
*
* @override
*/
_onKeyDown: function (event) {
if (event.target.matches?.('select.o_survey_dropdown_choice')
&& ['ArrowLeft', 'ArrowRight'].includes(event.key)) {
&& !((event.ctrlKey || event.metaKey) && event.key === 'Enter')) {
return;
}
return this._super.apply(this, arguments);
},
/**
* Correct answers are colored on the mirror radios: show them instead of
* the dropdown so the participant sees the correction.
* Correct answers are colored on the native radios: show them (only the
* selected and correct ones, see "review" mode) instead of the dropdown.
*
* @override
*/
_showQuestionAnswer: function (correctAnswers, questionId) {
this._super.apply(this, arguments);
const questionWrapper = this.el.querySelector(`.js_question-wrapper[id="${questionId}"]`);
const select = questionWrapper && questionWrapper.querySelector('select.o_survey_dropdown_choice');
if (select) {
select.disabled = true;
questionWrapper.querySelector('.o_survey_dropdown_select').classList.add('d-none');
questionWrapper.querySelector('.o_survey_dropdown_mirror').classList.remove('d-none');
const group = this.el.querySelector(
`.js_question-wrapper[id="${questionId}"] [data-survey-dropdown="edit"]`
);
if (group) {
group.dataset.surveyDropdown = 'review';
group.querySelector('.o_survey_dropdown_select').classList.add('d-none');
}
},
/**
* Click the radio of the chosen option, or the checked one to untick it
* when the empty option is chosen (native untick behavior).
*/
_onDropdownChoiceChange: function (ev) {
const select = ev.currentTarget;
const group = select.closest('.o_survey_form_choice');
if (!group || this.readonly) {
if (this.readonly) {
return;
}
const previous = group.querySelector('input.o_survey_form_choice_item:checked');
group.querySelectorAll('input.o_survey_form_choice_item').forEach((input) => {
input.checked = false;
input.classList.remove('o_survey_form_choice_item_selected');
});
// Labels' 'o_survey_selected' class is left untouched: the native
// handler relies on it to find the previous answer (conditional
// questions) and moves it itself.
const value = select.value;
const target = value && group.querySelector(
`input.o_survey_form_choice_item[value="${value}"]`
);
if (target) {
target.checked = true;
target.classList.add('o_survey_form_choice_item_selected');
}
// Native change listener (jQuery delegated) handles: comment area
// visibility, conditional questions, and auto-submit when
// users_can_go_back on page_per_question layouts. On reset to the
// empty option, it is fired on the previous (now unchecked) radio,
// like the native untick of a radio.
const changed = target || previous;
if (changed) {
changed.dispatchEvent(new Event('change', { bubbles: true }));
const select = ev.currentTarget;
const group = select.closest('.o_survey_form_choice');
const radio = select.value
? group.querySelector(`.o_survey_form_choice_item[value="${select.value}"]`)
: group.querySelector('.o_survey_form_choice_item:checked');
if (radio && !(select.value && radio.checked)) {
radio.click();
}
},
/**
* Keep the dropdown in sync when a radio changes by other means
* (A-Z keyboard shortcuts).
*/
_onDropdownRadioChange: function (ev) {
const group = ev.currentTarget.closest('.o_survey_form_choice');
const checked = group.querySelector('.o_survey_form_choice_item:checked');
group.querySelector('select.o_survey_dropdown_choice').value = checked ? checked.value : '';
},
});

View File

@@ -7,3 +7,14 @@
}
}
}
// Native radios still carry the answer but are replaced by the dropdown
.o_survey_form_choice[data-survey-dropdown="edit"] > div:has(> .o_survey_choice_btn) {
display: none;
}
// Review / print / correction: only show the selected and correct answers
.o_survey_form_choice[data-survey-dropdown="review"]
> div:has(> .o_survey_choice_btn):not(:has(> .o_survey_selected)):not(:has(> .bg-success)) {
display: none;
}

View File

@@ -1,97 +1,33 @@
<?xml version="1.0" encoding="utf-8"?>
<odoo>
<!-- Redirect the render of simple_choice questions to the dropdown
widget when the display_dropdown flag is set. The native radio
rendering is kept when a suggestion carries an image, and in
readonly mode (print / review) so that corrections are displayed. -->
<template id="question_container" inherit_id="survey.question_container" name="Survey question container: dropdown dispatch">
<xpath expr="//t[@t-if=&quot;question.question_type == 'simple_choice'&quot;]" position="replace">
<t t-if="question.question_type == 'simple_choice'">
<t t-if="question.display_dropdown and not answers_contain_image and not survey_form_readonly"
t-call="survey_dropdown_simple_choice.question_simple_choice_dropdown"/>
<t t-else="" t-call="survey.question_simple_choice"/>
</t>
<!-- Add a dropdown on top of the native radios when the display_dropdown
flag is set. The radios are kept (hidden by CSS) and still carry the
answer: the dropdown only clicks them (see survey_form_dropdown.js).
In readonly mode (review / print), the radios are shown but only the
selected and correct answers are kept visible (data-survey-dropdown
"review"). The native rendering is kept when a suggestion carries an
image. -->
<template id="question_simple_choice" inherit_id="survey.question_simple_choice" name="Question: simple choice (dropdown)">
<xpath expr="//t[@t-set='comment_line']" position="after">
<t t-set="dropdown_enabled" t-value="question.display_dropdown and not any(a.value_image for a in question.suggested_answer_ids)"/>
<t t-set="use_dropdown" t-value="dropdown_enabled and not survey_form_readonly"/>
</xpath>
</template>
<!-- Dropdown rendering for simple_choice questions.
The native JS (survey_form.js) still reads its answers from the
checked radios inside the .o_survey_form_choice wrapper:
the select and a hidden mirror group of radios coexist, a JS patch
keeps them in sync, so conditional questions, score display,
auto-submit and the 'other' comment keep working. -->
<template id="question_simple_choice_dropdown" name="Question: simple choice (dropdown)">
<t t-set="answer_line" t-value="answer_lines.filtered(lambda line: line.suggested_answer_id)"/>
<t t-set="comment_line" t-value="answer_lines.filtered(lambda line: line.value_char_box)"/>
<t t-set="other_selected" t-value="comment_line and not answer_line"/>
<div class="o_survey_answer_wrapper o_survey_form_choice"
t-att-data-name="question.id"
t-att-data-is-skipped-question="is_skipped_question or None"
data-question-type="simple_choice_radio">
<div class="row g-2 o_survey_dropdown_select">
<div class="col-sm-12">
<select class="form-select o_survey_dropdown_choice"
t-att-name="question.id"
t-att-aria-label="question.title">
<option value="" t-att-selected="'selected' if not answer_line and not other_selected else None"/>
<t t-foreach="question.suggested_answer_ids" t-as="label">
<t t-set="answer_selected" t-value="answer_line and answer_line.suggested_answer_id.id == label.id"/>
<option t-att-value="label.id" t-att-selected="'selected' if answer_selected else None"
<xpath expr="//div[hasclass('o_survey_form_choice')]" position="attributes">
<attribute name="t-att-data-survey-dropdown">('review' if survey_form_readonly else 'edit') if dropdown_enabled else None</attribute>
</xpath>
<xpath expr="//t[@t-set='has_correct_answer']" position="after">
<div t-if="use_dropdown" class="col-sm-12 o_survey_dropdown_select">
<select class="form-select o_survey_dropdown_choice" t-att-aria-label="question.title">
<option value=""/>
<option t-foreach="question.suggested_answer_ids" t-as="label"
t-att-value="label.id"
t-att-selected="'selected' if answer_line.suggested_answer_id == label else None"
t-out="label.value"/>
</t>
<t t-if="question.comments_allowed and question.comment_count_as_answer">
<option value="-1" class="o_survey_dropdown_other_option"
t-att-selected="'selected' if other_selected else None"
<option t-if="question.comments_allowed and question.comment_count_as_answer" value="-1"
t-att-selected="'selected' if comment_line else None"
t-out="question.comments_message or default_comments_message"/>
</t>
</select>
</div>
</div>
<!-- Hidden mirror radios: no 'name' attribute on purpose, they must
not flow into the submitted form data (the select carries the
answer for validation); only their checked state is read by
_prepareSubmitChoices. They are shown in place of the select
when correct answers are displayed after the page. -->
<div class="row g-2 d-none o_survey_dropdown_mirror">
<t t-foreach="question.suggested_answer_ids" t-as="label">
<t t-set="answer_selected" t-value="answer_line and answer_line.suggested_answer_id.id == label.id"/>
<div class="col-sm-12">
<label t-attf-class="o_survey_choice_btn py-1 px-3 w-100 h-100 rounded #{'o_survey_selected' if answer_selected else ''}">
<i class="fa fa-check-circle float-end mt-1 ms-1 position-relative"/>
<i class="fa fa-circle-thin float-end mt-1 ms-1 position-relative"/>
<input type="radio" t-att-value="label.id"
t-att-id="str(question.id) + '_' + str(label.id)"
t-attf-class="o_survey_form_choice_item invisible position-absolute #{'o_survey_form_choice_item_selected' if answer_selected else ''}"
t-att-checked="'checked' if answer_selected else None"/>
<span class="ms-2 text-break" t-field="label.value"/>
</label>
</div>
</t>
<t t-if="question.comments_allowed and question.comment_count_as_answer">
<div class="col-sm-12">
<label t-attf-class="o_survey_choice_btn py-1 px-3 h-100 w-100 rounded #{'o_survey_selected' if other_selected else ''}">
<i class="fa fa-check-circle float-end mt-1 ms-1 position-relative"/>
<i class="fa fa-circle-thin float-end mt-1 ms-1 position-relative"/>
<input type="radio" value="-1"
t-attf-class="o_survey_form_choice_item o_survey_js_form_other_comment invisible position-absolute #{'o_survey_form_choice_item_selected' if other_selected else ''}"
t-att-checked="'checked' if other_selected else None"/>
<span class="ms-2" t-out="question.comments_message or default_comments_message"/>
</label>
</div>
</t>
</div>
<!-- Comment areas: exact copy of the native structure so that
_applyCommentAreaVisibility and _prepareSubmitComment work. -->
<t t-if="question.comments_allowed and question.comment_count_as_answer">
<div t-attf-class="o_survey_comment_container mt-3 py-0 px-1 h-auto #{'d-none' if not comment_line else ''}">
<textarea type="text" class="form-control o_survey_question_text_box bg-transparent rounded-0 p-0"
t-att-disabled="None if comment_line else 'disabled'"><t t-esc="comment_line.value_char_box if comment_line else ''"/></textarea>
</div>
</t>
<div t-if="question.comments_allowed and not question.comment_count_as_answer" class="mb-2 o_survey_comment_container mt-3">
<textarea type="text" class="col form-control o_survey_comment o_survey_question_text_box bg-transparent rounded-0 p-0"
t-att-placeholder="question.comments_message or default_comments_message if not survey_form_readonly else ''"><t t-esc="comment_line.value_char_box if comment_line else ''"/></textarea>
</div>
</div>
</xpath>
</template>
</odoo>

View File

@@ -1,2 +1,3 @@
from . import test_survey_record_creation
from . import test_end_migration_18_0_1_0_1
from . import test_computed_fields

View File

@@ -0,0 +1,33 @@
from odoo import api, fields, models
class SurveyRecordGenerationFakeParent(models.Model):
_name = "survey.record.generation.fake.parent"
_description = "Fake parent record (tests only)"
name = fields.Char()
price = fields.Float()
class SurveyRecordGenerationFakeLine(models.Model):
"""Line whose price is computed from its parent, like the price of a
subscription line (subscription_oca).
Pattern reproduced: the survey creates a parent, then a line linked to
it, with a price answered by the user. The user's price must be kept,
the parent's price only applies when the user gave none.
"""
_name = "survey.record.generation.fake.line"
_description = "Fake line record (tests only)"
parent_id = fields.Many2one("survey.record.generation.fake.parent")
price_unit = fields.Float(
compute="_compute_price_unit", store=True, readonly=False
)
@api.depends("parent_id.price")
def _compute_price_unit(self):
for line in self:
if line.parent_id:
line.price_unit = line.parent_id.price

View File

@@ -0,0 +1,120 @@
from odoo_test_helper import FakeModelLoader
from odoo.addons.survey.tests.common import SurveyCase
class TestComputedFields(SurveyCase):
"""User's answers must not be overridden by computed fields depending on
a link to another generated record.
Use case: a membership form creating a subscription and a subscription
line whose price is typed by the participant (free amount), while the
line price is computed from the subscription.
"""
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.loader = FakeModelLoader(cls.env, cls.__module__)
cls.loader.backup_registry()
from .fake_models import (
SurveyRecordGenerationFakeLine,
SurveyRecordGenerationFakeParent,
)
cls.loader.update_registry(
(SurveyRecordGenerationFakeParent, SurveyRecordGenerationFakeLine)
)
@classmethod
def tearDownClass(cls):
cls.loader.restore_registry()
super().tearDownClass()
def setUp(self):
super().setUp()
self.survey = self.env["survey.survey"].create({"title": "Join us"})
self.question_amount = self._add_question(
page=None,
name="Free amount",
qtype="numerical_box",
survey_id=self.survey.id,
sequence=1,
)
# Parent, with a default price of 20
self.parent_creation = self._add_record_creation(
"Parent", "survey.record.generation.fake.parent", 0
)
self._add_field_value(
self.parent_creation, "name", value_origin="fixed",
fixed_value_char="Membership",
)
self._add_field_value(
self.parent_creation, "price", value_origin="fixed",
fixed_value_float=20.0,
)
# Line, linked to the parent, with the price answered by the user
self.line_creation = self._add_record_creation(
"Line", "survey.record.generation.fake.line", 1
)
self._add_field_value(
self.line_creation, "parent_id", value_origin="other_record",
other_created_record_id=self.parent_creation.id,
)
self._add_field_value(
self.line_creation, "price_unit", value_origin="question",
question_id=self.question_amount.id,
)
def _add_record_creation(self, name, model, sequence):
return self.env["survey.record.creation"].create(
{
"name": name,
"survey_id": self.survey.id,
"model_id": self.env["ir.model"]._get(model).id,
"sequence": sequence,
}
)
def _add_field_value(self, record_creation, field_name, **vals):
field = self.env["ir.model.fields"]._get(
record_creation.model_id.model, field_name
)
return self.env["survey.record.creation.field.values"].create(
{
"survey_record_creation_id": record_creation.id,
"survey_id": self.survey.id,
"model_id": record_creation.model_id.id,
"field_id": field.id,
**vals,
}
)
def _submit(self, amount=None):
answer = self._add_answer(
survey=self.survey, partner=False, email="jean@test.fr"
)
if amount is not None:
self._add_answer_line(
question=self.question_amount, answer=answer, answer_value=amount
)
answer._mark_done()
return self.env["survey.record.generation.fake.line"].search(
[("parent_id.name", "=", "Membership")]
)
def test_answer_is_not_overridden_by_computed_field(self):
line = self._submit(amount=33)
self.assertEqual(len(line), 1)
self.assertEqual(line.price_unit, 33.0)
def test_computed_field_applies_when_question_is_not_displayed(self):
# E.g. the "free amount" question is only displayed when the user
# chose "Other amount": otherwise the line keeps the computed price.
line = self._submit()
self.assertEqual(len(line), 1)
self.assertEqual(line.price_unit, 20.0)

View File

@@ -1,5 +1,3 @@
from unittest.mock import patch
from psycopg2 import IntegrityError
from odoo.addons.survey.tests.common import SurveyCase
@@ -1075,67 +1073,6 @@ class TestSurveyRecordCreation(SurveyCase):
self.assertNotEqual(self.answer.partner_id, jeanne)
self.assertEqual(self.answer.email, jean.email)
def test_link_to_already_created_record_is_set_at_creation(self):
# When a NOT required "other_record" field points to a record that
# is already created (lower sequence), the link must be given in
# create() and not written afterwards: a later write would trigger
# computed fields depending on this link (e.g. price_unit of a
# sale.subscription.line depends on its subscription) and override
# the values answered by the user.
self.survey_record_creation.sequence = 0
child_creation = self.env["survey.record.creation"].create(
{
"name": "Child contact",
"survey_id": self.survey.id,
"model_id": self.res_partner_model.id,
"sequence": 1,
}
)
self.env["survey.record.creation.field.values"].create(
{
"survey_record_creation_id": child_creation.id,
"survey_id": self.survey.id,
"model_id": self.res_partner_model.id,
"field_id": self.name_field.id,
"value_origin": "fixed",
"fixed_value_char": "Child",
}
)
parent_field = self.env["ir.model.fields"]._get("res.partner", "parent_id")
self.env["survey.record.creation.field.values"].create(
{
"survey_record_creation_id": child_creation.id,
"survey_id": self.survey.id,
"model_id": self.res_partner_model.id,
"field_id": parent_field.id,
"value_origin": "other_record",
"other_created_record_id": self.survey_record_creation.id,
}
)
self.answer = self._add_answer(
survey=self.survey, partner=False, email="jean@test.fr"
)
self._add_answer_line(
question=self.question_name, answer=self.answer, answer_value="Jean"
)
partner_class = type(self.env["res.partner"])
original_write = partner_class.write
written_fields = []
def spy_write(records, vals):
written_fields.extend(vals)
return original_write(records, vals)
with patch.object(partner_class, "write", spy_write):
self.answer._mark_done()
jean = self.env["res.partner"].search([("name", "=", "Jean")])
child = self.env["res.partner"].search([("name", "=", "Child")])
self.assertEqual(child.parent_id, jean)
self.assertNotIn("parent_id", written_fields)
def test_question_not_displayed_does_not_override_default_value(self):
# When a question is not displayed to the user (e.g. a conditional
# question), the field must keep its default (or computed) value