I'm trying to create a form whose structure depends on parameters in the URL. If no parameters are specified in the URL, an error message should be displayed. Based on the id, perform a database query and populate the form data.
Example URL: http://127.0.0.1/local/group/signin.php?groupid=14
Unfortunately, when I submit the form by clicking the action button, my form fails to validate. It jumps to http://127.0.0.1/local/group/signin.php and displays the error message "Group not found" because there are no parameters in the URL.
What am I doing wrong here?
signinform.php:
class signinform extends moodleform { public function definition() { global $DB; global $USER; $mform = $this->_form; $urlid = $this->_customdata['id']; // Get the passed group ID $message = 'Group not found'; if(is_null($urlid)){ $mform->addElement('html', ''.\core\notification::error($message).'
'); } else{ // Build forms, execute SQL queries, etc. $this->add_action_buttons(true, 'Submit'); } } function validation($data, $files) { return array(); } }
Login.php:
$PAGE->set_url(new moodle_url('/local/schedule/signin.php?')); $PAGE->set_context(\context_system::instance()); $PAGE->set_pagelayout('base'); $PAGE->set_title("Register"); $PAGE->set_heading("Register a group"); global $DB; global $USER; $urlid = $_GET["id"]; $to_form = array('id' => $urlid); // Pass the group ID to the form $mform = new signinform(null, $to_form); $homeurl = new moodle_url('/'); if ($mform->is_cancelled()) { redirect($homeurl, 'Cancelled.'); // Only for testing, never enter here } else if ($fromform = $mform->get_data()) { redirect($homeurl, 'Verification in progress'); // Only for testing, never enter here } echo $OUTPUT->header(); $mform->display(); echo $OUTPUT->footer();
You need to add a hidden field to the form that contains the 'id' that must be passed to the page, otherwise the id will no longer be present in the parameters of the page when the form is submitted.
For example (in definition())
Additionally, in Moodle you should not access $_GET directly - use the wrapper functions required_param() or optional_param() because they:
Therefore, your access to $_GET['id'] should be replaced with: