Codeigniter - Accessing variables from a helper file - not a class - php

I have a helper file, it has a variable that I want to pass across to a view, but it comes across as empty, so I am a bit unsure if I have the right code or I have overwritten it later on _ though I am sure I have not!
anyway say the variable in ther helper file is an array that contains a list of data, and I use:
$this->load->helper('helperfile_helper'); //contains the variable 'productList'
$data['productList'] = $productList;
$this->load->view('page', $data);
I would expect that the helper file works like an 'include' with the defined variables available once the helper has been called, is this the casee or have I missed something??

Helpers allow you to use function in your controller, have a look here: http://ellislab.com/codeigniter%20/user-guide/general/helpers.html
So you must create a function in your helper file that will return a value.
For example in your helper:
if( ! function_exists('random_number'))
{
function random_number()
{
return 4;
}
}
and in your controller you can use it:
$this->load->helper('helperfile_helper'); //contains the variable 'productList'
$data['random_number'] = random_number();
$this->load->view('page', $data);
So $data['random_number'] will contain 4

Related

Can someone explain how Laravel shares variables with view?

In Laravel controller function you can return view with array of variables you like to share with the current view. Something like this:
public function index() {
return view('index')->with(['name' => 'John doe']);
}
Then you can use the name inside the with() function as $name in your view.
Can someone explain how it been done please? I would like to do something similar by myself.
We can pass individual pieces of data to the view using the 'with' method.
When passing information in this manner, the data should be an array with key / value pairs. Inside your view, we can then access each value using its corresponding key, such as
<?php echo $key; ?>
Laravel include the view file inside a function which makes all defining variables scope within a function.
Just before including files laravel calls PHP's builtin function extract(array) which declare all the variable in the scope.
extract create variables out of array making key as variable name and value as variable value.

Get data from model to every view using OOP and DRY

I have a piece of data I want passed to every view. I am using CodeIgniter 3 and have PHP 7 available to me. The current way I do it is using something like this in every function.
$data['foobar'] = $this->general_model->foobar();
// More code
$this->load->view('homepage', $data);
I'd prefer not to have to call $data['foobar'] = $this->general_model->foobar(); on every single function.
I've tried many approaches to fix this without resorting to anything that makes the code too goofy. I've tried constructors, autoload, and hooks. The problem in each case boils down to the fact that $data is local to each function. The best I've gotten is usually something like this.
$data['foobar'] = $this->foobar;
// More code
$this->load->view('homepage', $data);
This is slightly nicer, but it still results in me placing this line in every function.
I'd like my functions to in someway inherit $data with the index foobar already set. I'd prefer to avoid a solution that requires every function receiving $data as a parameter. How can I accomplish this?
Option 1:
Not sure if you have tried this but you could set $data as a property of your class
protected $data = [];
Then in your constructor set it.
$this->data['foobar'] = $this->general_model->foobar();
This would mean your $data becomes accessible to all your methods in your controller and you would need to refer to them as $this->data['data_name'] and use it in a view like
$this->load->view('homepage', $this->data);
Option 2:
A second way is to create a method like render() which is common to all your methods that load views and replaces your existing view calls.
So you would have something like...
public function one_of_my_methods(){
$data['content'] = 'This is content 1';
$this->render('test_view',$data); // Call the new view handler
}
// All methods using views now call this to load the final view
public function render($view,$data){
$data['foobar'] = 'I am common'; // DRY
$this->load->view($view, $data);
}

How to pass a data with redirect in codeigniter

