CakePHP 2 accessing variable defined in the view - php

In both cakephp-1.2 and cakephp-1.3 I have used the following code snippet in an element named head called from the blog layout:
$this->preMetaValues = array(
'title' => __('SiteTitle', true).' '.$title_for_layout,
'desc' => Configure::read('siteTitle').', '.Configure::read('siteSlogan'),
'keywords' => Configure::read('keywords'),
'type' => 'article',
'site_name' => __('SiteTitle', true),
'imageURL' => $html->url('/img/logo.png', true)
);
if(!isset($this->metaValues)){
$this->metaValues = $this->preMetaValues;
}
else{
$this->metaValues = array_merge($this->preMetaValues, $this->metaValues);
}
<?php echo $html->meta('description',$this->metaValues['desc']); ?>
<?php echo $html->meta('keywords', $this->metaValues['keywords']);?>
I used the above code to define or modify meta-tags values from the any view file. The preMetaValues is regarded as the default values. If there is any metaValues defined in the view, this code will modify it and make the metaValues ready to be used.
Now with cakephp-2.4, the described code generates the following error:
Helper class metaValuesHelper could not be found.
Error: An Internal Error Has Occurred.
Indeed, I don't know why CakePHP regards this variable as helper? and how could I fix this issue?

You can do it by setting the variable from your controller action:
$this->set('title_for_layout', 'Your title');
And then in the view, printing it with:
<title><?php echo $title_for_layout?></title>
You have an example of this at the documentation:
http://book.cakephp.org/2.0/en/views.html#layouts
Just treat them as any other variable.

Why you're using $this object? Can't you use a simple solution like this:
$preMetaValues = array(
'title' => __('SiteTitle', true).' '.$title_for_layout,
'desc' => Configure::read('siteTitle').', '.Configure::read('siteSlogan'),
'keywords' => Configure::read('keywords'),
'type' => 'article',
'site_name' => __('SiteTitle', true),
'imageURL' => $html->url('/img/logo.png', true)
);
if(!isset($metaValues)){
$metaValues = $preMetaValues;
}
else{
$metaValues = array_merge($preMetaValues, $metaValues);
}
<?php echo $html->meta('description',$metaValues['desc']); ?>
<?php echo $html->meta('keywords', $metaValues['keywords']);?>

Finally I have found the solution. It is simply about how to set a variable for the layout from a view. It seems that in earlier versions of cakephp the view was processed before the layout while now in cakephp-2.4 the layout is processed first, so any override of any variable defined in the layout from the view will not success.
Hence, the solution will depend on the set method of the view object something as follows:
//in some view such as index.ctp
$this->set('metaValues', array(
'title', 'The title string...',
'desc' => 'The description string...'
)
);
Also as Alvaro regarded in his answer, I have to access those variable without $this, i.e as local variables.
This answer is inspired from: Pass a variable from view to layout in CakePHP - or where else to put this logic?

Related

CodeIgniter loading a view into a view

I need to load a view into a view within CodeIgniter, but cant seem to get it to work.
I have a loop. I need to place that loop within multiple views (same data different pages). So I have the loop by itself, as a view, to receive the array from the controller and display the data.
But the issue is the array is not available to the second view, its empty
The second view loads fine, but the array $due_check_data is empty
SO, I've tried many things, but according to the docs I can do something like this:
Controller:
// gather data for view
$view_data = array(
'loop' => $this->load->view('checks/include/due_checks_table', $due_check_data, TRUE),
'check_cats' => $this->check_model->get_check_cats(),
'page_title' => 'Due Checks & Tests'
);
$this->load->view('checks/due_checks',$view_data);
But the array variable $due_check_data is empty
I'm just getting this error, saying the variable is empty?
Message: Undefined variable: due_check_data
You are passing the $view_data array to your view. Then, in your view, you can access only the variables contained in $view_data:
$loop
$check_cats
$page_title
There is no variable due_check_data in the view.
EDIT
The first view is contained in the variable $loop, so you can just print it in the second view (checks/due_checks):
echo $loop;
If you really want to have the $due_check_data array in the second view, why don't you simply pass it?
$view_data = array(
'loop' => $this->load->view('checks/include/due_checks_table', $due_check_data, TRUE),
'check_cats' => $this->check_model->get_check_cats(),
'page_title' => 'Due Checks & Tests',
'due_check_data' => $due_check_data
);
$this->load->view('checks/due_checks',$view_data);
Controller seems has no error. Check out some notices yourself:
<?=$due_check_data?>
This only available in PHP >= 5.4
<? echo $due_check_data; ?>
This only available when you enable short open tag in php.ini file but not recommended
You are missing <?php. Should be something like this
<?php echo $due_check_data; ?>
OK, i managed to solve this by declaring the variables globally, so they are available to all views.
// gather data for view
$view_data = array(
'due_check_data' => $combined_checks,
'check_cats' => $this->check_model->get_check_cats(),
'page_title' => 'Due Checks & Tests'
);
$this->load->vars($view_data);
$this->load->view('checks/due_checks');

