Checkbox in user profile, updated with sprig
See original GitHub issueHi,
I have a user profile where a logged in user can toggle a checkbox if he/she wants to attend a tournament or not. Instead of clicking the checkbox and hitting a separate save button I’d like to transfer the status of the checkbox to the backend immediately with the help of the sprig plugin.
Unfortunately, the checkbox doesn’t react as planned. Clicking it the first time saves the right state in the user profile, but the checkbox flips back to the state before. A second click on that checkbox does reflect the right state.
In other words: If the user checkes an unchecked box, in the backend the state changes from no to yes as planned, but the checkbox in the frontend “reloads” quickly and then stays unchecked. A second klick makes it stay checked (and the box in the backend still shows “yes” what is correct). See the short video:
This is my code:
{# userprofile.twig #}
{% requireLogin %}
{{ sprig('_components/tournament') }}
{{ sprig.script }}
{# tournament.twig #}
<h1>Tournament 1</h1>
{% set user = user ?? currentUser %}
{{ hiddenInput('userId', user.id) }}
{# Include a hidden input first so Craft knows to update
the existing value, if no checkboxes are checked. #}
{{ hiddenInput('fields[tournament1]', '') }}
{% set field = craft.app.fields.getFieldByHandle('tournament1') %}
{% for option in field.options %}
{% set checked = user is defined
? user.tournament1.contains(option.value)
: option.default %}
<label>
<input sprig s-method="post" s-action="users/save-user"
type="checkbox"
name="fields[tournament1][]"
value="{{ option.value }}"
{% if checked %}checked{% endif %}>
{{ option.label }}
</label>
{% endfor %}
The checkbox-code was built with the help of the Craft docs
– Sprig: 1.3.0 – Craft CMS Pro: 3.5.17.1 – PHP 7.4.13 – local dev environment with Valet, Mac OS 10.15.7
Issue Analytics
- State:
- Created 3 years ago
- Comments:6
Top GitHub Comments
So after some investigating, it seems that the
currentUser
variable is being defined before the user is saved with the submitted values. Fetching the current user explicitly appears to fix it:Thanks! 🥳