LoginSignup
2
2

More than 5 years have passed since last update.

Moodle Formのeditor上でファイルをアップロードして保存する方法

Last updated at Posted at 2018-03-24

editorのハマりポイント

mformのeditor上でD&D等で画像をアップロードする場合、何も設定せずにmformを定義すると画像アップロードが出来ない。

今回やりたいこと

2018-03-25_0142.png (41.6 kB)

対応方法の概要

editor上でアップロードされた画像をMoodle File API経由でファイルを保存(draftからの昇格)し、pluginfile.phpのURL(draftfile.phpから呼び出さないようにする)に書き換える。

このため、formクラスをコールした後にファイルを受け取りFile APIに投げ込む処理を追加する。

対応

form定義(edit_hoge_form.php)

edit_hoge_form.php

public function get_options() {
        return [
            'trusttext' => true,
            'context' => $this->_customdata["context"]
        ];
}

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

    // 途中省略

    $mform->addElement('editor', 'intro_editor', '問題文', ['rows' => 5], $this->get_options());
    $mform->setType('intro_editor', PARAM_RAW);
}

この段階で、editorに画像アップロード自体出来るようになるが、draft扱いで保存されており正式にFile APIで保存されていない。このため、File APIを使ってきちんと保存させる必要がある。

書き込み処理の追加

まず、書き込み対象のDBレコードを取得する。

$data = $DB->get_record('hoge', ['id' => 1]);

次に、Prepare処理を行う。先程取得した$datafile_prepare_standard_editor関数の第一引数にする。

edit.php
$mform = new edit_hoge_form();

$mform->set_data(
    file_prepare_standard_editor(
        $data,
        'intro',
        $mform->get_options(),
        $context,
        'mod_hoge',
        'fileareaname'
    )
);

if ($mform->is_cancelled()) {
    redirect(new \moodle_url('view.php', ['id' => $cm->id]), "キャンセルしました。", 3);
} else if ($data = $mform->get_data()) {
    $data_intro = file_postupdate_standard_editor(
        $data,
        'intro',
        $mform->get_options(),
        $context,
        'mod_hoge', // コンポーネント(プラグイン名)
        'fileareaname', // filearea(任意の値)
        $itemid // itemid(任意の値)
    );

この段階で、指定したファイルエリアとitemidでファイルが保存される。pluginfile.phpでのURLに置換済みの物は

    $question->intro = $data_intro->intro;

で取得出来る。この値をDBレコードに保存するなどする。

結果

editorでアップロードした画像をFile APIで保存し、表示出来るようになった。

2018-03-25_0207.png (31.1 kB)

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2