How to access Model from Views in CodeIgniter - codeigniter

How to access Model from Views in Codeigniter.
I have a Model with a function, i need to call this function from view

Please Read the CI documentation First:
If You are using a MVC Structured Framework then you should be following the way it works.
You Need the Controller:
public function your_controller_function(){
// To load model
$this->load->model ('your_model');
//To Call model function form controller
$data = $this->your_model->model_function($ex_data);
//TO Send data to view
$this->load->view('your_view',['data'=>$data]);
}
Inside your model:
public function model_function($ex_data){
// Your Querys
// user return to send you query result to the controller anything
// Sample Example of query and return
$query = $this->db->select('*')
->where('your_column',$data['column_name'])
->get('your_table');
$your_result = $query->row_array();
if($this->db->affected_rows() > 0){
return your_result;
} else {
return FALSE;
}
}

Inside your view you can write :
<?php
$this->load->model('your_model');
$this->your_model->some_function();
?>

For example in User_controller load User Model $this->load->model('Users_model');
Then User View page $viewpage = this->Users_model->somefunction($id);

Related

how to get values from model and display in controller

I am making a site in codeigniter, here is my controller, model and view:
controller:
function checking()
{
$email=$this->input->post('email');
$this->load->model('login_model');
$data['dbemail']=$this->login_model->email();// assign your value to CI variable
$this->load->view('home', $data); //passing your value to view
}
model:
public function email()
{
$query = $this->db->query("SELECT email FROM change_password");
$result = $query->result_array();
return $result;
}
view:
foreach ( $dbemail as $new_dbemail )
{
echo $new_dbemail['database_field'];//in here you can get your table header.
//Ex if your table has name field and you need to sho it you can use $new_dbemail['name']
}
but i want to get $new_dbemail['name'] in my controller, how i can get the value of $new_dbemail['name'] in controller rather than view ???
To do so... you have to fetch data into a row_array not in result_array in Model.
Controller
function checking()
{
$email=$this->input->post('email');
$this->load->model('login_model');
$data['dbemail']=$this->login_model->email();
$database_field = $data['dbemail']['database_field']; //to get result in controller
$date['database_field'] = $data['dbemail']['database_field']; //to get result in view
$this->load->view('home', $data);
}
Model
public function email()
{
$query = $this->db->query("SELECT email FROM change_password");
return $query->row_array();
}
View
<p> Database Field value : <?=$database_field;?></p>
You are Calling the Model In A Variable :-
$data['dbemail']=$this->login_model->email();
So in this you have the results which you are fetching from Database. Than you passing this variable data to your View.
$this->load->view('home', $data);
So you already have the value in controller which u fetched from model which is stored in $data.
You can View the Values of $data , using
echo "<pre>";
print_r($data);
and it will show what data you are receiving
Try like this...
In controller...
function checking()
{
$email=$this->input->post('email');
$this->load->model('login_model');
$dbemail=$this->login_model->email();//array containing all emails
//For each loop here for displaying emails
foreach($dbemail as $email){
$mail = $email; //assigning to variable
echo $mail."<br/>";//displaying email
}
$data['dbemail'] = $dbemail;//for passing to view
$this->load->view('home', $data); //passing your value to view
}
First you need to fetch the name from the database in the model. Change the query line:
$query = $this->db->query("SELECT name, email FROM change_password");
Then to use the name data in the controller you could try this:
function checking()
{
$email=$this->input->post('email');
$this->load->model('login_model');
$data['dbemail']=$this->login_model->email();
$name = $data['dbemail']['name']; // example usage to retrieve name in controller
$this->load->view('home', $data);
}
Now the name data is available as $name in controller.
Controller:
public function checking()
{
$email=$this->input->post('email');
$this->load->model('login_model');
$data['dbemails']=$this->login_model->email();
$this->load->view('home', $data); //passing your value to view
}
Model
public function email()
{
$this->db->select("email"); // the row of the table you want to select.
$this->db->get('change_password'); //table name. you can still use your query, its just much neat when you use a specific query builder.
$result = $this->result(); //giving you a result of type object
return $result;
}
View
foreach ( $dbemails as $dbemail )
{
echo $dbemail->email; // the '->' will be the identifier of which row you want to get or display, i assume its email beacause you specify it in the model.
}
Hope this what your looking for.

How to pass variable with a master layout in Codeiginiter

