7

I have tried to create custom tables for a module in Drupal via hook_install() and hook_schema() in module.install, and it works fine after disabling and enabling module using drush dre module_name. Is that the proper way to create tables in custom module ?

Can I use config/schema/module_name.schema.yml for creating tables? If not, what is the use of schema files in Drupal 8?

3 Answers 3

9

hook_schema() is not used differently from how it was used on Drupal 7, the only difference is that it is not used to create database tables for entities. See, for example, node_schema(), which doesn't define the table used for the Node entity (the node table).
In particular, you don't need to call drupal_install_schema()) in hook_install() to create custom database tables, which was instead necessary in Drupal 6.

.schema.yml files (for example, user.schema.yml) are used to define the schema for the module configuration files. Their purpose is different from defining a database table schema, and they cannot be used for that.

3

For a database table, you use hook_schema to define it and if the module already exists, you can use hook_update to create the table manually as it hook_schema is only triggered during installation.

This is all like you describe.

The schema config is not used to create database tables, instead it's use to define the schema of configs. Basically you use it to explain the structure of configs your module will save, data types etc. I don't know what actually uses this as most things will work without it.

1
  • 1
    Not so sure anymore, newer releases seem to require schema.yml - particularly for exporting and being a test dependency. A lot of contrib modules have had issues in the last 3 months needing to provide it because it was causing fatal errors.
    – Kevin
    Feb 22, 2017 at 14:06
2

The two 'schema' have different contexts.

Your assertion of creating database tables is correct.

schema.yml files serve another purpose. From the docs:

Using the knowledge embedded in the configuration schemas about what is stored of a configuration entity, the default persistence implementation for configuration entities requires a configuration schema for the configuration entity, so the right properties are exported with the types defined. Although it is better to provide configuration schemas, if you really don't want, implement the toArray() method in your configuration entity implementation to not require schema for saving configuration entities of your type.

And that is just one reason. See: https://www.drupal.org/docs/8/api/configuration-api/configuration-schemametadata#use

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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