Yii php: Displaying a widget in a Tab

i've been using Yii framework for some time now, and i've been really having a good time especially with these widgets that makes the development easier. I'm using Yii bootsrap for my extensions..but i'm having a little trouble understanding how each widget works.
My question is how do i display the widget say a TbDetailView inside a tab?
i basically want to display contents in tab forms..however some of them are in table forms...some are in lists, detailviews etc.
I have this widget :
$this->widget('bootstrap.widgets.TbDetailView',array(
'data'=>$model,
'attributes'=>$attributes1,
));
that i want to put inside a tab
$this->widget('bootstrap.widgets.TbWizard', array(
'tabs' => $tabs,
'type' => 'tabs', // 'tabs' or 'pills'
'options' => array(
'onTabShow' => 'js:function(tab, navigation, index) {
var $total = navigation.find("li").length;
var $current = index+1;
var $percent = ($current/$total) * 100;
$("#wizard-bar > .bar").css({width:$percent+"%"});
}',
),
and my $tabs array is declared like this :
$tabs = array('studydetails' =>
array(
'id'=>'f1study-create-studydetails',
'label' => 'Study Details',
'content' =>//what do i put here?),
...
...);
when i store the widget inside a variable like a $table = $this->widget('boots....);
and use the $table variable for the 'content' parameter i get an error message like:
Object of class TbDetailView could not be converted to string
I don't quite seem to understand how this works...i need help..Thanks :)
You can use a renderPartial() directly in your content, like this:
'content'=>$this->renderPartial('_tabpage1', [] ,true),
Now yii will try to render a file called '_tabpage1.php' which should be in the same folder as the view rendering the wizard. You must return what renderPartial generates instead of rendering it directly, thus set the 3rd parameter to true.
The third parameter that the widget() function takes is used to capture output into a variable like you are trying to do.
from the docs:
public mixed widget(string $className, array $properties=array ( ), boolean $captureOutput=false)
$this->widget('class', array(options), true)
Right now you are capturing the object itself in the variable trying to echo out an object. Echo only works for things that can be cast to a string.

CodeIgniter - How to nest a view in view using second controller

So I have this part in my View:
<body>
<div id = "content">
<?php echo $catalog ?>
</div>
</body>
There are also other variables in it. Here is the part of my Controller where I send them to the View:
$this->load->view('layout',array(
'categories' => $categories,
'home_menu' => $home_menu,
'information' => $information,
'favourite' => $favourite,
'new_products' => $new_products,
'bestsellers' => $bestsellers,
'login_info' => $login_info,
'catalog' => ''
));
I want to create second controller, which when activated sends a second view to the variable $catalog.
Something like this (similar to Kohana):
$this->layout->catalog = $this->load->view('products/catalog', array(
'name' => $name,
'description' => $description));
But it's not working.
My question is, how can I show this second nested view after clicking on a link that activates the second Controller?
EDIT:
But I want to send the catalog view to $catalog variable after the user has clicked on a link that activates second controller, which look something like this:
$products = $this->Product_model->list_products($category_id);
foreach ($products as $row)
{
$name = $row->name;
$description = $row->description;
}
.. after that I want $name and $description to be passed to:
$this->load->view('products/catalog', array(
'name' => $name,
'description' => $description));
..which itself to be passed to $catalog in the layout view defined in the first controller
You can call a $this->load->view within the view's code but I would not recommend it.
Instead pass true as the 3rd parameter in the load view function and this will return the view rather than echo it straight out. Then you can assign that returned code to your original view.
I'm hoping I'm understanding your question fully, but if not, I apologize.
My guess is that you're loading the page with all of the 'extras' and want to be able to update the 'content' part of your page through a user initiated click.
If you're implementing a javascript based solution, then you just need a controller that will output the html fragment and inject that into the current page via an ajax call.
If you're not implementing javascript, then it would be an entire page refresh, so you would just rebuild the page and pass the selected catalog content to the controller.
UPDATE
To do this without ajax or hmvc, you need to get the contents from another controller into this controller, so you could just make an additional request with php:
$catalog_content = file_get_contents('/url_to_second_controller.html');
$this->load->view('layout',array(
'categories' => $categories,
'home_menu' => $home_menu,
'information' => $information,
'favourite' => $favourite,
'new_products' => $new_products,
'bestsellers' => $bestsellers,
'login_info' => $login_info,
'catalog' => $catalog_content
));

CakePHP requestAction() alternative option w/ element

I am in a situation where I am trying to pass a value from a controller action to an element directly.
The only way I know how to do this is with requestAction(), but I don't like using that feature for resource reasons and its not recommended in the manual.
Can anyone shed some light on another method?
Here is what I have now:
Bird Controller action:
function element_array_pass() {
$this->paginate['Bird'] = array(
'fields' => array('id', 'name'),
'contain' => array('id', 'name'),
'order' => 'Bird.id'
);
$bird_elmnt = $this->paginate('Bird');
$this->set(compact('bird_elmnt', $bird_elmnt));
}
dir: views/elements/element_array_pass.ctp
debug($bird_elmnt); // nothing being passed here.
dir: views/birds/index.ctp
I include the element in this file, but the array will not pass.
echo $this->element('element_array_pass',array("bird_elmnt" => $bird_elmnt)); // call to element.
I would like to include this element in my index.ctp with values passed from the action() I included above.
echo $this->element('birds_paginator_element',array('bird_elmnt_var'=>$bird_elmnt_var));
You are able to pass additional data to an element through the 2nd argument of the element() method.
echo $this->element('birds_paginator_element', array(
'bird_elmnt_var' => $bird_elmnt
));
// In element
var_dump($bird_elmnt_var);
Also have a read of this article from Mark Story.

CodeIgniter - Variable scope

I have a controller which I use for a login form. In the view, I have a {error} variable which I want to fill in by using the parser lib, when there is an error. I have a function index() in my controller, controlled by array $init which sets some base variables and the error message to '':
function index()
{
$init = array(
'base_url' => base_url(),
'title' => 'Login',
'error' => ''
);
$this->parser->parse('include/header', $init);
$this->parser->parse('login/index', $init);
$this->parser->parse('include/footer', $init);
}
At the end of my login script, I have the following:
if { // query successful }
else
{
$init['error'] = "fail";
$this->parser->parse('login/index', $init);
}
Now, of course this doesn't work. First of all, it only loads the index view, without header and footer, and it fails at setting the original $init['error'] to (in this case) "fail". I was trying to just call $this->index() with perhaps the array as argument, but I can't seem to figure out how I can pass a new $init['error'] which overrides the original one. Actually, while typing this, it seems to impossible to do what I want to do, as the original value will always override anything new.. since I declare it as nothing ('').
So, is there a way to get my error message in there, or not? And if so, how. If not, how would I go about getting my error message in the right spot? (my view: {error}. I've tried stuff with 'global' to bypass the variable scope but alas, this failed. Thanks a lot in advance.
$init musst be modified before generating your view.
To load your header and footer you can include the following command and the footer's equivalent into your view.
<?php $this->load->view('_header'); ?>
to display errors, you can as well use validation_errors()
if you are using the codeigniter form validation.
if you are using the datamapper orm for codeigniter you can write model validations, and if a query fails due to validation rule violation, you get a proper error message in the ->error property of your model.
Code for your model:
var $validation = array(
'user_name' => array(
'rules' => array('required', 'max_length' => 120),
'label' => 'Name'
)
);
You might try this:
function index() {
$init = array(
'base_url' => base_url(),
'title' => 'Login',
'error' => ''
);
$string = $this->parser->parse('include/header', $init, TRUE);
$string .= $this->parser->parse('login/index', $init, TRUE);
$string .= $this->parser->parse('include/footer', $init, TRUE);
$this->parser->parse_string(string);
}
In parse()you can pass TRUE (boolean) to the third parameter, when you want data returned instead of being sent (immediately) to the output class. By the other hand, the method parse_string works exactly like `parse(), only accepts a string as the first parameter in place of a view file, thus it works in conjunction.

Categories