Hide and show blocks

Hide and show blocks

by Fred Riley -
Number of replies: 2

Hi all

A simple question: can a block hide itself using code, and if so how?

The context is that I'm writing a block to add/hide content sections, and only want it to be visible in edit mode. So something like:

if ($PAGE->user_is_editing()) {
  // show me
}

else {

  // hide me

}

I've had a hunt in this forum, Moodle Docs and a Famous Internet Search Engine [TM], and can find lots on hiding blocks in the UI but nothing on code to do so. I suspect that it's not possible, in which case no big deal, I'll just display the block empty in non-editing mode.

Fred

Average of ratings: -
In reply to Fred Riley

Re: Hide and show blocks

by Tim Hunt -
Picture of Core developers Picture of Documentation writers Picture of Particularly helpful Moodlers Picture of Peer reviewers Picture of Plugin developers

Aside: Within a block you should refer to $this->page, not the global variable $PAGE. (They are probably the same thing, but it is better to avoid global variables.)

You can do this sort of thing in blocks. If you return an empty $this->content object from get_content, then your block will not appear. https://github.com/moodle/moodle/blob/40f0ad21a3fbfaf6e04cc1d53778cf2ca710b8bd/blocks/comments/block_comments.php#L48 looks like a good example.

In reply to Tim Hunt

Re: Hide and show blocks

by Fred Riley -

Ah, yes, sorry, I'd forgotten that an empty content var hides the block. D'OH!!