I'm working on a Moodle 4.x Assignment Submission plugin that requires the use of a recurring field, or set of fields, for the student to enter text (Title / URL). I have the plugin working with one field using the moodle forms, and after being informed that the repeat fields method isn't available in submission plugin contexts, I've had limited success in using a Jquery AMD module's form fields, in that they display and function in the ui but cannot access the data from the locallib php file. Can anybody point me towards a good practice for this?
The jquery is here:
define(['jquery'], function($) {
return {
init: function() {
$(document).ready(function() {
var container = $('#urlsub_container');
// Targetting the add button by its ID
$('#add_url_button').on('click', function(e) {
e.preventDefault();
addUrlTitlePair();
});
// Function to add a new URL-title pair
function addUrlTitlePair() {
var index = $('.url-title-pair').length;
console.log(index);
// URL and title inputs, and removal button
var urlInput = $('<input>').attr({
type: 'text',
name: 'urls[' + index + '][url]',
placeholder: 'URL',
class: 'url-input'
});
console.log(urlInput);
var titleInput = $('<input>').attr({
type: 'text',
name: 'urls[' + index + '][title]',
placeholder: 'Title',
class: 'title-input'
});
var removeButton = $('<button>').attr({
type: 'button',
}).text('Remove').on('click', function() {
$(this).parent().remove();
});
// Container for the pair
var pairContainer = $('<div>').addClass('url-title-pair');
pairContainer.append(urlInput, titleInput, removeButton);
container.append(pairContainer); // Append the pair to the container
}
// Initial pair
addUrlTitlePair();
// Form submission handler
$('form').on('submit', function(e) {
e.preventDefault();
var formData = $(this).serialize();
$.ajax({
type: 'POST',
url: $(this).attr('action'),
data: formData,
success: function(response) {
console.log(response);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
});
});
}
};
});
...with the locallib.php save function looking like this:
public function save(stdClass $submission, stdClass $data) {
global $USER, $DB;
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// assuming an array of URLs
$urls = parse_str($_POST['data'], $formData);
// Passing data to save function
$submission = new stdClass();
$submission->id = 1; // to replace with actual submission ID
$data = new stdClass();
$data->urls = $urls;
$urlsub = new assign_submission_urlsub();
$urlsub->save($submission, $data);
}
}
Many thanks
I've tried using Moodle's mform API, and also the AMD approach, but not data is available when submitted through the form.