Welcome Guest, Not a member yet? Register   Sign In
Variable dedclared in controller available in view
#1

(This post was last modified: 10-15-2021, 10:03 PM by CodingInCodeigniter. Edit Reason: Typo )

In my project i have my website settings saved in a DB table. I need to use these settings throughout the website.
Previously in Ci3 i would do the following in the beginning of my controller
Code:
<?php
class Access extends CI_Controller {
  var $settings = '';
  var $this_file = 'Admin Access Controller';

function __construct()
{
parent::__construct();
$this->load->model('Setting_model');  
$this->settings = $this->Setting_model->get_settings();
}

$this->settings would then be available to me in the controller as well as the views.

Im trying to replicate this is Ci4 but im struggling to get it to work.

Ive tried this:


Code:
<?php

namespace App\Controllers\Admin;

use App\Controllers\BaseController;
use App\Models\SettingModel;
use App\Models\GeneralModel;
use App\Models\Admin\AccessModel;
class Access extends BaseController
{
 
    public $site_settings = array(); // I need this variable available to me throughout the application
    public function __construct()
    {
      $this->Setting_model = new SettingModel();
      $this->Access_model = new AccessModel();
      $this->site_settings = $this->Setting_model->get_settings();

When i use it in my view like this:
Code:
<title>Administration for <?php echo $this->site_settings['site_name_title']?></title>
I get the following error"
Undefined property: CodeIgniter\View\View::$site_settings

Can you please tell me what im doing wrong/not understanding
Reply
#2

You did it wrong in CI3 too. You should pass $this->settings to the view in a data array. Then access $settings in the view.

Something like:
PHP Code:
return view('your_view', ['settings' => $this->settings]); 

See this tutorial in the user guide for an example: https://codeigniter.com/user_guide/tutor...y-the-news
CodeIgniter 4 tutorials (EN/FR) - https://includebeer.com
/*** NO support in private message - Use the forum! ***/
Reply
#3

Gosh, ive been using it like that for years in Ci3 across tons of projects and it worked like a charm.
I am familiar with passing data to the view and i would use that to pass values initiated by that function but because every function would need $this->settings, i set it in my constructor.
Thank you for your reply. Ill have to figure this one out.
Reply
#4

I guess it work in CI3 because everything is loaded in the main CI object. In CI4 the architecture is very different. There's no global CI object.

When I have data I need in every controllers, I load them in a data array in the BaseController, then each controller add whatever they need to that array and pass it to the view. See my tutorial on multilingual website for an example of what I mean. Search the viewData variable: https://includebeer.com/en/blog/creating...r-4-part-1
CodeIgniter 4 tutorials (EN/FR) - https://includebeer.com
/*** NO support in private message - Use the forum! ***/
Reply
#5

(This post was last modified: 10-17-2021, 12:54 AM by InsiteFX. Edit Reason: fixed spacing )

This is a merge array method I created for the BaseController.

PHP Code:
<?php

namespace App\Controllers;

use 
CodeIgniter\Services;
use 
CodeIgniter\Controller;
use 
CodeIgniter\HTTP\CLIRequest;
use 
CodeIgniter\HTTP\IncomingRequest;
use 
CodeIgniter\HTTP\RequestInterface;
use 
CodeIgniter\HTTP\ResponseInterface;
use 
Psr\Log\LoggerInterface;

/**
 * Class BaseController
 *
 * BaseController provides a convenient place for loading components
 * and performing functions that are needed by all your controllers.
 * Extend this class in any new controllers:
 *    class Home extends BaseController
 *
 * For security be sure to declare any new methods as protected or private.
 */
class BaseController extends Controller
{
    /**
    * Instance of the main Request object.
    *
    * @var CLIRequest|IncomingRequest
    */
    protected $request;

    /**
    * An array of helpers to be loaded automatically upon
    * class instantiation. These helpers will be available
    * to all other controllers that extend BaseController.
    *
    * @var array
    */
    protected $helpers = [
        'debug',
        'auth',
        'utility',
    ];

    /**
     * @var \CodeIgniter\Session\Session
     */
    protected $session;

    /**
     * @var array - Global data array for views.
     *
     * Fill in your global view data here that will be
     * used in all views.
     */
    protected static $globalViewData = [
       'test' => 'This works!',
    ];

    /**
    * Constructor.
    *
    * @param RequestInterface  $request
    * @param ResponseInterface $response
    * @param LoggerInterface  $logger
    */
    public function initController(RequestInterface $requestResponseInterface $responseLoggerInterface $logger)
    {
        // Do Not Edit This Line
        parent::initController($request$response$logger);

        //--------------------------------------------------------------------
        // Preload any models, libraries, etc, here.
        //--------------------------------------------------------------------
        // E.g.: $this->session = \Config\Services::session();

        // Ensure that the session is started and running
        if (session_status() == PHP_SESSION_NONE)
        {
            $this->session Services::session();
        }

    }

    /**
     * mergeGlobalData ()
     * -------------------------------------------------------------------
     *
     * You must set the globalViewData array above with your global data
     * for all Controllers.
     *
     * Usage: Controller
     *
     * $data = $this->mergeGlobalData($data);
     *
     * @param  array $viewData
     * @return array
     */
    protected function mergeGlobalData(array $viewData) : array
    {
        if (is_array(self::$globalViewData))
        {
            return array_merge($viewDataself::$globalViewData);
        }
 
        return [];
    }

    // --------------------------------------------------------------------

}

/**
 * -----------------------------------------------------------------------
 * Filename: BaseController.php
 * Location: ./app/Controllers/BaseController.php
 * -----------------------------------------------------------------------
 */ 
What did you Try? What did you Get? What did you Expect?

Joined CodeIgniter Community 2009.  ( Skype: insitfx )
Reply




Theme © iAndrew 2016 - Forum software by © MyBB