Passing more than one array to more than one view - php

I'm trying to load a controller wich loads two two different views, and passes a different array to each view.
public function index(){
$this->load->view('Head');
$data=$this->DAOPromotor->recuperarPromotor();
$eventos=$this->DAOEvento->recuperarPromotorEventos();
$this->load->view('MostrarPromotor', $data);
$this->load->view('MostrarPromotorEventos', $eventos);
$this->load->view('Footer');
}
This is my Controller. Now, the first view ("MostrarPromotor') loads just fine, but the second one keeps throwing an Undefined Variable warning. I've used the recuperarPromotorEventos() method on differnt controllers, and it works just fine. I treat the array the same way on both scripts, but it only works in one.
I'm wondering if maybe it's not possible to have two views reciving data at the same time.

Found a solution after looking around some more: when you pass an array to a view, it breaks down said array on its different components, using the index names of the array as references. So, if I had this array:
$eventos = array(
'data1' => 'someData',
'data2' => 'someMoreData'
);
When I pass that array to a view, the view can access the variables $data1 and $data2, but not the $eventos data. As my original array didn't have any index named eventos, there wasn't any variable called that.
As for my particular problem, the only thing I had to do to fix it was to change the code to this:
public function index(){
$this->load->view('Head');
$data=$this->DAOPromotor->recuperarPromotor();
$eventos["eventos"]=$this->DAOEvento->recuperarPromotorEventos();
$this->load->view('MostrarPromotor', $data);
$this->load->view('MostrarPromotorEventos', $eventos);
$this->load->view('Footer');
}

Related

Passing data to view from controller using templates

Controller:
public function home(){
$data['page_title'] = 'Home';
$data['navbar_content'] = $this->model->get($var);
$data['page_content'] = $this->model->get($var1);
$this->load->view('template/header');
$this->load->view('template/navbar');
$this->load->view('pages/home');
$this->load->view('template/footer');
}
Using the sample code above, Since codeigniter only allows the passing of variables/data through an array or object from controller to the view then what is the 'right' way to pass my data?
I could simply pass the data when loading the header and things will still work out fine.
$this->load->view('template/header', $data);
$this->load->view('template/navbar');
$this->load->view('pages/home');
$this->load->view('template/footer');
But that doesn't seem 'right' to me, i guess i wanted things to be clear in my code for example:
$this->load->view('template/header', $title);
$this->load->view('template/navbar', $navbar_content);
$this->load->view('pages/home', $page_content);
$this->load->view('template/footer');
The above is clear cut and there is a distinction to the data that are being passed.
But since i can't do that, is there a 'correct' way of doing this? or am i thinking too much on it?
I neglected to mention, I could simply make 2 arrays to pass to the view. I thought this is wrong in the first place since i'm going out of my way to make 2 arrays to pass just so i can pass a single string variable to my header page.
Ofcourse when i pass more data to my navbar then it would make sense to me.
This is the correct way according to the documentation:
https://codeigniter.com/userguide3/general/views.html
Data is passed from the controller to the view by way of an array or an object in the second parameter of the view loading method.
You should also look on:
Codeigniter: Best way to structure partial views
You should structure you views hierarchically.
$this->load->view('template/header', ["title" => $title]);
$this->load->view('template/navbar', ["navbar_content" => $navbar_content]);
$this->load->view('pages/home', ["page_content" => $page_content]);
$this->load->view('template/footer');
CodeIgniter passes data from controllers to views.
You need to pass $data to views.
You will pass an array with its keys be strings or even arrays (multi-dimensional arrays also).
So, you need to pass it to every view you are using $data.
$this->load->view('template/header', $data);
$this->load->view('template/navbar', $data);
$this->load->view('pages/home', $data);
$this->load->view('template/footer', $data);
And in your view, you can access $data with keys.
For example:
if your data is
$data['header_banner'] = 'Header Banner';
In your view, you can access this value by:
echo $header_banner;
Observe that to the key in $data, you just need to add a $ and you can access that variable.
Its something line PHP's in built function extract()

Cake PHP multiple view pages have access to the same variables

I'm doing the blog tutorial (CakePHP 2.4.1) and have a question.
What is the reasoning ( and why) does the index.ctp page require me to loop through the
$posts variable to get data but the view.ctp file lets me just grab $post without looping?
I deleted the following action in PostController.php
and still could render the view.ctp file so I figure the two are not connected.
public function index() {
$this->set('posts', $this->Post->find('all'));
}
You're setting post in both of the controller's functions:
index()
$this->set('posts', $this->Post->find('all'));
view()
$post = $this->Post->findById($id);
$this->set('post', $post);
It would be odd if you weren't able to access the variables, but it seems everything is functioning as normal in your example
Edit:
You loop through the array in the index because you have multiple posts inside of an array. And in the view you're setting only a singular array containing one post so there is no need to loop through anything, you're able to grab the elements directly.
$this->set('posts', $this->Post->find('all'));
This will return an array of posts - notice the find('all')
$this->set('post', $this->Post->findById($id));
This will return a single post by the passed $id parameter.
The reason you have to loop through $posts is because its an array (returned by the find all), where $post is just a single post returned by findById)

Codeigniter Session->userdata is null

