Best practise for passing data to subview codeigniter - php

I am looking for the best practise when it comes to passing data from the controller to a subview in Codeigniter, so far I have created a layout file which loads the subviews. For example, when I have been doing this, it does work but I am wondering if there is a cleaner way of doing things? Or are there any better options for templating my html and CSS without having to do this for every function?
Currently renaming each separate $data variable to $var1, $var2, $var3 etc.
Here is my code when loading pagination and passing this to the subview.
function index($start=0)
{
$var1['posts']=$this->post->get_posts(3,$start);
$this->load->library('pagination');
$config['base_url']=base_url().'posts/index/';
$config['total_rows']=$this->post->get_posts_count();
$config['per_page']=3;
$this->pagination->initialize($config);
$var2['pages']= $this->pagination->create_links();
$var3=array('subview' => 'post_index');
$data=array_merge($var1, $var2, $var3);
$this->load->view('layouts/layout',$data);
}
And in my template file I use this line of code in the body to load the subviews:
<?php $this->load->view($subview); ?>

Okay there indeed is a way to do that. Assuming you have a view called post_index in which you pass $var['posts'] and then you want to put that view in your master layout.
$var['posts'] = $this->post->get_posts(3, $start);
// setting the third parameter as true would return the view as
// data which you can pass to another view
$data['page'] = $this->load->view('post_index', $var, TRUE);
$this->load->view('layouts/layout', $data);
From codeigniter docs
Returning views as data
There is a third optional parameter lets you
change the behavior of the method so that it returns data as a string
rather than sending it to your browser. This can be useful if you want
to process the data in some way. If you set the parameter to TRUE
(boolean) it will return data. The default behavior is false, which
sends it to your browser. Remember to assign it to a variable if you
want the data returned.

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()

how to pass a variable from one controller to the other in Code igniter

