Everything looks OK but when I submit my form, field doesn't get updated.

When the page reloads, the checkbox is still showing old state.

<label>Some Option</label>
<label><input type="checkbox" name="fields[membersAvailableForCollaborativeProjects]" value="1" {% if user.membersAvailableForCollaborativeProjects %}checked="checked"{% endif %} /> Yes

membersAvailableForCollaborativeProjects is a Lightswitch field type. Treating it the same as a Checkbox.

Any ideas?

My form action is users/saveUser as I'm trying to update a users profile via the front-end.

up vote 12 down vote accepted

After taking a look at this it would seem like the lightswitch is always expecting a value to determine the whether the state should be on or off. When you don’t check the input and submit the form, the field doesn’t get sent to the controller, the value isn’t replaced (as there technically is no value) and nothing updates.

You can work around this by providing a hidden input above the checkbox with a constant value of 0, so when the form submits and there is no check in the checkbox a 0 will get sent and will override the 1 if already set. If you check the input then the hidden field will be overwritten when the form submits and will update the field value of 0 to a 1 and will light the switch.

I hope that makes sense.

Here is the complete form I have used with success:

<form method="post" accept-charset="UTF-8">
 {{ getCsrfInput() }}
 <input type="hidden" name="action" value="users/saveUser">
 <input type="hidden" name="redirect" value="/">
 <input type="hidden" name="userId" value="{{ currentUser.id }}">

 <label>Some Option</label>
 <label>
  <input type="hidden" name="fields[membersAvailableForCollaborativeProjects]" value="0">
  <input type="checkbox" name="fields[membersAvailableForCollaborativeProjects]" value="1" {% if user.membersAvailableForCollaborativeProjects %}checked{% endif %} /> Yes
 </label>
 <input type="submit" value="Save user">
</form>
  • Saves my day! Had the same problem. Hidden field works perfect now. – Johannes Lamers Mar 24 '15 at 10:51

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.