Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
<?php
/**
a. Embedding the user ID as a query string variable seems like a bad idea. I assume you’re using that to set a model state when you do your browse page. Here is what I would do:
1) create a settings controller if you haven’t already
2) depending upon which actions you need the user id set for, I would either set it as a model state in the controller constructor if you need user id set for all actions:
**/
public function __construct(ObjectConfig $config)
{
parent::__construct($config);
$this->getRequest()->query->set(‘user_id’, $this->getUser()->id );
}
/**
There alternative approaches to the above, you could set the user_id directly on the model as shown below, but this means the model will be loaded in the constructor when it may not be needed.
Or if you need it for specific actions, register a before callback for specific actions
**/
public function __construct(ObjectConfig $config)
{
parent::__construct($config);
$this->registerCallback(‘before.browse’, array($this, ’setUserId’);
$this->registerCallback(‘before.read’, array($this, ’setUserId’);
}
public function setUserId(ControllerContextInterface $context)
{
$this->getModel()->user_id( $this->getUser()->id );
}
/**
b) This is a prime example of when to use a callback, you want to check the result set after browse and redirect if necessary
**/
public function __construct(ObjectConfig $config)
{
parent::__construct($config);
$this->registerCallback(‘after.browse’, array($this, ’redirectOnOne’);
}
public function redirectOnOne(ControllerContextInterface $context)
{
if($context->result->count() == 1)
{
$context->response->setStatus(DispatcherResponse::FOUND);
$context->response->setRedirect($this->getObject('lib:dispatcher.router.route', array(‘url=> ‘?option=com_myapp&view=part&id=.$context->result->top()->id));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.