My project has several views which draw values out of the session->userdata array.
the whole project works flawlessly on my development machine, but when I copied the project up to a server, I find that $this->session->userdata is null.
This is the code which inserts some values into the session->userdata array:
It is called in the Controller.
$sessionArray = array(
'web_id' => $id,
'paperId' => $paperId,
'prelimId' => $prelimId,
'intakeId' => $intakeId,
'finalId' => $finalId,
);
$this->session->set_userdata($sessionArray);
In the view file I call
var_dump($this->session->userdata);
The value returned is null. As I mentioned before, the array is NOT null on my development computer (running WAMP). Does anyone know why?
In order to retrieve all session data as an ASSOC array, you could use the all_userdata() method. (Take a look at CodeIgniter user guide),
You can write that within your Controller and send the returned value to the view, as follows:
$data['userdata'] = $this->session->all_userdata();
$this->load->view('your/view.php', $data); // use $userdata in the view
Note: Using the session library directly inside the views may cause unexpected problems. Try managing your sessions in the Controller instead of the View.
Sorry for posting here in answer block first of all.......... Where you are assigning those values to $sessionArray. What i mean is in model or controller or in view file.
Are you calling var_dump($this->session->userdata) in view file.
Why don't you call that in controller and pass that as an array to view file via controller.
try like this in controller i will get user details in $login array from database for suppose when i submit username and password.
I will send those details to session array like this in model file
$this->session->set_userdata('logged_in_user', $login);
after that in controller if i want use user name from session array i will use like below.
$logged_in = $this->session->userdata("logged_in_user");
$model=array();
$model['logged_in_user']=$logged_in[0];
Once after i assigned to $model array i like to use that in view file so i will pass that $model array to view file from controller like this
$this->load->view('view_file_path',$model);
You can use that array in view file how ever you want from passed array.

MVC Fundamentals: Passing work along to the view?

I'm using Doctrine2 and CodeIgniter2, and am new to both, as well as to OOP/MVC, so please use simple explanations :)
For testing purposes, I have a Controller a Model and a View. I want to display data from a table that contains user information. First name, last name, ID number, and so forth.
My controller makes a call to the model- which retrieves data from the doctrine entity, and then the controller passes that data to the view.
(controller)
class Test_v_to_m extends CI_Controller {
public function index() {
$this->load->model('testing/test_v_to_m_model');
$data = $this->test_v_to_m_model->display_user_info();
$this->load->view('testing/test_v_to_m_view', $data );
}
}
(model)
class Test_v_to_m_model extends CI_Model{
public function display_user_name() {
$query = $this->doctrine->em->createQuery("select u from ORM\Dynasties2\Users u");
return $query->getResult();
(view)
//print_r($data);
First question is: How do I pass the object or array along to the view in a useful way? This works if I'm just dealing with a single variable:
(controller)
$user = $this->doctrine->em->find('Entities\User', $user_id);
$data['firstname'] = $user->getFirstName();
$this->load->view('testing/test_v_to_c_view_2',$data);
(view)
echo $firstname;
But I don't know how to do something similar when its an array, or a multidimensional array.
The second question is whether or not to let the view do any real work (php logic, loops, foreach, etc) or to do all of that in the controller and have the view only do formatting and display.
Yes, You can just pass multi-dimensional array to the view and then access it as required.
e.g.
$template_date['result_arr'] = array(
array('firstname' => 'abc', 'lastname' => 'xyz')
, array('firstname' => 'abc', 'lastname' => 'xyz')
);
in your view file -
foreach($result_arr as $key => $row) {
echo $row['firstname'].' <br />';
}
Re your 2nd question - As per my understanding - it's fine to use some foreach, for loops in the view but it's best if business logic is kept to controllers and models. Hope it makes sense to you.
As for your first question, I don't know the answer off the top of my head (sorry!). I would imagine, however, that an array can be passed as part of the data (as a single item), but you would need to iterate though it in the view (see below). Just a guess, however...
As for your second question, the principle of MVC is to have only display logic in the view - so all of the "real work" should be done in the controller.
Now, if you want to have a loop to display data in a table, that's "real work" being done in the view, but since it's part of formatting and display that would be acceptable.
Regarding your first question, it's actually quite simple:
$data = array(
'firstname' => 'string',
'array' => array(1, 2, 3),
'multidimensional_array' => array('ocean' => 'deep')
);
In the view, you can access these as:
$firstname;
$array;
$multidimensional_array;
They're just exported to the view, so you can treat each key in the $data array as a variable, and the values in the $data array as the variables' values.
Regarding the second question, it is generally best if you have the view only do formatting and display. In some cases, it might be useful to use ifs or loops, for example, if you want to display different messages based on a certain variable, or if you want to fill a table with a bunch of rows. However, I strongly recommend that you keep out as much logic as possible. The view is meant to receive all the data it needs and display it in a way that suits it.
There are plenty of reasons for this, namely maintainability (if your logic changes, you don't need to update the view), reusability (if you make views as general as possible, you can reuse them very easily) and even the ability to create new views or to replace that view with a different one, without worrying about the logic.
I hope this helps. :)

How does CodeIgniter send information from a Model to a View with the Controller?

When I call a controller and it calls the model, model returns information from my database assigned to something in the controller.
But how does it "send" it to the view for rendering? How for example, when I send $data array to my_view.php. how does it get to that page so that, I am guessing, I can do things like use extract to get my individual variables.
I'm really asking at the php level, how would you send that data (so I can learn). How does that view know what I sent it?
Thanks.
You have to "send" that $data array to the view as the second parameter when you load it.
$data['user'] = array(
'name' => 'Tom Jones',
'gender' => 'male'
);
$this->load->view('blogview', $data);
Then, the contents of the array are accessed within the view by their corresponding key values
<?php echo $user['name']; ?>
Checkout out the docs for more details: http://codeigniter.com/user_guide/general/views.html
The general pattern of all php views is this:
function render_view($__filename, $__data) {
extract($__data);
include $__filename;
}
This is basically how CodeIgniter does it, but it uses a loader to find the view filename and includes output buffering options.

Categories