When working with objects, how do you pass a method to the FormAPI's ['#after_build'] feature?

For example, how can I pass $myObject->_my_after_build_function to ['#after_build']?

Non-OOP exampe of what I would like to accomplish:

$form['#after_build'][] = '_my_after_build_function';

$form['#after_build'] is handled from the following code, contained in form_builder().

  if (isset($element['#after_build']) && !isset($element['#after_build_done'])) {
    foreach ($element['#after_build'] as $function) {
      $element = $function($element, $form_state);
    $element['#after_build_done'] = TRUE;

Differently from other cases, Drupal doesn't use function_exists() to check if the function exists. This means that using the following code works, since PHP 5.2.3.

$form['#after_build'][] = 'MyClass::_my_after_build_function';

As side note, it would work also with closures.

$build_function = function($element, $form_state) {
  // …

$form['#after_build'][] = $build_function;

I think your best bet is to call a function that will call


One way that won't work most likely.

$method_name = _my_after_build_function;  

Another shot in the dark that might work if using PHP 5.2.3+ http://php.net/manual/en/function.call-user-func.php.


You can try the above 2 methods but with a & in front of it. http://www.php.net/manual/en/language.references.pass.php

  • Creating a function that loads the method worked. Thank you. – Citricguy Dec 2 '11 at 23:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.