Is there a straightforward way to load the instance of a block from some arbitrary location?
e.g.
$block = load_a_block( $instanceid );
echo $block->config->somedata;
That's basically it, I want to access the block's config data but I don't want to pass the data around in an HTTP link.
I looked in lib/blocklib.php, but it doesn't seem to be wired up that way.
Do you know the name of the block? If so, use:
$instance = get_record('block_instance', 'id', $instanceid);
$blockname = 'myblock';
$block = block_instance($blockname, $instance);
If you only have the instance id, you'll have to get the name from the block record:
$select = 'SELECT bi.*, b.name ';
$from = 'FROM '.$CFG->prefix.'block_instance bi ';
$join = 'INNER JOIN '.$CFG->prefix.'block b ON b.id = bi.blockid ';
$where = 'WHERE bi.id = '.$instanceid;
$sql = $select . $from . $join . $where;
$instance = get_record_sql($sql);
$blockname = 'myblock';
$block = block_instance($blockname, $instance);
mike
$instance = get_record('block_instance', 'id', $instanceid);
$blockname = 'myblock';
$block = block_instance($blockname, $instance);
If you only have the instance id, you'll have to get the name from the block record:
$select = 'SELECT bi.*, b.name ';
$from = 'FROM '.$CFG->prefix.'block_instance bi ';
$join = 'INNER JOIN '.$CFG->prefix.'block b ON b.id = bi.blockid ';
$where = 'WHERE bi.id = '.$instanceid;
$sql = $select . $from . $join . $where;
$instance = get_record_sql($sql);
$blockname = 'myblock';
$block = block_instance($blockname, $instance);
mike
Well, in newer code (Moodle 2.x) you should instead use:
$instance = $DB->get_record('block_instances', array('id' => $id)); $blockname = 'myblock'; $block = block_instance($blockname, $instance);
Remeber however, that block retrieved this way will have empty (newly created) $block->page and $block->page->course.
If you need to access anything in the context of page and course where this block is located, you need to set things up yourself:
if (!$block) { print_error('invalidblockinstance', 'error', $id); } $context = context::instance_by_id($instance->parentcontextid); if (!is_a($context, context_course)) { print_error('invalidcontext', 'error'); } $course = get_course($context->instanceid); $returnurl = new moodle_url('/course/view.php', array('id' => $course->id)); // Override page settings, because $block->page is empty. $block->page->set_course($course); $block->page->set_url($returnurl);