Posted by & filed under Code Tips.

For a Moodle plugin I’m writing I needed a way to check if a String exists. Normally, if a string doesn’t exist then Moodle just outputs [[missing_string]] (replace missing_string with whatever you’re calling the string) and moves on. But, in developer or debug mode it also displays a stack trace.

What I needed was a way to check if a string was set, and if not display a different string which I knew was set. This is what I came up with.

function get_string_check($identifier) {
	if (!get_string_manager()->string_exists($identifier, 'plugin_name')) {
		return get_string('a_known_string', 'plugin_name');
	}
	return get_string($identifier, 'plugin_name'); 
}

The reason I needed this was that I was building strings based on error constants. So there might be a string err_1, err_2, err_3, etc. But I needed a way to not display an error if I requested err_99 without there actually being that string.

The only catch is that the you must have $string['a_known_string'], or whatever you want to call it, in the language file for your plugin. For me, it just says Unexpected Error.

Leave a Reply

Your email address will not be published. Required fields are marked *