简体   繁体   中英

Codeigniter: Load model and controller result in Helper

No idea what is the right way. But what I am trying to do is to make one helper function for positions list or dropdown (will set parameter for this) so that's how position list/dropdown can available to the entire system by writing single code `get_positions($type)'

The problem is not loading Model/Controller variables.

Error message:

A PHP Error was encountered

Severity: Notice

Message: Undefined variable: positions

Filename: helpers/content_helper.php

Line Number: 14

Helper

<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');


// Position List
if ( ! function_exists('get_positions'))
{
    function get_positions()
    {
        $CI =& get_instance();
        $CI->load->model('admin/hr/hr_model');

        if(count($positions)):
            echo form_open();

            $array = array();
            foreach($positions as $position):   
                $label[] = $position->label;
                $pos[] = $position->position;
            endforeach;

            echo form_dropdown('positions', array_combine($pos, $label));
            echo form_close();
        endif;
    }
}

Model

<?php (defined('BASEPATH')) OR exit('No direct script access allowed');

class HR_Model extends MY_Model
{

    protected $_table_name      =   'positions';
    protected $_order_by        =   'label ASC';
    public $rules               =   array();


    public function get_new()
    {
        $position = new stdClass();
        $position->position = '';
        $position->label = '';
        return $position;
    }


    public function get_positions($id = NULL, $single = FALSE)
    {
        $this->db->get($this->_table_name);        
        return parent::get($id, $single);
    }

}

Controller

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class HR extends MX_Controller
{

    public function __construct()
    {
        parent::__construct();
        $this->load->model('admin/hr/hr_model');
    }

    public function index()
    {
        // Fetch all pages
        $this->data['positions'] = $this->hr_model->get_positions();        

        // Load view
        $this->load->view('hr/index', $this->data);
    }

}

Eventually what I am looking is to create helper function which available to entire system by calling get_positions($type)

You have to define the $positions variable before if (count($positions)): . You should call the get_positions method from the Model.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM