Showing posts with label form. Show all posts
Showing posts with label form. Show all posts

Wednesday, 22 February 2017

Moodle: moodle_form inside module: Edit or new?

Hello,

Sometimes inside a custom Moodle module we need to know if we are editing or creating a new module (activity or resource) instance... Here the solution:

function definition() {
        global $CFG, $DB;
        $mform =& $this->_form;

        if (is_numeric($this->_instance) && $this->_instance && $mymodule = $DB->get_record("mymodule", array("id"=>$this->_instance))) {
            $mform->addElement('header', 'general', 'Editing');
        } else {
            $mform->addElement('header', 'general', 'Creating');
        }

...

Best regards,
Iban Cardona.

Wednesday, 4 November 2015

Moodle: Avoid alert message when form changed and exit page

Hello,

Sometimes in a moodleform you want to move to another page by javascript and a message appears saying "Are you sure...?"

The solution:

In your javascript code, use before call window.location:

window.onbeforeunload = null; 

Best regards!

UPDATE 09/3/2015
P.D: Another option is editing the form and in the definition function add:

public function definition() {
        $mform =& $this->_form;
        $mform->disable_form_change_checker();

Thursday, 15 May 2014

jQuery: Send form by ajax

Hello,

Sometimes we want to send form data but we don't want to reload page. In this case best option is send data by ajax and jQuery. In this example we used version 1.10.2 of jQuery.

HTML code:

<form id="FORMID" accept-charset="UTF-8" action="action.php" method="POST"> <input type="text" name="username" id="username" placeholder="Write username"> </form>;

Javascript code:

$('#FORMID').on('submit', function(e)  {
$.post(
$(this).prop('action'),
{
"username": $(this).find('input[name=username]').val()
},
function(data) {
alert(data.result);
},
'json'
); return false;
});


php (action.php) code:

<?php
$username = $_POST['username'];
$ret = array();
$ret['result'] = 'OK';
return json_encode($ret);

Best regards!