wortle
wortle

Reputation: 41

How to create a dynamic form in wordpress?

On a WordPress website I would like to have a form where users can submit data about courses they are offering, but some offer more and different courses than others. Therefor, I would like to give them an option to add another field to the form, so it would look a bit like the following. The basic form would look like this:

Course name (text field) - language (dropdown) - date (date picker or text field)

But if a user offers 2 courses, they would be able to press a button like 'add row' and it would give them the same row of three fields again. Looking like

Course name 1 - language - date [add row]
Course name 2 - language - date [add row]

But also, if a user offers 1 course, but in 2 languages and on 3 dates, they should be able to enter that, looking like

Course 1 - language 1 [add language]- date 1[add date][add row]
           language 2 [add language]- date 2[add date][add row]
                                      date 3[add date][add row]
Course 2 - language 1 [add language]- date 1[add date][add row]
           language 2 [add language]- date 2[add date][add row]
           language 3 [add language]

And so on and so forth...

Would it be possible to do this with dynamic fields and how? Is there a WordPress plugin that already offers this (preferred)?

Upvotes: 0

Views: 6509

Answers (2)

Nick Surmanidze
Nick Surmanidze

Reputation: 1689

I believe you need to do that on the front end.

For that you would need some jquery.

Group the fields about the course into a row. For example:

$('#add-row').click(function(){

  $('.rows').append("<div class='course-row'><input type='text' name='course-name'><input type='text' name='language'><button class='remove'>remove</button></div>");
  
});

$(document).on('click', '.remove', function(){

  $(this).closest('.course-row').remove();
  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='rows'>
  
  <div class='course-row'>
    <input type='text' name='course-name'>
    <input type='text' name='language'>
    <button class='remove'>remove</button>
  </div>
  
</div>

<button id='add-row'>Add row</button>

So instead of the second input you can use select and wrap all of that into a form. Then once the form is submitted just fetch and parse incoming data from repeated fields as an array.

Upvotes: 2

ataylor
ataylor

Reputation: 101

You should look at Advanced Custom Fields. It is a WordPress plugin to assist in form creation and has a repeater field addon, which will help you.

The repeater fields allows you to group inputs together and let's the user repeat those as necessary. Check out their doc on nested repeaters to achieve what you want.

Upvotes: 0

Related Questions