My master layout here's below and working fine. I just want little bit more passing a default variable with this master layout that I can get in every pages.
class MY_Controller extends CI_Controller {
public $layout;
function __construct() {
parent::__construct();
$this->layout='layout/master';
}
}
I need to pass variable like below:
function __construct() {
parent::__construct();
$data['msg'] = $this->session->flashdata('usermsg');
$this->layout=('layout/master',$data);
}
How do I get this.
If you are loading up the data dynamically from the controller with the help of $this->layout you can send the data like this.
Method 1:
If you are using the general method to load the data to the view you can use this method.
$this->load->view('profile_view', $data);
This will load the profile_view page along with the $data as you passs into it with the help of array()
Method 2:
If you have created a master Layout and you are passing the data from the controller to the Master Layout you need to do like this.
<?php
public function master_layout () {
$this->template['header'] = $this->load->view('include/header', $this->Front_End_data, true);
$this->template['navigation'] = $this->load->view('include/navigation', $this->Front_End_data, true);
$this->template['center'] = $this->load->view($this->middle, $this->Front_End_data, true);
$this->template['footer'] = $this->load->view('include/footer', $this->Front_End_data, true);
$this->load->view('include/index', $this->template);
?>
In this code the below line alone will be loaded dynamically based on the page which you call in the master Layout.
$this->template['center'] = $this->load->view($this->middle, $this->Front_End_data, true);
In order to pass the data to this center layout you can use the funciton like this.
$data['msg'] = 'Success';
$this->template['center'] = $this->load->view ($this->middle = 'pages/view_oage',$data, true);
$this->master_layout();
And in the page you can get the data to be printed using the foreach loop as follows.
foreach($msg as $value)
{
echo $value;
}

How to passing value from link in codeigniter

My link in view page
Detail
My controller
public function cari(){
//what i'm doing here ? please help ?
}
My model
function search_by_id($id){
$query = $this->db->where('id',$id);
$query = $this->db->get();
return $query->result();
}
How pass value from link to model and show the result to view again?
it's my first time using codeigniter, need some help
You have to pass argument into method:
public function cari($hasil_id){
if ((int)$hasil_id > 0)
{
$this->load->model('Name_of_model');
$data['search_by_id'] = $this->Name_of_model->search_by_id($hasil_id);
$this->load->view('hasil_view', $data);//assuming page for item
}
else
{
redirect('not_good_id_method', 'refresh');//in case of not valid id
}
}
In your controller ,receive the value passed through link by uri class.And then pass it into your model.
Controller :
public function cari()
{
$id= $this->uri->segment(3);
$this->model_name->search_by_id($id);
}
Take a look on this.

Simple AJAX / JSON response with CakePHP

I'm new to cakePHP. Needless to say I don't know where to start reading. Read several pages about AJAX and JSON responses and all I could understand is that somehow I need to use Router::parseExtensions() and RequestHandlerComponent, but none had a sample code I could read.
What I need is to call function MyController::listAll() and return a Model::find('all') in JSON format so I can use it with JS.
Do I need a View for this?
In what folder should that view go?
What extension should it have?
Where do I put the Router::parseExtension() and RequestHandlerComponent?
// Controller
public function listAll() {
$myModel = $this->MyModel->find('all');
if($this->request->is('ajax') {
$this->layout=null;
// What else?
}
}
I don't know what you read but I guess it was not the official documentation. The official documentation contains examples how to do it.
class PostsController extends AppController {
public $components = array('RequestHandler');
public function index() {
// some code that created $posts and $comments
$this->set(compact('posts', 'comments'));
$this->set('_serialize', array('posts', 'comments'));
}
}
If the action is called with the .json extension you get json back, if its called with .xml you'll get xml back.
If you want or need to you can still create view files. Its as well explained on that page.
// Controller code
class PostsController extends AppController {
public function index() {
$this->set(compact('posts', 'comments'));
}
}
// View code - app/View/Posts/json/index.ctp
foreach ($posts as &$post) {
unset($post['Post']['generated_html']);
}
echo json_encode(compact('posts', 'comments'));
// Controller
public function listAll() {
$myModel = $this->MyModel->find('all');
if($this->request->is('ajax') {
$this->layout=null;
// What else?
echo json_encode($myModel);
exit;
// What else?
}
}
You must use exit after the echo and you are already using layout null so that is OK.
You do not have to use View for this, and it is your wish to work with components. Well all you can do from controller itself and there is nothing wrong with it!
Iinjoy
In Cakephp 3.5 you can send json response as below:
//in the controller
public function XYZ() {
$this->viewBuilder()->setlayout(null);
$this->autoRender = false;
$taskData = $this->_getTaskData();
$data = $this->XYZ->getAllEventsById( $taskData['tenderId']);
$this->response->type('json');
$this->response->body(json_encode($data));
return $this->response;
}
Try this:
public function listAll(){
$this->autoRender=false;
$output = $this->MyModel->find('all')->toArray();
$this->response = $this->response->withType('json');
$json = json_encode($output);
$this->response = $this->response->withStringBody($json);
}

Codeigniter and Set Session in Model

I want to unset and set session in model function depend on passed id.
I have language field for every record and should change session considering that.
in sample word i have a link like this : http://www.mysite.com/report/2020
now this article by this id maybe saved by english language but current session is french.so I should change the session.
here is my code but it dos not work.
//function for checking language by id
public function lang($id)
{
$data = $this->db
->select('language')
->from('content')
->where('id',$id)
->get();
if ($data->num_rows > 0) {
return $data;
}else{
return false;
}
}
//function for reading data from db depend on id and language
public function report($id)
{
$cat=2;
$code=$id;
$langu= $this->lang($id)->row()->language;
if($langu==3){
$this->session->unset_userdata('lang');
$this->session->set_userdata('lang','dr');
}
if($langu==2){
$this->session->unset_userdata('lang');
$this->session->set_userdata('lang','pa');
}
if($langu==1){
$this->session->unset_userdata('lang');
$this->session->set_userdata('lang','en');
}
$language= $this->session->userdata('lang');
$lang=$language;
$data = $this->db
->select('*')
->from('content')
->where('category',$cat)
->where('language',$lang)
->where('id',$code)
->get();
if ($data->num_rows > 0) {
return $data;
}else{
return false;
}
}
the best way to session is:
you have to check the query in model, and call the model in controller, if its true set session data within controller....
Setting Session within the model is not a good idea for an MVC architecture.
Sometimes there is really need to set or get session data in model.
Use then Code Igniter instance like below:
$codeIgniter =& get_instance();
$codeIgniter->set_userdata('data', $data);
// or to read data:
$data = $codeIgniter->userdata('data');
Note that using $this to call set_userdata() or userdata() in model will not work correctly.

Resources