2

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:)

1 Answers1

0

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;
Ross Riley
  • 826
  • 5
  • 8
  • Aah, thanks for your answer:) I had already given up hope for an anwser:) The fix with "temporarily overwriting the request didn't work though... I am now trying the raw query solution –  Sep 03 '15 at 20:30
  • Great, the first method worked fine! Thanks. But you should review the 2nd method:) –  Sep 03 '15 at 20:39