undefined variable on codeigniter - php

I have a project in which is develop in codeigniter.
The project is like this:
-root
--controller
---Slider.php
--models
---My_data.php
--views
---slider_view.php
---giris.php
Slider.php
public function manset_al(){
$title['title']='manşet listesi';
$this->load->model('My_data');
$data['manset']= $this->My_data->get_manset();
$this->load->view('slider_view' ,$data);
}
My_data.php code is;
public function get_manset() {
// $sorgu =
// mysql_query("select * from manset, haberler
// where manset.onay='1' and manset.link=haberler.id and haberler.onay='1'
// order by haberler.id desc");
$this->db->select('*');
$this->db->from('manset as man, haberler as hab');
$this->db->where('man.link=hab.id');
$this->db->where('hab.onay=1');
$query = $this->db->get();
if ($query->num_rows() > 0) {
return $query->result();
} else {
return $query->result();
}
slider_view.php code is:
foreach($manset as $row){
$baslik =$row->baslik;
$icerik =$row->icerik;
$link =$row->link;
$img_path =$row->img_path;
$giris =$row->giris;
$cikis =$row->cikis;
echo '
<div>
<img data-u="image" src="'.$img_path.'"/>
<div data-u="thumb"> <h5 style="color:white; margin:10px;">'.$baslik.' </h5> </div>
</div>';
}
Now when i called
http//example.com/index.php/Slider/manset_al
every think is ok - the slider is running.
But when i get the slider in giris.php with this code;
$this->load->view('slider_view');
it's not run and say: undefined variable manset;
how can ı fix it?
Thank you.

We're missing some details to quickly solve this one: namely, how is giris.php called, exactly? Without those details I can only give a general answer.
This error means that you are trying to access data in your template file that you haven't passed to the templating system. For instance, in your controller (Slider.php) you pass data off to the templates here:
$this->load->view('slider_view' ,$data);
The $data is the important part: codeigniter takes every entry in that array and creates a variable in the template system whos name corresponds to the name of each key. Therefore, foreach( $manset as $row ) works because $data has a key named manset that has each row in it. You can see that in giris.php you are specifically not sending any data to the template:
$this->load->view('slider_view');
Notice the lack of a second parameter. Of course your file structure implies that giris.php is itself a view file, which means that whatever controller method that called giris.php needs to be the one sending data out to the view. So generally, that is the answer: whatever controller is ultimately calling giris.php needs to be sending the slider information out to the templating system, but isn't. Without more details on how giris.php is actually called, that is as specific as I can get.

Related

Functions in controllers and blade - Laravel

I'm slowly starting to come to grip with Laravel but keep having little issues doing basic things.
So this is what I have at the moment
A function and a function that is called by my route both in my webcontroller.php
// Function for printing out copyright year
function copyright_info($begin_year = NULL)
{
date_default_timezone_set('Europe/London');
if(empty($begin_year) || $begin_year == date('Y'))
echo date('Y');
else
echo $begin_year." - ".date('Y');
}
// function being called by route.php to get Restaurant Page
public function restaurant () {
$cookie = Cookie::get("basket");
return view('pages.restaurant', ['basket' => $cookie]);
}
Now all the first function does is print out something like 2013-2015 once the year is provided.
So I should be able to do something like this
public function restaurant () {
// use the function and get copyright year
$year = copyright_info('2013')
$cookie = Cookie::get("basket");
// pass data to the view including the year we just created
return view('pages.restaurant', ['basket' => $cookie, 'year' => $year]);
}
Now in my restaurant.blade.php file, I'm including my footer in my includes folder that is generic to all my pages like this #include('includes.footer'). Now the footer is what actually contains a div that requires the $year I have passed to the restaurant view. in my footer.blade.php I have this
<p style="font-size: 0.9rem">Copyright © {{ $year }} | xxx.com Limited</p>
Now I would assume that when I pass data to restaurant and footer is included in restaurant the data will apply to footer when it gets included in restaurant but that doesn't happpen.
After a lot of testing, I have now found out that my function doesn't produce any data at all. This is not because the function doesn't work also because in normal PHP it does
Any guidance appreciated
Try to pass $year from restaurant.blade to footer.blade
#include('includes.footer', ['year'=>$year])
So I figured it out.
Laravel will add the variable regardless of whether it is used in the main view or the include
Always, always make sure that your functions return something. From the question you can see that my function uses echo
Hope this helps someone in the future.

Zend View array variable inside a partialLoop

Here is the code in my controller:
$this->view->myArray = array();
$this->view->test = "";
$out = $this->view->partialLoop('tab/partial.phtml', $data);
echo $this->view->test; // Output: This works
echo count($this->view->myArray); // Output: 0
And the partial partial.phtml:
$v->test = $this->partialLoop()->view;
$v = "This works";
echo $v->test; // Output: This works
$v->myArray[] = "hello";
echo count($v->myArray); // Output: 0
I don't think that accessing view variables from a partialLoop is a wonderful idea. That aside, why doesn't it work for my array variable?
it doesn't work because you don't have access to the view variables in the partial. You have access to the data you pass to the partial.
$out = $this->view->partialLoop('tab/partial.phtml', $data);
This line of code would have access to the information contained in $data.
So this code in your current partial is basically meaningless:
$v = $this->partialLoop()->view; //you choose to assign view data to the partial, and I don't think it's working as expected.
//By not passing any args to the partial you have at least some access to the view object.
$this->view->test = "This works";//assign data to view locally
echo $v->test; // you seem to be echoing out locally assigned data
$v->myArray[] = "hello";//you didn't assign this to the view
echo count($v->myArray); // myArray probably doesn't exist in this context or dosen't work as expected. If you make this an associative array it might work.
I don't think I've ever seen partials used in quite this manner before. The point of the partial is to establish a different variable scope for a specific portion of the view.
The partial and partialLoop are view helpers so the only action you need to take in your controller (data may be or come from a model as well) is to make available any data you want to use in your partials as well as any data you want available in your normal view scope.
//in a controller
public function userAction() {
$model = Application_Model_DbTable_User();//Table columns = id, name, role
$this->view->partailData = $model->fetchAll();//assign data to view that we want to use in partial, should be an array or object.
}
//in a view script
<?php
//pass the path to the partial as the first arg and the data to be displayed as the second arg
echo $this->partialLoop('/path/to/partial.phtml', $this->partialData);
//we could pass data explicitly as well
echo $this->partial('/path/to/partial.phtml', array('id'=>1,'name'=>'jason','role'=>'user'));
?>
//now for our partial.phtml
//this could be used a simple partial or as a partialLoop
<p>My name is <?php echo $this->name ?>.</p>
<p>My data file id is <?php echo $this->id ?>.</p>
<p>My access control role is <?php echo $this->role ?>. </p>
<!-- name, id and role would be column names that we retrieved from the database and assigned to the view -->
To use a partial or partialLoop you need to pass an array of some type or an object that implements toArray().
[EDIT]
Clean up your code your still in left field.
//controller code
$this->view->myArray = array();
//view code
<?php $v = $this->partial()->view ?>
<?php $v->myArray[] = 'newName' ?>
<?php Zend_Debug::dump(count($this->partial()->view->myArray)) ?>
//my output =
int(1)
I don't seem to be able to pass the view any further then this, if I assign to an actual partial script and attempt to output the view object errors are thrown:
//my view again
<?php echo $this->partial('partial.phtml', $this->partial()->view) ?>
//This and attempts similar result in the error
/*Catchable fatal error: Object of class Zend_View could not be converted to string in E:\www\home-local\application\views\scripts\partial.phtml on line 1*/
//when the partial.phtml looks like
<?php echo $this />
//however when I access the data available in the view
<?php echo $this->myArray[0] ?>
//the result works and the output is
newName
it looks like an empty partial() (partialLoop()) call will give you access to the view object, when you already have access to the view object. If you leave the scope of the view object you will have only the access available to your current scope as provided by __get() and __call().
I hope I was able to explain this enough to help.
maybe you cant set the value of $v or the item because its private or static or discarded
also from the code you posted its using recursion which could make it a lot more breakable (ie the controller is referencing the views data, and the view is setting it or hasnt set it or has set it twice)
agreed i dont think accessing view var's from a partialLoop is a good idea.
edit:
$this->view->assign('variablename', $my_array);
I think the variable is otherwise "lost" on the Rerender, so work on your variables in your controller, and before you are done assign them to the view. I wouldn't really do array operations on $this->view->myArray

Query string, populating a page from DB or file

Is this facebook link populated fully from the DB? Or, is it a physical file with PHP in it? Just, how is this page called?
http://www.facebook.com/profile.php?id=49300915&sk=photos
They probably do something like:
if(isset($_GET['id'], $_GET['sk'])) {
mysql_query("SELECT info, photos FROM users WHERE id = '$id'");
}
I'm trying to ask, how do they include this page? Is it like Drupal / any CMS where the PHP and page is stored in the DB, or is it a physical file on the server? If the latter, what's the best way to get the file (case insensitive URL)?
I would have a class with a single method, which reads 'sk' and runs another method, depending on what it's value is.
One method would be 'photos' which would read 'id' and fetch a photo from the database. It would then run another method, displayPage, which will display a page from that data.
The displayPage method takes a "template" filename and an array of variables to provide to the template. It sets up a smarty object, provides the variables, and instructs it to display the template.
Inside the template, I'd include another template for the global header that's on every page in the site, then i'd have the html page content, using smarty to insert dynamic values, then include a global footer.
Note that i've simplified this system a lot. A real page like that would take me a week to write all the code, since a big website does a lot of stuff just to display a simple page (for example: find out if the logged in user actually has access to the page... i don't have access to the example one you gave).
<?php
// profile.php
class ProfileController
{
public function run()
{
if ($_GET['sk'] == 'photos')
return $this->photosPage();
}
protected function photosPage()
{
$id = (int)$_GET['id'];
$result = mysql_query("select * from photo where id = $id");
$photo = mysql_fetch_object($photo);
$this->displayPage('view-photo.tpl', array('photo' => $photo);
}
protected function displayPage($templateFile, $templateVariables)
{
$smarty = new Smarty();
foreach ($templateVariables as $variableName => $variableValue) {
$smarty->assign($variableName, $variableValue);
}
$smarty->display($templateFile);
}
}
$conntroller = new ProfileController();
$controller->run();
And the smarty code:
<!-- view-photo.tpl -->
{include file='head.tpl'}
<h1>View Photo {$photo->name|escape}</h1>
<img src="{$photo->src|escape}" width="{$photo->width|escape} height="{$photo->height|escape}>
{include file='foot.tpl'}

Codeigniter two param database breadcrumb

I am using the php framework codeigniter.
I am attempting to create a here is an example:
animals/feline/lion
animals/feline/tiger
animals/feline/snow-leopard
animals/canine/wolf
animals/canine/coyote
Where both genus (feline) and species (lion) are both retrieved from a database and animals is a controller. I have models that place genus and species in their respective arrays. I also wish to have views for each step along the breadcrumb as follows:
animals
animals/feline
animals/canine
Any help would be greatly appreciated. I just looked at autocrumb and all it was as for displaying the breadcrumb control structure on the view, and not what I want.
I'd use URi routing., as another approach than __remap(), which is better, but I just wanted to give another choice
$route['animals/(:any)/(:any)'] = "animals/method/$1/$2";
In you animals controller you have
function method($genus,$species)
{
$data['breadcrumb'] = 'animals -> '.$genus.' -> '.$species.
$this->load->view('breadcrumb', $data);
$this->load->view('animals/'.$genus.'/'.$species);
}
view breadcrumb.php:
<div id="breadcrumb">
<?php echo $breadcrumb;?> <!-- Display: animals -> feline -> lion -->
</div>
View folder contains:
breadcrumb.php
animals /
feline /
feline.php
canine/
wolf.php
Is this what you were looking for?
EDIT after comments:
SO looks like we've mistaken what you wanted. If you're retrieving those variables from DB, then you could do like this:
function index()
{
$this->load->view('animals/index');
}
function genus($genus)
{
$data['genus_data'] = $this->your_model->load_genus_data($genus);
$this->load->view('animals/genus',$data);
}
function species($genus,$species)
{
$data['genus_data'] = $this->your_model->load_genus_data($genus);
$data['species_data'] = $this->your_model->load_species_data($species);
$this->load->view('animal/genusspecies',$data);
}
In your view genus.php (in folder animal):
<?php $genus_data->name;?> is an animal that...Here's a pic in its habitat.
In your view genusspecies.php (in folder animal):
<?php $species_data->name;?> is a species of genus <?php $genus_data->name;?>....
all those might be html snippets you load from database;
Your routing might look like this then:
$route['animal'] = "animal";
$route['animal/(:any)'] = "animal/genus/$1";
$route['animal/(:any)/(:any)'] = "animal/species/$1/$2";
If I were you, I'll go about this way. Do I got it better or am I still wrong somewhere?
Add a _remap() function to your animals controller
if($this->uri->segment(3) === FALSE)
{
$this->genus();
}
else
{
$this->species();
}
This assumes you have a method called genus() and a method called species()
_remap() docs:
http://codeigniter.com/user_guide/general/controllers.html#remapping
URI Library docs:
http://codeigniter.com/user_guide/libraries/uri.html
redirect('animals/' . $genus . '/' . $species);

View in MVC, what is a layout and how to create one

I dont understand what the layout is, in the view. I asked a question previously on the subject of templating in PHP, but I still dont quite understand. I assume that you create a general layout for the site and then include each specific view within that layout.... I would like to know how to go about doing this. Also, are should the templates be made using just html, because I also looked at these things called helpers.... I'm just confused on the View part of the MVC, and the actual templates and how they're made. I learn best with examples, If you guys have any.
Also, a more important question, lets say I had a form that a user saw only if he was logged in, would I control that in the view, or in the controller?
So Would i do
in the controller
include 'header';
if(isset($_SESSION['userID'])){
include 'form';
}
include 'footer';
or
in the template
<html>
<?php if(isset($_SESSION['user_id'])): ?>
<form>....</form>
<?php endif;?>
</html>
EDIT
So, is there an include statement from within the layout to see the specific view template? how so?
a layout is whatever you have around your main content area. Usually on a normal website it would be any sidebar,header,footer. Most of MVC framework provide the layout to avoid to repeat those parts in all views.
You can imagine if like you have two view cascaded
you actual view is rendered, this content is saved
the layout view (all the items around the content) are rendered and your content is included in that output
for your login question actually your would have to do both
on the controller and the view
$this->view->isLogged = isset($_SESSION['userID']);
in the view
<?php if($isLogged): ?>
<form>....</form>
<?php endif;?>
I hesitate to answer this question only because of the religious fervor that surrounds it.
To get a really good understanding of the issues behind the general concepts see This Wiki Discussion Page This is the discussion page around the wiki MVC article.
Here is the rule of thumb I like to follow (BTW I use CodeIgniter and it kind of sounds like you are too):
The "view" should have virtually no logic. It should only be HTML (in the web world) with peppered PHP that simply echos variables. In your example you would break out the form into its own view and the controller would determine if was loaded or not.
I like to look at it this way: The view should have no concept of where the data comes from or where it is going. The model should be view agnostic. The controller meshes data from the model and provides it to the view - and it takes input from the view and filters it to the model.
Here is a quick and dirty (untested - but it should get the point across) example:
Theapp.php (The App controller)
class Theapp extends Controller
{
var $_authenticated;
var $_user;
var $_menu; // array of menus
function __construct()
{
session_start();
if (isset($_SESSION['authenticated']) && $_SESSION['authenticated'])
{
$this->_authenticated = $_SESSION['authenticated']; // or some such thing
$this->_user = $_SESSION['user'];
}
$this->_menu = array("Logout", "Help", "More");
parent::__construct();
$this->loadView("welcome"); // loads primary welcome view - but not necessarily a complete "html" page
}
function index()
{
if (!$this->_authenticated)
$this->loadView("loginform");
else
{
$viewData['menu'] = $this->_menu;
$viewData['user'] = $this->_user;
$this->loadView("menu", $viewData);
}
}
function login()
{
/* code to authenticate user */
}
function Logout() { /* code to process Logout menu selection */ }
function Help() { /* code to process Help menu selection */ }
function More() { /* code to process More menu selection */ }
}
welcome.php
<h1> Welcome to this quick and dirty app!</h1>
All sorts of good HTML, javascript, etc would be put in here!
loginform.php
<form action"/Theapp/login" method="post">
User: <input id='user' name='user'>
Pass: <input id='pass' name='pass' type='password'>
<input type='submit'>
</form>
menu.php
Hi <?= $user ?>!<br>
Here's your menu<br>
<? foreach ($menu as $option) { ?>
<div class='menuOption'><a href='/Theapp/<?=$option?>'><?=$option?></a></div>
<? } ?>
Hope this helps.
If your not using a framework, then a simple way to have a layout and a view can be like so:
<?php
function layout($layout_params) {
extract($layout_params);
# Remember: $layout_content must be echoed for the view to be seen.
ob_start();
include "layout_page.php";
$html = ob_get_contents();
ob_end_clean();
return $html;
}
function view($view_params) {
extract($view_params);
ob_start();
include "home_page.php";
$html = ob_get_contents();
ob_end_clean();
return $html;
}
#
# The variable $parameters is extracted and $params becomes a variable in the view as an array,
# $logged_in is also now avaiable in the view
#
$parameters = array("params" => array("name" => "joe"), "logged_in" => false);
$view_content = view($parameters); # => Returns the HTML content for home_page.php
# Now we need the layout content to include the view:
# The layout file will expect a variable called $layout_content to be the html view.
# So we need to set $layout_content to be $view_content
$parameters["layout_content"] = $view_content;
# We no longer need $view_content so we can unset the variable
unset($view_content);
# When $paramters is extracted it will have $layout_content as a variable:
$layout_content = layout_view($paramters); # => Returns the HTML content for the layout_page.php
# Now send the results to the browser
echo $layout_content;
?>

Categories