Create a custom table and define various fields in it using
This blog post is in continuation with the previous blog post.
To manage blocks’ visibility we need to have parameters that would determine whether a block would be visible or not. The parameters that we need to set when we create or edit a block are:
- Pages : to restrict blocks' visibility on certain pages.
- Content Types : to restrict blocks' visibility on certain content types.
- Roles : to restrict blocks' visibility for certain user roles.
- Users : to allow per user customizations for blocks.
These parameters are available out of the box in any drupal site. To create custom parameters refer to this blog post.
We need to save these parameters/configurations into the database in a custom table. To create a custom table we can use
hook_schema() takes care of the table creation and deletion at the time of module installation and un-install respectively. In the following code, I’ve created a custom table named
block_date inside the
hook_schema() in the my_module.install file. Read more about hook_schema() here and .install files here.
'fields' is an array of fields. So the table
block_date would be created when we install our module and it would have the above defined fields.
So we have our custom table created and data would be queried into it when a block is edited or a new block is created. The code for the database query would look like this:
This is to be put inside the submit handler of the form we altered using
hook_form_FORM_ID_alter() in the previous blog post so that the query runs when the form is submitted after some validations, of course.
Duh! We have a problem there, Know what?
If we edit a block whose visibility parameters are already set, and we happen to change the parameters and submit the form again, we would be querying into the database two different parameters of visibility for the same block. And that, sure as hell, is a problem.
To avoid this we would need to delete the previously set parameters for that block from the database. To do that we use the following query before inserting new data into the database in the submit handler of the
So now we have a block created or edited and the parameters collected from it and stored into a custom table in our database. Now we need to use these parameters to determine blocks’ visibility. I would be writing another blog post to explain how to use these parameters to manage a block’s visibility.
Stay tuned!comments powered by Disqus