Tip On Adding Code To Drupal Forms

7th April 2012 - 2 minutes read time

There are various different forms and modules in Drupal that allow for PHP code to be embedded into them. I have even talked about adding PHP code to forms in a previous post. These form elements can have their uses, modules like Views allow for PHP code to be run when collecting arguments which can allow for some advanced funcationality.

However, it can lead to problems. The code in the form is essentially outside of source control which means that anyone can mess about with the code and there is no way to revert changes or get back the code if the form save action failed for whatever reason.

One useful tip when using this functionality is to create a function that will run the needed code and then reduce the code entered into the form into a single return call. As an example, you would enter the following into the PHP code form.

  1. <?php
  2. return mymodule_afunction/();

And then add the following to a module so that the function is accessible to the form code:

  1. function mymodule_afunction() {
  2. return;
  3. }

This means that the mymodule_afunction() function is now in source control, and any changes we need to make to the function can be done within in code, rather than within the form.

Thanks goes to Thomas Davis (@TEDavis) for telling about this tip at a the last NWDUG meetup.

Add new comment

The content of this field is kept private and will not be shown publicly.