How to appear form elements in the block.

How to appear form elements in the block.

by Rahul Rai -
Number of replies: 4
  • I am doing:- block_message_to_self_form.php

           <?php

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

                  class message_form extends moodleform {

                             function definition() {

                                   global $CFG;

                                   $mform =&$this->_form; 

                                   $mform->addElement('textarea', 'message', get_string("message_to_self", "block_message_to_self"), 'wrap="virtual" rows="5" cols="10"');

        $mform->addElement('button', 'messagesave', get_string("message_save", "block_message_to_self"));       

    } 

}

  • I want to display this form in block class file block_message_to_self.php.

require_once('block_message_to_self_form.php');

class block_message_to_self extends block_base {

     /**

     * block initializations

     */

    public function init() {

        $this->title = get_string('pluginname', 'block_message_to_self');

    }

    public function get_content() {

        global $CFG, $USER, $COURSE, $OUTPUT;

        if ($this->content !== NULL) {

            return $this->content;

        }

        if (!isloggedin()) {

            return '';

        }

        $this->content = new stdClass;

        $this->content->text = 'Hello';

        $this->content->footer = '';

        $course = $this->page->course;

        $simplehtml = new message_form();

       $this->content->text.=$simplehtml->display();  // this form is not displaying in block

        return $this->content;

    }

}

Please help me.

Average of ratings: -
In reply to Rahul Rai

Re: How to appear form elements in the block.

by Davo Smith -
Picture of Core developers Picture of Particularly helpful Moodlers Picture of Peer reviewers Picture of Plugin developers

$form->display() outputs the form contents, it does not return the contents as a string.

If you want the contents of a form as a string that you can then use elsewhere, then you need to call $form->render()


Average of ratings: Useful (2)
In reply to Davo Smith

Re: How to appear form elements in the block.

by Mehulkumar Parmar -

Hello Davo,

Rendering the form inside the block makes the block layout a bit messy. Can give me any advise on that? 

Thanks,

Mehulkumar

In reply to Rahul Rai

Re: How to appear form elements in the block.

by Darko Miletić -

And people stop doing this:

$mform =&$this->_form; 

This is PHP4 obsolete thing. This is the right way:

$mform = $this->_form;