Search code examples
phpmoodlemoodle-api

Need A Value of id of url inside a box


i am a newbie having difficulty in this. i did not getting a value of ID In A box for Update Inside A Box.

update code

    <?php

require_once (__DIR__ . '/../../config.php');
require_once($CFG->dirroot.'/local/message/classes/form/edit.php');



global $DB;
$PAGE->set_url(new moodle_url('/local/message/update.php'));
$PAGE->set_context(\context_system::instance());
$PAGE->set_title('Edit');
//here display form

$mform=new edit();
$table='local_message';
$id=required_param('id', PARAM_INT);
$info=$DB->get_records($table,array('id' => $id));


if ($mform->is_cancelled()) {
    print_r("1");
    redirect($CFG->wwwroot.'/local/message/manage.php', 'You Cancelled The Form');
} else if ($fromform = $mform->get_data()) {
    print_r("2");
    $record = new stdClass();
    $record->id=$id;
    $record->messagetext = $fromform->messagetext;
    $record->messagetype = $fromform->messagetype;
    $DB->update_record($table, $record);
    redirect($CFG->wwwroot . '/local/message/manage.php', 'you created a message with a title ' . $fromform->messagetext);
}
echo $OUTPUT->header();
$mform->display();

echo $OUTPUT->footer();

Form/moodle/Code

<?php
require_once("$CFG->libdir/formslib.php");

class edit extends moodleform {
    public function definition() {
        global $CFG;
        $mform = $this->_form; // Don't forget the underscore!

        $mform->addElement('text', 'id');
        $mform->setType('id', PARAM_INT);
        $mform->addElement('text', 'messagetext', get_string('message_text', 'local_message')); // Add elements to your form
        $mform->setType('messagetext', PARAM_NOTAGS);                   //Set type of element
        $mform->setDefault('messagetext', get_string('enter_message', 'local_message'));        //Default value

        $choices = array();
        $choices['0'] = \core\output\notification::NOTIFY_WARNING;
        $choices['1'] = \core\output\notification::NOTIFY_SUCCESS;
        $choices['2'] = \core\output\notification::NOTIFY_ERROR;
        $[enter image description here][1]choices['3'] = \core\output\notification::NOTIFY_INFO;
        $mform->addElement('select', 'messagetype', get_string('message_type', 'local_message'), $choices);
        $mform->setDefault('messagetype', '3');

        $this->add_action_buttons();
    }
    //Custom validation should be added here
    function validation($data, $files) {
        return array();
    }
}

Solution

  • You need to pass the id to the form before displaying the form

    $mform->set_data($info);
    $mform->display();
    

    Also, you should use the single get_record function not the multiple get_records function

    $info = $DB->get_record($table, array('id' => $id));
    

    Also, you might want to use the hidden element for the id

    $mform->addElement('hidden', 'id');