Reputation: 28803
I have the following code:
function search_reset ()
{
$search_query = $_GET['q'];
if($search_query)
{
echo $this->Html->link('Clear', array('controller' => 'home', 'action' => 'index'), array('title' => 'Clear search query'));
}
}
But it causes the following error: Fatal error: Using $this when not in object context in /Users/cameron/Sites/smplr/app/views/search/index.ctp on line 9
I have two questions:
1.) What do I use INSTEAD of $this
when inside a function?
2.) Where would I put a custom function like this? As I can't put it inside my controller as it's NOT an action.
Upvotes: 2
Views: 4176
Reputation: 11574
@Cameron, Here is how you make this available site wide. First, create your custom helper and put it in the views/helpers/ directory as search_reset.php
<?php
class SearchResetHelper extends AppHelper {
var $helpers = array('Html'); // include the HTML helper
/**
* @param string $query, This is the search query you will pass from the view
*/
function reset_link($query = null) {
if($query == null) {
return;
}
if(!empty($query)) {
return $this->Html->link('Clear', array('controller' => 'home', 'action' => 'index'), array('title' => 'Clear search query'));
}
}
}
Now, in your controller, make sure you include this in the $helpers array at the top:
var $helpers = array('SearchReset','any','other','helpers');
Now in your view, you simple call:
<?php echo $this->SearchReset->reset_link($_GET['q']); ?>
Then you will get the link as needed. It will work in any view as long as you call the helper in the controller.
Happy Coding!
Upvotes: 4
Reputation: 522135
I'm looking to make these functions accessible SITE-WIDE any ideas on how I could this?
Create your own Helper or add it as a method in the AppHelper.
Upvotes: 4
Reputation: 8086
Since it's in your ctp, you have access to it directly (without $this). You should just be able to write a function in your template and include as a global:
function search_reset ()
{
global $html;
$search_query = $_GET['q'];
if($search_query)
{
echo $html->link('Clear', array('controller' => 'home', 'action' => 'index'), array('title' => 'Clear search query'));
}
}
To include html helper in your app controller:
class AppController extends Controller {
public function constructClasses(){
//Apply App helpers and merge with controller helpers
$helpers = array('Html','Javascript' /*add whatever you want, these are global*/);
//merge global, controller helpers
$this->helpers = array_merge($this->helpers, $helpers);
parent::constructClasses();
}
}
The above code will merge the helpers specified there with any other helpers specified in your controller. Then you can use $html helper in any ctp file.
Upvotes: -1