CodeIgniter 4 using Request object in view

It can be useful to use the request object in a view to retrieve input, this was easy with CodeIgniter 3 but with CodeIgniter 4 the documentation doesn’t cover this.

Add this to the top of your view

$request = \Config\Services::request();

Then you can use the request methods like this

<input type="hidden" id="score" name="score" value="<?=$request->getVar('score')?>">

CodeIgniter 4 tips

To prevent the debug toolbar from appearing for a certain controller method when in development mode, for example if you are generating a CSV file with code, edit app/Config/Filters.php and add the following

public function __construct()
  // hide debug toolbar when generating a CSV file
  if (strpos($_SERVER['REQUEST_URI'], 'export_csv')) unset($this->globals['after'][0]);

It isn’t obvious from the CodeIgniter 4 documentation how to prevent the debug toolbar from being added to the bottom of text output with a ResourceController.

Either output an array which changes the content type to application/json,

edit app/Config/Filters.php

public $globals = [
        'before' => [
            // 'honeypot',
            // 'csrf',
        'after' => [
            // 'toolbar',
            'toolbar' => ['except' => 'feedback/*'],
            // 'honeypot',

Or use header X-Requested-With set to XMLHttpRequest in a REST client like Postman.

WordPress add inline JavaScript

This is the WordPress way to add inline JavaScript if you have no script dependencies:

wp_register_script( 'dummy-handle', '' );
wp_enqueue_script( 'dummy-handle' );
wp_add_inline_script( 'dummy-handle', 'var my_variable = true;', 'before' );