I'm making a website with categories and products. The categories and the products are both contenttypes. Categories can't be a taxonomy type because the editor of the website has to change data for the categories. To solve this problem i created a custom routing:
products:
path: /{catslug}/{slug}
defaults: { _controller: 'Bolt\Controllers\Frontend::record', contenttypeslug: 'products' }
requirements:
catslug: 'Bolt\Controllers\Routing::getAnyCategorieRequirement'
I added a function in Routing.php (I will later move it to an extension):
public function getAnyCategorieRequirement()
{
$slugs = array();
foreach($this->app['storage']->getContent("categories") as $cat){
$slugs[] = $cat['slug'];
}
return implode("|", $slugs);
}
But then I bumped into a problem:
Accessed request service outside of request scope. Try moving that call to a before handler or controller.
So I temporarily commented out the database request and added a default slug to $slugs:
public function getAnyCategorieRequirement()
{
$slugs = array();
$slugs[] = "hollandse-kazen";
return implode("|", $slugs);
}
This way everything worked as expected. Now my question: How can I do this database request in the routing controller, or is there a workaround for this problem?
Ross Riley's first solution worked for me:
$slugs = array();
//Do complicated request because of [url to stackoverflow]
$stmt = $this->app['db']->query('SELECT slug FROM bolt_categories');
while($cat = $stmt->fetch()){
$slugs[] = $cat['slug'];
}
return implode("|", $slugs);
This way it works as expected:)
This is unfortunately a known issue with Bolt's getContent() method that depends on being in the request loop, as discussed here: https://github.com/bolt/bolt/issues/2129
The two ways around it are to use $app['db'] to make a raw query to the db, rather than using getContent()
The other is to temporarily overwrite $app['request'] to allow it to work. Something like this will do the job.
use Symfony\Component\HttpFoundation\Request;
.....
$oldRequest = $app['request'];
$app['request'] = Request::createFromGlobals();
....
<do database call here>
....
$app['request'] = $oldRequest;