Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Favourite Kohana Tips & Features? [closed]

Generating Form::select() options from database result

Kohana 3.1 and 3.0

$options = ORM::factory('model')
 ->order_by('title','ASC')
 ->find_all()
 ->as_array('id','title');

$select = Form::select('name', $options);

It should be noted this is not restricted to the ORM and can be used on all database results (they all support as_array). See the database results information for more details.

If you want to add a default option:

$options = Arr::merge(array('Please select a value.'), $options);

Show last query executed

Kohana 3.1 and 3.0

echo Database::instance()->last_query

Taken from In Kohana 3, how do you figure out errors made during a query?.


Set Kohana::$environment

Paste these lines to your .htaccess:

SetEnvIf SERVER_ADDR "^(127\.0\.0\.1|::1)$" KOHANA_ENV=development
SetEnvIf SERVER_ADDR "^((?!127\.0\.0\.1|::1).)*$" KOHANA_ENV=production

now, if you're on localhost, you are in development mode, otherwise you're in production mode

Edit: Added support for IPv6


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.


Add data to pivot tables using ORM

ORMs add function accepts a third parameter where you can specify additional data to be saved on the 1pivot table1.

For example, if a user has many roles and a role has many users (through a table named 1roles_users1), you can save information to the 1pivot table1 by passing an array of column keys and data values as the 3rd argument to the add method.

Kohana 3.1

Not supported. The alternative would be to load the pivot table and add the data as you would with any other table.

Kohana 3.0

$user->add('role', $role, array('date_role_added' => time()));

where $role is ORM::factory('role', array('name' => 'user'));


Turn off auto_rendering for AJAX requests

These code samples assume you're extending from the template controller.

Kohana 3.1

public function before()
{
    parent::before();

    if (Request::current()->is_ajax())
    {
      $this->auto_render = FALSE;
    }
}

Kohana 3.0

public function before()
{
    parent::before();

    if (Request::$is_ajax)
    {
      $this->auto_render = FALSE;
    }
}