Version 11, last updated by fonny at 23 Mar 22:16 UTC
Code snippets
How do I retrieve the id of an item after an add action
The 'add' action in the controller triggers an insert operation on the database. If the database table you are inserting into has an autoincrement id you can retrieve this id from the KDatabaseRow object after it's saved. There are a couple of ways to do this. Here are three examples :
1. In the controller add action
Here we override the controllers 'add' action to retrieve the id and do something with it. This is the easiest way using inheritance.
class ComHarbourControllerBoat extends ComDefaultControllerView
{
protected function _actionAdd()
{
//parent action will call KControllerBread::_actionAdd, and returns the saved $row object
$row = parent::_actionAdd();
//retrieve the row id
$row->id;
}
}
2. In a controller, by registering an after action function
For example, suppose you register a controller function to be triggered after add and you want to use the id. In this case we use the registerFunctionAfter, which registers a function, in this case 'afterAdd' to be triggered after the the add action has been executed.
class ComHarbourControllerBoat extends ComDefaultControllerView
{
public function __construct(KConfig $config)
{
parent::__construct($config);
$this->registerFunctionAfter('add' , 'afterAdd');
}
public function afterAdd()
{
//get the newly added boat
$boat = KService::get($this->getModel())->getItem();
$id = $boat->id;
}
}
3. Advanced : In a controller after action function
This is the same as above, only difference is that we are now retrieving the id from the command chain context object instead of from the model. This is a more advanced example.
The afterAdd function is triggered by a special command, when the chain is running the context is stored and can be retrieved from the outside. This makes it possible to change the context.
class ComHarbourControllerBoat extends ComDefaultControllerView
{
public function __construct(KConfig $config)
{
parent::__construct($config);
$this->registerFunctionAfter('add' , 'afterAdd');
}
public function afterAdd()
{
$row = $this->getCommandChain()->getContext()->result;
//retrieve the row id
$row->id;
}
}
How to create a user Select List
Integrating in to Joomla! often requires a select list of Joomla! users. This is a helper snippet that generates it for you.
public function users($name, $selected)
{
$users = KService::get('com://admin/users.model.users')->getList();
$attribs = array('class' => 'inputbox', 'size' => '1')
return KTemplate::loadHelper('select.genericlist', $users, $name, $attribs, 'id', 'username', $selected);
}