I have just started learning Code Igniter .
I want to know how can I pass a variable from one controller(first_cont.php) to other controller (second_cont.php) ?
Any help would be appreciated .
Thanks in Advance :)
It will depend on the circumstances. If you want to retain the data for some time, then session data would be the way to go. However, if you only need to use it once, flash data might be more appropriate.
First step would be to initialise the session library:
$this->load->library('session');
Then store the information in flash data:
$this->session->set_flashdata('item', $myVar);
Finally, in the second controller, fetch the data:
$myVar = $this->session->flashdata('item');
Obviously this would mean you'd have to either initialise the session library again from the second controller, or create your own base controller that loads the session library and have both of your controllers inherit from that one.
I think in codeigniter you can't pass variable, between two different controller. One obvious mechanism is to use session data.
Ok, here is something about MVC most will readily quote:
A Controller is for taking input, a model is for your logic, and, a view is for displaying.
Now, strictly speaking you shouldn't want to send data from a controller to another. I can't think of any cases where that is required.
But, if it is absolutely needed, then you could simply use redirect to just redirect to the other controller.
Something like:
// some first_cont.php code here
redirect('/second_cont/valuereciever/value1')
// some second_cont.php code here
public function valureciever($value){
echo $value; // will output value1
}
In Codeigniter there are many way to pass the value from one controller to other.
You can use codeigniter Session to pass the data from one controller to another controller.
For that you have to first include the library for session
$this->load->library('session');
Then You can set the flash data value using variable name.
// Set flash data
$this->session->set_flashdata('variable_name', 'Value');
Them you can get the value where you want by using the codeigniter session flashdata
// Get flash data
$this->session->flashdata('variable_name');
Second Option codeigniter allow you to redirect the url from controll with controller name, method name and value and then you can get the value in another controller.
// Passing the value
redirect('/another_controller_name/method_name/variable');
Then you can get the value in another controller
public function method_name($variable)
{
echo $variable;
}
That all....
If you are using session in the first controller then dont unset that session in first controller, instead store the value which you want in the other controller like,
$sess_array = array('value_name1' => 'value1', 'value_name2' => 'value2');
$this->session->set_userdata('session_name', $sess_array);
then reload this session in the other controller as
$session_data= $this->session->userdata('session_name');
$any_var_name = $session_data['value1'];
$any_var_name = $session_data['value2'];
this is how you can pass values from one controller to another....
Stick to sessions where you can. But there's an alternative (for Codeigniter3) that I do not highly recommend. You can also pass the data through the url. You use the url helper and the url segment method in the receiving controller.
sending controller method
redirect("controller2/method/datastring", 'refresh');
receiving controller method
$this->load->helper('url');
$data = $this->uri->segment(3);
This should work for the default url structure. For a url: website.com/controller/method/data
To get controller $this->uri->segment(1)
To get method $this->uri->segment(2)
The limitation of this technique is you can only send strings that are allowed in the url so you cannot use special characters (eg. %#$)

Clean way of passing variable to partial view

I'm looking for a clean way to pass variables to partial views. Consider the following example code:
In my controller I do:
$this->view->articles = $arrayWithArticles;
$this->render('articles.phtml');
In my articles.phtml view I do:
foreach($this->articles as $article) {
// show article
$this->render('comments.phtml');
}
In another controller I do:
$this->view->products = $arrayWithProducts;
$this->render('products.phtml');
In my products.phtml view I do:
foreach($this->products as $product) {
// show product
$this->render('comments.phtml');
}
As you can see I use the same (partial) view comments.phtml to display comments about written articles as well as products. The 'comments' I want to display are in $article->comments and $product->reviews. The partial view will need these to display them.
What would be a clean way to pass them to the partial view. I really don't want to do:
$this->comments = $article->comments;
$this->render('comments.phtml');
Because this would potentially become a pain to keep track off (i.e. setting the same view variables in both the controller as in the view).
Is there a clean solution to pass variables to partial views?
Well, I think adding a parameter to your render() method would be sufficient. Maybe something like...
$this->renderSubView($fileName, $data);
Then in renderSubView() you could do whatever it is that you need to do with the array and return the rendered partial view. This way you don't need to redeclare the variable in view, just pass the data appropriate for that specific partial when it is being rendered.

Codeigniter pagination conceptual problem

I have a page /discussion and I want to implement pagination in it. Now, I want that for the first time the page should load as /discussion, which means that this act as if it was /discussion/page/1. For the other page the url will be /discussion/page/$pagenumber.
Now, the problem is index(). Normally, I initialize all the page data in the index() and then load the view with the initialized data. But, here I’ll have to initialize default page stuff in index() and then the pagination stuff in page(). So, is there a way of sending another set of data from page() to the view? I don’t want to load the view since it will be loaded by the index().
However, I think it is not possible to do what I mentioned above. So, maybe I should keep my index() empty and do all the initialization in the page() and then load the view there. What do you say?
You don't need both the "page" and "index" methods, just use a route.
Using an index() method and dropping the page() method:
$route['discussion/page/(:num)'] = 'discussion/index/$1';
/discussion still gives you page 1, requesting discussion/page/32 will map to discussion/index/32
This assumes you're grabbing the page number as an argument (url segment), like so:
function index ($page = 1) {}
If you are doing something else, a route is still appropriate, maybe just not the one provided.
I suggest to have a look at PEAR's awesome Pager package. It automatically generates a pager and gives you the correct indexes depending on the (GET) input variables.
It sounds like you're trying to have your page method decorate your index method. Without knowing more about the overall structure of the controller, there really isn't terribly much to say, but it sounds like the below will help:
function page( $pos )
{
$this->index( $pos );
}
// a default parameter lets you ensure that this does not neet to have a page set.
function index( $pos = 0 )
{
// when calling the DB (I'm guessing that is where the pagination really happens)
// COUNT should be defined in the config if possible.
$this->db->where/*... add more here...*/->limit( COUNT, $pos );
}
Realistically, you should look into your URI routing class or using the _resolve method, but this should do what you need it to.
I'm not quite sure what your problem is.
If you have a index() method you can set all the pagination information there, remember you have to tell the pagination library which uri segment will be using to get the page number, and that doesn't have anything to do with the index().
There is no page() method in the controller, all of the pages are the same index() with a different set of paginated data, given by the uri_segment defined as the page number, that means all the stuff that is not related to the paginated queryset are intact through the pages.

Returning Data with a Zend Framework View Helper

I am creating a view helper to deal with returning some data screen scraped from elsewhere and my question is, what is the best way to gather the collected data and return it for use in the view?
Assume the view helper goes out and successfully grabs a few divs full of data.
Should I return an array of data and iterate over that in the view?
$i = 0
foreach($this->myHelper as $noob) {
echo '<div><h3>'.$noob[$i][0].'</h3>'.$noob[$i][2].'</div>';
$i++;
}
or perhaps build the output in the view helper and return the whole lot as a string?
echo $this->myHelper;
/* giving me something like:
<div><h3>Foo1</h3>bar1</div>
<div><h3>Foo2</h3>bar2</div>
*/
or return an object rather than an array or some other way I am missing (or screwing up in the above examples)? Thanks in advance.
I'd add a view partial argument and pass the data to the nominated partial script, returning the result using the partial or partialLoop helpers (depending on your data), for example
<?php echo $this->myHelper('path/to/partial.phtml') ?>
and in your helper
return $this->partial($partialScript, $data);
Edit If you wanted to simplify things, you could make the partial argument optional and if it was missing, build your HTML string internally.
The basic ideas with view helpers is that they return strings or objects that implement __toString()

Categories