In my controller i used this way. i want to pass a variable data to my index function of the controller through redirect
$in=1;
redirect(base_url()."home/index/".$in);
and my index function is
function index($in)
{
if($in==1)
{
}
}
But I'm getting some errors like undefined variables.
How can i solve this?
Use session to pass data while redirecting. There are a special method in CodeIgniter to do it called "set_flashdata"
$this->session->set_flashdata('in',1);
redirect("home/index");
Now you may get in at index controller like
function index()
{
$in = $this->session->flashdata('in');
if($in==1)
{
}
}
Remember this data will available only for redirect and lost on next page request. If you need stable data then you can use URL with parameter & GET $this->input->get('param1')
So in the controller you can have in one function :
$in=1;
redirect(base_url()."home/index/".$in);
And in the target function you can access the $in value like this :
$in = $this->uri->segment(3);
if(!is_numeric($in))
{
redirect();
}else{
if($in == 1){
}
}
I put segment(3) because on your example $in is after 2 dashes. But if you have for example this link structure : www.mydomain.com/subdomain/home/index/$in you'll have to use segment(4).
Hope that helps.
Use session to pass data while redirecting.There are two steps
Step 1 (Post Function):
$id = $_POST['id'];
$this->session->set_flashdata('data_name', $id);
redirect('login/form', 'refresh');
Step2 (Redirect Function):
$id_value = $this->session->flashdata('data_name');
If you want to complicate things, here's how:
On your routes.php file under application/config/routes.php, insert the code:
$route['home/index/(:any)'] = 'My_Controller/index/$1';
Then on your controller [My_Controller], do:
function index($in){
if($in==1)
{
...
}
}
Finally, pass any value with redirect:
$in=1;
redirect(base_url()."home/index/".$in);
Keep up the good work!
I appreciate that this is Codeigniter 3 question, but now in 2021 we have Codeigniter 4 and so I hope this will help anyone wondering the same.
CI4 has a new redirect function (which works differently to CI3 and so is not a like for like re-use) but actually comes with the withInput() function which does exactly what is needed.
So to redirect to any URL (non named-routed) you would use:
return redirect()->to($to)->withInput();
In your controller - I emphasise because it cannot be called from libraries or other places.
In the function where you are expecting old data you can helpfully use the new old() function. So if you had a key in your original post of FooBar then you could call old('FooBar'). old() is useful because it also escapes data by default.
If however, like me, you want to see the whole post then old() isn't helpful as the key is required. In that instance (and a bit of a cheat) you can do this instead:
print'<pre>';print_r($_SESSION['_ci_old_input']['post']);print'</pre>';
CI4 uses the same flash data methods behind the scenes that were given in the above answers and so we can just pull out the relevant session data.
To then escape the data simply wrap it in the new esc() function.
More info would be very helpful, as this should be working.
Things you can check:
Is your controller named home.php? Going to redirect(base_url()."home"); shows your home page?
Make your index function public.
public function index($in) {
....
}

Rewriting PHP Function - Basics for Optimizing Notice of Undefined Variable

Need advise, as was getting "Undefined variable: tpl in /home/mytoys11/public_html/components/com_forms/controller.php on line 101"
function toys(){
// Create the view
global $Itemid;
$model = & $this->getModel('pages');
$view = & $this->getView('pages', 'html');
$view->setLayout('toys');
// Push the model into the view (as default)
$view->setModel($model, true);
// Display the view
$view->toys($tpl);
}
Which is solved like this by removing the undefined variable $tpl from view in the last line
function toys(){
// Create the view
global $Itemid;
$model = & $this->getModel('pages');
$view = & $this->getView('pages', 'html');
$view->setLayout('toys');
// Push the model into the view (as default)
$view->setModel($model, true);
// Display the view
$view->toys();
}
The page is loading fine after removing $tpl. I think tpl is empty string, but is this the correct way or the function is poorly optimized, any suggestions. Thanks
Edit
Thanks, As advised, here's the code been modified
public function toys(){
$model = $this->getModel('pages');
$view = $this->getView('pages', 'html');
$view->setLayout('toys');
$view->setModel($model, true);
$view->toys();
}
However, it does not work with using function name as :-
displaytoys()
It is ok and safe to omit the $tpl argument, if you don't want to address a specific (sub-) template of your view.
The code has several other problems, though.
Visibility is not declared. For an action in a controller this should be public.
Method names are verbs, not nouns.
Never use global. $Itemid is not even used.
Don't comment the obvious facts.
PHP4 is gone, so objects are assigned by reference by default.
So your code should look like this:
public function displayToys()
{
$model = $this->getModel('pages');
$view = $this->getView('pages', 'html');
$view->setLayout('toys');
$view->setModel($model, true);
$view->displayToys();
}
In order to make the renaming to displayToys work, you'll also have to change other places in your code. Wherever you refer to the task toys, you have to change it to displayToys. The corresponding method in the view class has to be renamed, too.
Since this only is a style issue, it is ok to leave the name alone and stay with toys in the first step. You'll not get functional problems from that.

