Dynamic form with Settings API?

I have a form in the admin-backend of a selfmade plugin, written the old fashioned style. So I’m not using the Settings API. Instead I’ve written a form, added nonces, wrote an endpoint checking the nonces and so on.

Now I want to utilize the Settings API of WordPress to provide a modern way of managing my plugin.
But I’m stuck with handling the API according my needs for adding additional input fields dynamically (accomplished via JavaScript).

Here’s my use case (simplified):
I’m managing the box offices of movies. So I have a bunch of movies, I read from a custom table and create an output via foreach:

// $movies contains the result of my MySQL query
foreach ($movies as $mkey => $mvalue) {
$moviefacts = new NT_Movie($mvalue[‘tmdb_id’]);
echo ‘<tr>
<td style=”width: 60px”><img src=”‘.$moviefacts->get_the_poster_url(‘xs’) . ‘” width=”50″ /></td>
<td><input type=”hidden” name=”id[]” value=”‘ . $mvalue[‘id’] . ‘” />
<input type=”text” name=”moviename[]” value=”‘ . $moviefacts->get_the_title() . ‘” /></td>
<td><input type=”text” name=”real_visitors[]” value=”‘ . $moviefacts->get_the_real_visitors().'” /></td>
<td><input type=”text” name=”tmdb_id[]” value=”‘ . $mvalue[‘tmdb_id’].'” /></td>
</tr>’;
}

For adding new movies to the list, I’ve created a JavaScript, which adds new rows to the form:

function AddFormField() {
jQuery(‘#NTT_form’).prepend(‘<tr>
<td>&nbsp;</td>
<td><input type=”hidden” name=”id[]” value=”” />
<input type=”text” name=”moviename[]” /></td>
<td><input type=”hidden” name=”real_visitors[]” value=”DUMMY_NEW_VALUE” /></td>
<td><input type=”text” name=”tmdb_id[]” /></td>
<td><input type=”text” name=”vote_id[]” /></td>
</tr>’);
return false;
}

With this approach, I can iterate through the fields when processing the form, regardless of the amount of datasets: New datasets are recognized by the value “DUMMY_NEW_VALUE” and existing datasets get updated, if something has changed in them.

Do you have any approach, how to transform this setting to the Settings API of WordPress?

Thanks in advance.

Read more here:: Dynamic form with Settings API?

Leave a Reply

Your email address will not be published. Required fields are marked *