Search code examples
phpbolt-cms

How to run custom PHP code in Bolt CMS?


What I want to do is have one page that lists some data from my database (the data is separate from Bolt).

I've looked into extensions but I don't see any way to make a "page" as such, only create "snippets". But snippets don't display actually in the content area, you can only add them right after the <body> tag or in the <head>. Also it looks like they appear on every page, not on page.

Is it possible to run some custom PHP code on a page to fetch some data from a database and display it? Does anyone have a bare-bones example?


Solution

  • This is the sort of thing that extensions are for, but snippets are not what you want.

    Bolt is a Silex application and comes with a Doctrine DBAL provider, so you can just use $app['db'] to give you access to the \Doctrine\DBAL\Connection object that you can use to query your table, e.g.

        $resultArray = $this->app['db']->createQueryBuilder()
            ->select('*')
            ->from($tableName)
            ->where('my_column_1  = :my_column_value_1')
            ->andWhere('my_column_2  = :my_column_value_2')
            ->orderBy('my_column_3', 'DESC')
            ->setParameter(':my_column_value_1', $value1)
            ->setParameter(':my_column_value_1', $value2)
            ->execute()
            ->fetch(\PDO::FETCH_ASSOC);
    

    You can then do what you want with the data, and render that in Twig as you see fit.

    There is a tonne of documentation on creating extensions with Twig functions that you can put in a template {{ my_twig_function() }}