Positioning two $mform text fields horizontally

Positioning two $mform text fields horizontally

by Pedro Martins De Torre -
Number of replies: 2

I'm using code similar to the following to add a form to the view.php file of my module:

class mymod_form extends moodleform {
    public function definition() {
        global $CFG;
        $mform = $this->_form;

        $mform->addElement('header', 'myheader', get_string('myheader', 'mod_mymod'));

        $mform->addElement('text', 'field1', get_string('field1', 'mod_mymod'));
        $mform->setType('field1', PARAM_NOTAGS);

        $mform->addElement('text', 'field2', get_string('field2', 'mod_mymod'));
        $mform->setType('field2', PARAM_NOTAGS);

        $mform->addElement('header', 'mybody', get_string('mybody', 'mod_mymod'));

    }
}

That gives me something similar to:

I have this form


How can I position the two fields horizontally next to each other? I want something like this:

I want this


How do I achieve that using $mform?

Thanks.

Average of ratings: -
In reply to Pedro Martins De Torre

Re: Positioning two $mform text fields horizontally

by Pedro Martins De Torre -

Perhaps I could create the form elements using the html_writer class, but will that work? Moodle has $mform which is apparently much better for forms because it handles the entire preparation, submission and validation processes for the form. So does anyone have any idea how I could achieve the above layout using $mform?

Or can I achieve what I want by applying CSS to the $mform code? If so, can anybody describe how?

In reply to Pedro Martins De Torre

Re: Positioning two $mform text fields horizontally

by Mark Johnson -
Picture of Core developers Picture of Particularly helpful Moodlers Picture of Peer reviewers Picture of Plugin developers

CSS is the right answer here.  You can add it to your module's styles.css file, and use rules that just apply to that form (you can give the form an ID by passing it in the form constructor's $attributes array).

I can't tell you the exact CSS to use, but the following might be a good start:

#myformid .fitem {
width: 50%;
display: inline-block;
}
Average of ratings: Useful (1)