1

I have a frontend form and would like to save multiple related entries by checking 1 checkbox. I have this working to save 1 related entry:

<input type="checkbox" id="user-type-select-{{ userType|kebab }}" name="fields[hasUserTypes][]" value="{{ userType.id }}" />

But how do I pass multiple userType.id values in there? I tried various syntaxes such as comma seperated, enclosed in brackets like an array or a comma seperated string with the |hash filter as seen here but nothing worked.

What is the correct sytax?

1

You can't solve that with one input alone but you can make use of hidden fields (like craft does) Your solution would be 1 visible dummy checkbox and multiple hidden "real" inputs.. So your visible dummy checkbox triggers a javascript event, that sets the values of your hidden. Here is the syntax

<input type="checkbox" id="user-type-select-{{ userType|kebab }}" />

You have to add a javascript/jquery onchange event that sets the values of your hidden fields

<input type="hidden" id="someId1" name="fields[hasUserTypes][]" value="someIntegerValue1" /> 
<input type="hidden" id="someId2" name="fields[hasUserTypes][]" value="someIntegerValue2" /> 
<input type="hidden" id="someId3" name="fields[hasUserTypes][]" value="someIntegerValue3" /> 

in your php part your $_POST variable would be looking like

array(
    ....
    'fields' => array(
        'hasUserTypes' => array(
            someIntegerValue1, someIntegerValue2, someIntegerValue3
        ),             
    ),
    ....
);

If you have (let us say) 3 visible checkboxes and each of it contains 2-3 relation presets you would like to store you have to change the values of your 2-3 hidden fields depending on what the user has selected. If you right click on craft cp pages and inspect the code you'll see craft does exactly the same, for every relation you select one <input type="hidden"> is created with the value of the id from the related entry

  • To bad this isn't as easy as I thought. But your solutions should work. I could even generate the hidden fields in JavaScript I suppose and add it to the HTML depending on the amount of values I'd like to save. – Tom De Smet Nov 10 '17 at 9:13
  • well - actually it is easy. You only need a few lines and if you don`t refuse to try angular you can do it within 3-4 lines – Robin Schambach Nov 10 '17 at 9:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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