CodeIgniter: Create new helper?

I need to loop lot of arrays in different ways and display it in a page. The arrays are generated by a module class. I know that its better not to include functions on 'views' and I want to know where to insert the functions file.
I know I can 'extend' the helpers, but I don't want to extend a helper. I want to kind of create a helper with my loop functions.. Lets call it loops_helper.php
A CodeIgniter helper is a PHP file with multiple functions. It is not a class
Create a file and put the following code into it.
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
if ( ! function_exists('test_method'))
{
function test_method($var = '')
{
return $var;
}
}
Save this to application/helpers/ . We shall call it "new_helper.php"
The first line exists to make sure the file cannot be included and ran from outside the CodeIgniter scope. Everything after this is self explanatory.
Using the Helper
This can be in your controller, model or view (not preferable)
$this->load->helper('new_helper');
echo test_method('Hello World');
If you use this helper in a lot of locations you can have it load automatically by adding it to the autoload configuration file i.e. <your-web-app>\application\config\autoload.php.
$autoload['helper'] = array('new_helper');
-Mathew
Some code that allows you to use CI instance inside the helper:
function yourHelperFunction(){
$ci=& get_instance();
$ci->load->database();
$sql = "select * from table";
$query = $ci->db->query($sql);
$row = $query->result();
}
Well for me only works adding the text "_helper" after in the php file like:
And to load automatically the helper in the folder aplication -> file autoload.php add in the array helper's the name without "_helper" like:
$autoload['helper'] = array('comunes');
And with that I can use all the helper's functions
To create a new helper you can follow the instructions from The Pixel Developer, but my advice is not to create a helper just for the logic required by a particular part of a particular application. Instead, use that logic in the controller to set the arrays to their final intended values. Once you got that, you pass them to the view using the Template Parser Class and (hopefully) you can keep the view clean from anything that looks like PHP using simple variables or variable tag pairs instead of echos and foreachs. i.e:
{blog_entries}
<h5>{title}</h5>
<p>{body}</p>
{/blog_entries}
instead of
<?php foreach ($blog_entries as $blog_entry): ?>
<h5><?php echo $blog_entry['title']; ?></h5>
<p><?php echo $blog_entry['body']; ?></p>
<?php endforeach; ?>
Another benefit from this approach is that you don't have to worry about adding the CI instance as you would if you use custom helpers to do all the work.
Create a file with the name of your helper in /application/helpers and add it to the autoload config file/load it manually.
E.g. place a file called user_helper.php in /application/helpers with this content:
<?php
function pre($var)
{
echo '<pre>';
if(is_array($var)) {
print_r($var);
} else {
var_dump($var);
}
echo '</pre>';
}
?>
Now you can either load the helper via $this->load->helper(‘user’); or add it to application/config/autoload.php config.
Just define a helper in application helper directory
then call from your controller just function name like
helper name = new_helper.php
function test_method($data){
return $data
}
in controller
load the helper
$this->load->new_helper();
$result = test_method('Hello world!');
if($result){
echo $result
}
output will be
Hello World!
To retrieve an item from your config file, use the following function:
$this->config->item('item name');
Where item name is the $config array index you want to retrieve. For example, to fetch your language choice you'll do this:
$lang = $this->config->item('language');
The function returns FALSE (boolean) if the item you are trying to fetch does not exist.
If you are using the second parameter of the $this->config->load function in order to assign your config items to a specific index you can retrieve it by specifying the index name in the second parameter of the $this->config->item() function. Example:
// Loads a config file named blog_settings.php and assigns it to an index named "blog_settings"
$this->config->load('blog_settings', TRUE);
// Retrieve a config item named site_name contained within the blog_settings array
$site_name = $this->config->item('site_name', 'blog_settings');
// An alternate way to specify the same item:
$blog_config = $this->config->item('blog_settings');
$site_name = $blog_config['site_name'];

Categories