Welcome Guest, Not a member yet? Register   Sign In
Where To Place View Related Function?
#1

[eluser]Md. Iftekharul Islam Sakib[/eluser]
Hi,
I have some function in my project which are used to display Some Common Things Of View.

As Example
Code:
function showTrueOrFalse($myBool)
{
if($myBool)
echo "It is True";
else
echo "Oops! It is false";
}

If I don't use this function than I have to write the same code many times. For using these function I just call them from View.

As Example
Code:
<?php showTrueOrFalse(true)?>;

They will only be called from view. But as I have 3 views if I copy this function in both of them it will be a mere code duplication.

As, I am new to codeigniter, I am not understanding where to put this view related functions. It will be very helpful if any of you help me.



#2

[eluser]InsiteFX[/eluser]
Code:
function showTrueOrFalse($myBool)
{
$result = '';

if($myBool)
$result = 'It is True';
else
$result = 'Oops! It is false';

return $result;
}

// controller
$data = array();

$data['show_bool'] = showTrueOrFalse($myBool);
$this->load->view('your_view', $data);

// in view file
<?php echo $show_bool; ?>
#3

[eluser]Stefan Hueg[/eluser]
Against the previous poster's opinion it sounds to me like a perfect example for a helper, as you said that this function is view-related and in case that you don't need any CodeIgniter-related objects or variables.

To do so, just create a new .php file under /application/helpers/ using the scheme "myname_helper.php".

You then load it with
Code:
$this->load->helper('myname');
anywhere in your controller or just add it to the autoload.php

Code:
$autoload['helper'] = array('myname');

Which would autoload it on every controller call, in case that you need it. You will then be able to call your helpers functions directly inside of your view.

You will find further information in the great CodeIgniter documentation:
http://ellislab.com/codeigniter/user-gui...lpers.html




Theme © iAndrew 2016 - Forum software by © MyBB