Drupal7: Tip On Adding Code To Drupal Forms

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.

<?php 
return mymodule_afunction/();

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

function mymodule_afunction() {
	return;
}

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.
CAPTCHA
4 + 6 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.