Inspired from the other community wikis, I'm interested in hearing about the lesser known Kohana tips, tricks and features.
- Please, include only one tip per answer.
- Add Kohana versions if necessary.
This a community wiki.
Inspired from the other community wikis, I'm interested in hearing about the lesser known Kohana tips, tricks and features.
This a community wiki.
Checking for an internal request (Kohana 3)
if (Request::instance() !== $this->request)
{
print 'Internal called made with Request::factory';
}
Adding additional data to pivot tables using ORM (Kohana 3)
ORM's add
function accepts a third parameter where you can specify additional data to be saved on the pivot table.
For example, if a User has_many Roles and a Role has_many Users (through a table named roles_users
), you can save information to the date_role_added
column on that table:
$user->add('role', $role, array('date_role_added' => $today_date));
The difference between this->request->route->uri()
and this->request->uri()
(Kohana 3)
// Current URI = welcome/test/5
// Using default route ":controller/:action/:id"
// This returns "welcome/test/5"
echo $this->request->uri();
// This returns "welcome/test1/5"
echo $this->request->uri(array( 'action' => 'test1' ));
// This returns "welcome/index"
echo $this->request->route->uri();
// This returns "welcome/test1"
echo $this->request->route->uri(array( 'action' => 'test1' ));
As you can see, $this->request->route->uri() uses current route defaults (id is null), while $this->request->uri() applies current uri segments.
Instead of writing a link like so
<a href="<?php echo URL::base(); ?>hello/path/somearg/">link</a>
You can call the route by name (from bootstrap.php) and echo the link.
<a href="<?php echo URL::base() . Route::get('route_name')->uri(array('arg' => 'somearg')); ?>">link</a>
And here would be the route in application/bootstrap.php
for reference
Route::set('route_name', 'hello/path/<arg>')
->defaults(array(
'controller' => 'home',
'action' => 'index'
));
Generating Form::select() options from database resultset
$options = ORM::factory('model')
->order_by('title','ASC')
->find_all()
->as_array('id','title');
$select = Form::select('select_name',$options,$val);
If you want to add a 0 value option, do:
$options = Arr::merge(array(0 => 'Select some option'), $options);
or
$options = array(0 => 'Select some option') + $options;
Detect ajax request and deactivate autorendering
// Somewhere in your controller before-method
$isAjax = preg_match("/ajax/", $this->request->action);
if($isAjax) {
if(!Request::is_ajax()) {
die("Not allowed.");
}
$this->autoRender = false;
}
// Some ajax action-method
public function action_ajaxDoSth()
{
// return json or do sth. else
}