Using PHP On Drupal Settings Pages

Bevan Rudge

on

November 11, 2008

Using PHP On Drupal Settings Pages

It is generally recognized that CMSes are about separating the content from it's appearance and the logic that manipulates the content. In Drupal, it is good practice to maintain code in files which can be version-controlled (with subversion for example), and keep just the dynamic content and data in the database. In other words, executable code should not go in the database. In some cases the only way to configure certain things (such as block display settings and special views argument handlers) is to use PHP in a textarea on the settings form. The cleanest way to handle this in Drupal is to put your logic into a function in a custom module. E.g.;
<?php
 
// Block display settings for the foobar block.  See admin/build/block/mymodule/foobar
 
function mymodule_foobar_block_display_settings() {
    global
$foo;
   
$bar = FALSE;
    if (
$foo) {
     
$bar = TRUE;
    }
    return
$bar;
  }
?>
And then call that function from the textarea. E.g.; return mymodule_foobar_block_display_settings(); This allows us to put as little PHP code as possible into the database, while still version-controlling the logic and making it easily grepable and debuggable. Don't forget to clearly document what URL has the settings for each function so that a developer can find it in Drupal's settings. For added cushioning and coding for errors, you should wrap the function call in if function_exists(FUNCTIONNAME) or if (module_exists(MODULENAME)). This will avoid fatal PHP errors (WSODs) if the module is moved to a different directory or the function is renamed. On the other hand, it might be useful to know when something has broken! This approach would need a little more PHP in the textarea; if function_exists('mymodule_foobar_block_display_settings') { return mymodule_foobar_block_display_settings(); }

Share it!