Tip On Adding Code To Drupal Forms

Saturday, April 7, 2012 - 03:24

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
2
<?php 
return mymodule_afunction/();

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

1
2
3
function mymodule_afunction() {
        return //code;
}

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.

Category: 
Tags: 
philipnorton42's picture

Philip Norton

Phil is the founder and administrator of #! code and is an IT professional working in the North West of the UK.
Google+ | Twitter

Add new comment