3

Learning how to create plugins. I want to do a select query in an existing table in the Craft database, build navigation HTML and then return that HTML using a variable. I can see how to set up my own variable using the *Variable.php file. In the docs I don't see how querying database tables is done with any of the sections of the plugin found here.

I am guessing that I would use a class in the Craft classes?

If so then...

Do I put my logic for querying the table in my method to return the variable value, in my primary plugin class or somewhere else?

Which classes would I use?

3

A great place to start with this is over on https://pluginfactory.io/.

Select "Craft CMS Plugin Version 3.x" and check any plugin components you'd like to include, and it will build out the plugin scaffolding for you with ample comments and some examples.

For accessing database content, Craft heavily relies on the framework it uses, Yii 2. The "Working with Databases" docs are a good place to start: https://www.yiiframework.com/doc/guide/2.0/en/start-databases#working-with-databases

It will go over how to retrieve data using Active Record (Craft's AR classes) and Query Builder for direct database access.

You can do that data access from your plugin's Variable class, but a more common pattern is for the Variable class to have a wrapper method that calls a Service class method that returns the value to the Variable, then back to the template.

You can see Craft's Service classes here: https://github.com/craftcms/cms/tree/develop/src/services

And in case it's not obvious yet, the Craft source code itself is a great place to look for examples of how to do things in your plugin.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.